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): add vector layers and spline editing (#10281)

Valeri Che23880e57258a
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 cbd17f550f..6b676c97d4 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
@@ -1,7 +1,7 @@
---
title: Canvas guide
description: A detailed guide to the Canvas — its tools and their options, navigation, the header buttons, the generation frame, selections, transform, filters, the staging area, menus, settings and keyboard shortcuts.
-lastUpdated: 2026-10-29
+lastUpdated: 2026-11-15
---
import { Image } from 'astro:assets';
@@ -30,7 +30,8 @@ A tool that cannot change the selected layer says so instead of doing nothing: t
| **Generation frame** | **C** | Move and resize the generation frame. Tap **C** to switch to it, or hold **C** to use it briefly. |
| **Brush** | **B** | Paint on the selected raster layer, or paint a mask or region on the selected inpaint mask or regional guidance layer. **Shift**-click draws a straight line from the end of the last stroke on that layer. |
| **Eraser** | **E** | Erase paint or mask. **Shift**-click erases a straight line, as with the Brush. |
-| **Shape** | **U** | Draw a rectangle, ellipse, triangle, star, polygon or freehand shape on a raster layer, or add a shaped area to the selected inpaint mask or regional guidance layer. Press **U** again to cycle through the shapes. |
+| **Shape** | **U** | Draw a rectangle, ellipse, triangle, star, polygon or freehand shape on a raster layer, or add a shaped area to the selected inpaint mask or regional guidance layer. On a vector layer, draw editable paths instead of pixels. Press **U** again to cycle through the shapes. |
+| **Spline Edit** | **S** | Edit points, curves and individual paths on the selected vector layer. See [Vector layers and splines](#vector-layers-and-splines). |
| **Gradient** | **G** | Create a linear or radial gradient. |
| **Text** | **T** | Add editable text. |
| **Marquee select** / **Lasso select** | **M** / **L** | Select an area of pixels. Press **M** again to switch between rectangle and ellipse, or **L** again for freehand and polygon. |
@@ -51,11 +52,33 @@ A pick that changes a layer is one undoable step. Gradient stops are not picked
* **Eraser** — **Size**, **Opacity** and **Hardness**; and, under **Dynamics**, whether pen pressure affects the width. Pressure never changes how strongly the eraser erases.
The Brush, Eraser, Shape and Text options are remembered for your account, so they are the same in every project and after a reload. Colors are the project's own.
-* **Shape** — settings for the next shape: its **Kind**, a row of buttons showing each shape (point at one for its name), and **Place on**, which draws on the **Selected layer** or on a **New layer** of its own. Only a paint layer, an inpaint mask or a regional guidance layer takes shape pixels. With anything else selected, or nothing selected, **Selected layer** is unavailable and **New layer** shows where the shape will go; a note below explains why. Your placement preference returns when you select a paint layer or mask. Under the tool's **Appearance** group, **Fill**, **Stroke** and stroke **Width** set the next shape's defaults. To edit an existing shape's appearance, use the **Layer** section below the tool options; those controls stay available with any tool active and each gesture is one undoable step. **Shift** constrains the proportions, **Alt** draws from the center, and **Shift+Alt** does both. **Ctrl** (**Cmd** on macOS) cuts the shape out of the selected paint layer or mask instead of drawing it, whatever **Place on** says: it erases like the Eraser and never adds a layer. With no paint layer or mask selected, a notice says so and nothing is drawn. For polygons, click to place points and double-click, press **Enter** or click the first point to close the shape; **Escape** drops the points without drawing anything. With an inpaint mask or regional guidance layer selected, the shape is added to the mask or region, which makes shapes a quick way to mark rectangular or geometric areas; the colors are ignored.
+* **Shape** — settings for the next shape: its **Kind**, a row of buttons showing each shape (point at one for its name), and **Place on**, which draws on the **Selected layer** or on a **New layer** of its own. On a selected vector layer, Shape draws editable paths; see [Vector layers and splines](#vector-layers-and-splines). Only a paint layer, an inpaint mask or a regional guidance layer takes shape pixels. With any other non-vector layer selected, or nothing selected, **Selected layer** is unavailable and **New layer** shows where the shape will go; a note below explains why. Your placement preference returns when you select a paint layer or mask. Under the tool's **Appearance** group, **Fill**, **Stroke** and stroke **Width** set the next shape's defaults. To edit an existing shape's appearance, use the **Layer** section below the tool options; those controls stay available with any tool active and each gesture is one undoable step. **Shift** constrains the proportions, **Alt** draws from the center, and **Shift+Alt** does both. **Ctrl** (**Cmd** on macOS) cuts the shape out of the selected paint layer or mask instead of drawing it, whatever **Place on** says: it erases like the Eraser and never adds a layer. With no paint layer or mask selected, a notice says so and nothing is drawn. For polygons, click to place points and double-click, press **Enter** or click the first point to close the shape; **Escape** drops the points without drawing anything. With an inpaint mask or regional guidance layer selected, the shape is added to the mask or region, which makes shapes a quick way to mark rectangular or geometric areas; the colors are ignored.
* **Gradient** — **Kind** (Linear or Radial), **Angle**, and the color **Stops**, which can be added and removed or follow the foreground and background colors. Dragging creates a gradient layer the size of the generation frame, or repositions the selected gradient layer.
* **Text** — the font **Family**, **Style** or **Weight**, **Size**, **Line height**, **Align** and **Fill** color. Click the canvas to start typing; **Ctrl+Enter** or clicking elsewhere finishes the text, and **Escape** cancels it. The text stays editable as a text layer.
* **Marquee select** and **Lasso select** — the **Shape** and the selection **Mode** (Replace, Add, Subtract or Intersect). **Shift** adds to the selection and **Alt** subtracts from it. A polygon lasso closes like a polygon shape, and **Escape** drops its points while keeping the current selection. The **Actions** fill or erase the selection on the selected paint layer, image, control layer or mask (a mask gets full coverage), lift it to a **New layer**, **Invert** it, select everything, or **Deselect**.
+### Vector layers and splines
+
+Create a **Vector layer** from the **+** menu in the Layers panel, select it, then use **Shape** to draw paths. Vector paths are guides, not image pixels. You can change their **Guide color** in the layer's Properties if desired.
+
+Choose **Spline Edit** (**S**) from the Canvas toolbar and click a path or one of its control points to edit it. Drag a control point to move it, or drag its handles to reshape the curve on either side. **Shift**-click a curve to add a control point. **Ctrl**-click (**Cmd** on macOS) or drag a selection box to select multiple control points.
+
+In the tool's Properties, **Corner**, **Smooth** and **Symmetric** apply to the selected control points:
+
+* **Corner** lets each handle move independently, allowing a sharp corner.
+* **Smooth** keeps the two handles aligned, with independent lengths, for a smooth curve through the point.
+* **Symmetric** keeps the handles aligned and equal in length, so adjusting one mirrors the other.
+
+**Split** breaks a path at the selected control point; **Join** connects compatible selected endpoints. Under **Path**, the smoothing controls let you smooth the whole active path or only its selected control points. The remaining actions copy the active path, extract a copy to a new vector layer, or delete the path.
+
+Right-click an individual path on the selected vector layer, or select a path and press **Shift+F10** with the canvas focused, to access **Transform Path**, **Trace Path**, and **Fill Path** (closed paths only). These operations affect only the selected path, not the entire vector layer.
+
+To render the entire vector layer, choose **Trace/Fill** in the vector layer's Properties. **Fill** and **Stroke** determine whether this renders filled regions, traced lines, or both. **Trace Path** always traces the individual path; **Fill Path** fills the individual closed path.
+
+Both individual path operations and whole-layer rendering use the fill color, stroke color, **Stroke width**, and optional taper settings in the vector layer's Properties. These settings, along with the **Fill** and **Stroke** switches, are stored independently for each vector layer. Changing them does not change the Brush tool or other vector layers.
+
+Rendering creates a raster layer for generation and export while keeping the original vector paths editable.
+
### Fonts
The Text tool offers built-in font families, plus any fonts you add. To add fonts, open **Fonts** in the Launchpad and use **Add Fonts** to upload `.ttf`, `.otf`, `.woff` or `.woff2` files. Uploaded fonts are private to your account (**My fonts**); administrators can also upload shared fonts for everyone on the server. Select a font in the library to preview it and see its variation axes and named instances. Variable fonts expose those axes in the Text tool's options.
@@ -221,7 +244,8 @@ The tool keys, **Shift+T**, **[** and **]**, and **X** and **D** also work after
| Shortcut | Action |
|---|---|
-| **H**, **V**, **Shift+T**, **C**, **B**, **E**, **U**, **G**, **T**, **M**, **L**, **I** | Select a tool (see [Tools](#tools)) |
+| **H**, **V**, **Shift+T**, **C**, **B**, **E**, **U**, **S**, **G**, **T**, **M**, **L**, **I** | Select a tool (see [Tools](#tools)) |
+| **Shift+F10** | Open the active spline path menu while the canvas has focus |
| Hold **Space** | Pan temporarily |
| Hold **Alt** | Pick a color (with tools that do not use **Alt** themselves) |
| Hold / tap **C** | Use the generation frame tool until you let go / switch to it |
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index e1a85ace01..ba01e4092e 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -1183,6 +1183,10 @@
"Layers apply top to bottom, and each can carry a stack of non-destructive adjustments such as levels, curves, or hue."
]
},
+ "layerStackVector": {
+ "heading": "Vector Layers",
+ "paragraphs": ["Layers that hold editable vector guide paths."]
+ },
"layerStackRegionalGuidance": {
"heading": "Regional Guidance",
"paragraphs": [
@@ -4459,6 +4463,7 @@
"selectBrushTool": "Select brush tool",
"selectEraserTool": "Select eraser tool",
"selectGradientTool": "Select gradient tool",
+ "selectSplineTool": "Select spline editing tool",
"selectLassoTool": "Select lasso tool",
"selectMarqueeTool": "Select marquee tool",
"selectMoveTool": "Select move tool",
@@ -4732,6 +4737,8 @@
"shapeFreehand": "Freehand",
"shapeMaskHint": "Shapes add to the selected mask; fill and stroke set which parts, not their colors.",
"shapePolygon": "Polygon",
+ "vectorShapePolyline": "Polyline/Polygon",
+ "vectorPolylineHint": "Click to place points. Enter or double-click finishes an open path; click the first point to close it.",
"shapeRect": "Rectangle",
"shapeStar": "Star",
"shapeTarget": "Place on",
@@ -4765,6 +4772,7 @@
"frameLinked": "Linked to Generate’s size: the size and aspect lock are shared."
},
"tools": {
+ "spline": "Spline Edit",
"bbox": "Generation frame",
"brush": "Brush",
"colorPicker": "Color picker",
@@ -5070,6 +5078,7 @@
"addControlLayer": "Control layer",
"addInpaintMask": "Inpaint mask",
"addRasterLayer": "Raster layer",
+ "addVectorLayer": "Vector layer",
"addRegionalGuidance": "Regional guidance",
"addRegionalReferenceImage": "Regional reference image",
"actionFailed": "Layer action failed",
@@ -5749,7 +5758,8 @@
"control": "Control Layers",
"inpaint_mask": "Inpaint Masks",
"raster": "Raster Layers",
- "regional_guidance": "Regional Guidance"
+ "regional_guidance": "Regional Guidance",
+ "vector": "Vector Layers"
},
"maskFill": {
"color": "Fill color",
@@ -5841,6 +5851,7 @@
"shape": "Shape",
"text": "Text",
"regional_guidance": "Region",
+ "vector": "Vector layer",
"group": "Group"
},
"groupSummary_one": "{{count}} layer",
@@ -5848,9 +5859,67 @@
"groupEmpty": "Empty group",
"groupSelectedHint": "Select a layer inside this group to paint.",
"tree": "Layer tree",
+ "vector": {
+ "pathTitle": "Active Path",
+ "selectToolHint": "Select Spline Edit to edit points and handles.",
+ "selectVectorLayerHint": "Select an unlocked, visible vector layer to edit its curves.",
+ "guideColor": "Guide color",
+ "traceFill": "Trace/Fill",
+ "fillPath": "Fill Path",
+ "fillTitle": "Fill",
+ "fillColor": "Fill color",
+ "fillAll": "Fill closed paths",
+ "fillFailed": "Could not fill this layer. Finish the current gesture or operation and try again.",
+ "traceEmpty": "No paths or bounded regions to render.",
+ "traceTooComplex": "This layer is too complex to fill. Split it into smaller vector layers and try again.",
+ "traceOverBudget": "Not enough Canvas memory to create this result. Reduce its size and try again.",
+ "traceBusy": "Finish the current gesture or operation and try again.",
+ "traceTitle": "Trace",
+ "traceColor": "Trace color",
+ "strokeWidth": "Stroke width",
+ "taperEnds": "Taper ends",
+ "taper": "Taper",
+ "traceAll": "Trace all paths",
+ "tracePath": "Trace Path",
+ "traceFailed": "Could not trace this layer. Finish the current gesture or operation and try again.",
+ "transformPath": "Transform Path",
+ "extractPath": "Extract Path",
+ "extract": "Extract",
+ "pathActionUnavailable": "This path action has not been ported yet.",
+ "pointsTitle": "Points",
+ "pathPropertiesTitle": "Path",
+ "selectedPoints": "Selected points",
+ "smoothSelectedOnlyHint": "Apply smoothing only to selected points",
+ "copyPathButton": "Copy path",
+ "deletePathButton": "Delete path",
+ "deletePath": "Delete Path",
+ "deletePoints": "Delete points",
+ "edit": "Edit",
+ "apply": "Apply",
+ "cancel": "Cancel",
+ "reset": "Reset",
+ "undo": "Undo",
+ "redo": "Redo",
+ "corner": "Corner",
+ "smooth": "Smooth",
+ "symmetric": "Symmetric",
+ "smoothPath": "Smooth path",
+ "smoothPoints": "Smooth points",
+ "split": "Split",
+ "join": "Join",
+ "copy": "Copy Path",
+ "delete": "Delete",
+ "hint": "Drag points or handles. Drag empty space to select points; Ctrl/Cmd adds to selection. Shift-click a segment to insert a point.",
+ "unavailable": "Cannot edit right now. Check that the layer is visible and unlocked and finish any active operation.",
+ "exitTitle": "Finish editing vector paths?",
+ "exitBody": "Apply your changes, discard them, or continue editing.",
+ "discard": "Discard"
+ },
"summary": {
"referenceImages_one": "{{count}} reference image",
"referenceImages_other": "{{count}} reference images",
+ "vectorPaths_one": "{{count}} path",
+ "vectorPaths_other": "{{count}} paths",
"denoiseLimit": "Denoise ≤ {{value}}%",
"noise": "Noise {{value}}%"
},
diff --git a/invokeai/frontend/webv2/src/platform/ui/hints/hintRegistry.ts b/invokeai/frontend/webv2/src/platform/ui/hints/hintRegistry.ts
index 3242f63b5c..550d2ac4a7 100644
--- a/invokeai/frontend/webv2/src/platform/ui/hints/hintRegistry.ts
+++ b/invokeai/frontend/webv2/src/platform/ui/hints/hintRegistry.ts
@@ -46,6 +46,7 @@ export const FEATURE_HINTS = {
layerStackInpaintMask: {},
layerStackRaster: {},
layerStackRegionalGuidance: {},
+ layerStackVector: {},
loraWeight: {
href: 'https://support.invoke.ai/support/solutions/articles/151000159072-concepts-low-rank-adaptations-loras-',
},
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
index cc4bf52f54..e4eafe35c2 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
@@ -25,9 +25,21 @@ Port `dispatch()` returns whether named project's canvas identity changed. User-
Paint persistence clears dirty result only after intended layer accepts bitmap reference. Rejected update keeps dirty pixels for retry; layer or project deletion is terminal and discards obsolete persistence work. Rule applies equally to raster/control paint sources and paint-backed masks.
+## Vector runtime readiness
+
+The engine loads `vectorRuntime.ts` on the first vector-layer creation, Spline tool request, or explicit `layers.vectorEdit.prepare()`. That runtime owns editing, vector Shape sessions, guide rendering, and Trace/Fill geometry. Raster tools and ordinary document bounds stay synchronous and do not import it. `interaction.vectorToolsStatus` reports idle/loading/ready/failed; pending requests share one load, failures report through the engine notification port and an explicit request can retry.
+
+`canvas-operations/useCanvasEngine.ts` prepares saved vector documents before exposing an interactive engine, and withholds the handle while loading. Layer creation waits for readiness and checks the original document and active engine lifetime before returning its descriptor; a tool request also checks that no later tool superseded it. Cooldown cancels pending user intents, while a completed module remains reusable until disposal. A load completing after disposal creates no runtime state. Vector Properties, path menus and Spline settings load on demand through React boundaries.
+
## Document contract and hierarchy
-`CanvasDocumentContractV3` holds four stack forests, `document.stacks.{raster, control, regional_guidance, inpaint_mask}`. Each forest: top-first tree of leaves (unchanged v2 leaf contracts) and pass-through groups (`type: 'group'` with `id`, `name`, `isEnabled`, `isLocked`, optional overlay-only `isHidden`, `children`). Node belongs to exactly one stack, ids unique across document, groups nest at most ten levels deep, document holds at most 10,000 nodes. `selectedLayerId` may name leaf or group; leaf-only tools refuse a group rather than guess a descendant. Groups carry no opacity, blend mode, transform, or raster surface: they only organise leaves and gate their effective state. Loader refuses older document versions; nothing migrates them.
+Triangle and Star creation share their vertex geometry with raster Shapes in `math/shapeGeometry.ts`. Shape creation overlays share dashed styling and polyline vertex/closure markers through `render/rasterizers/shapeRasterizer.ts`; completed vector guides remain solid blue.
+
+Shapes on a selected vector layer use `tools/vectorShapeTool.ts`; other targets keep the raster Shapes behavior. Vector Rect/Oval drags commit closed Bezier paths, Polygon clicks continue until explicit open/closed completion, and Freehand fits an open path with the v6 geometry math. Selected/New target chooses appending a path or creating another vector layer. Previews remain engine-local until completion; a completed edit records one structural history entry through the vector config patch. `render/overlayFrame.ts` supplies committed, visible vector paths and creation previews to `render/vectorGuides.ts`, which projects control points into CSS space before drawing constant-width blue guides. Layer changes, document replacement, cancellation and real tool switches drop stale creation sessions. Tool-owned modifier hooks let Space move a box or pan during an unfinished polyline/freehand, and Alt center a box without selecting the color picker.
+
+Vector guide layers use `type: 'vector'` in the optional `document.stacks.vector` forest, between control and regional guidance in bottom-first order. Their `paths` contain named, explicitly open/closed Bezier paths with layer-local anchors and handles. They have no raster source or pixel extent and do not enter generation or raster exports. Creating a vector stack adopts Canvas schema 7; documents that have never used it omit the forest and retain their existing schema. Layer creation, selection, flags, grouping, duplication and removal use the same structural commands and history as other stacks; duplication also rekeys path IDs.
+
+`CanvasDocumentContractV3` holds stack forests, `document.stacks.{raster, control, vector, regional_guidance, inpaint_mask}` (the vector forest is optional). Each forest: top-first tree of leaves (unchanged v2 leaf contracts) and pass-through groups (`type: 'group'` with `id`, `name`, `isEnabled`, `isLocked`, optional overlay-only `isHidden`, `children`). Node belongs to exactly one stack, ids unique across document, groups nest at most ten levels deep, document holds at most 10,000 nodes. `selectedLayerId` may name leaf or group; leaf-only tools refuse a group rather than guess a descendant. Groups carry no opacity, blend mode, transform, or raster surface: they only organise leaves and gate their effective state. Loader refuses older document versions; nothing migrates them.
`document/documentIndex.ts` builds one index per `stacks` identity (parent, path, sibling index, document order, ancestor-effective enabled/locked/hidden per node). Selection and bbox edits keep `stacks` and cost no index. Value edit (transform, opacity, blend, name, source, config, or a flag) goes through `updateNodeValues`, which finds each edited node via index and copies only sibling arrays on its path (cost: sibling counts along edited paths, never the forest), so `stacks` changes; it then registers a derived index for new forests extending previous one, and records the edit's replaced nodes (before and after; ancestors rebuilt only for a new child array are not listed) against new forests: `byId` is a layered map reading through to previous index for every untouched id, `nodes` and `leaves` materialize only when a consumer reads them (`leaves` keeps identity when no leaf object changed), and only entries constructed are edited path plus subtree under a group whose flags changed. After eight derivations chain flattens onto its plain root: one override layer holding newest entry of every id chain touched, still pointing consumers at root's cached compile so flattening recompiles only what chain changed; only when overrides cover more than a quarter of root is a plain index rebuilt. So lookups read through at most nine layers; nothing older than root is retained. `document-model/documentModel.budget.test.ts` pins this at 10,000 nodes: leaf edit revisits and constructs `depth + 1` entries, compiles `depth + 1` semantic nodes (ancestors keep counts without walking subtrees) and one leaf, answers `lookupDocumentLeaf`/`lookupDocumentNodeState` without materializing node list; complete reducer → mirror value edit does same with no forest diff.
@@ -55,6 +67,8 @@ A paint bake, with or without smoothing, evaluates the whole adjustment stack in
`canvas-operations/` owns application workflows such as Filter and Select Object. Coordinators may depend on queues, uploads, model selection, narrow engine capabilities. Their stores are React-free and `useSyncExternalStore`-compatible; React adapters stay under `widgets/`.
+Non-owning engine lookup lives in `canvas-operations/engineRegistry.ts`. Gallery actions and invocation preparation query the process-wide default registry without constructing an engine or acquiring a lease. The registry owns leases, cooldown, disposal and account cleanup; isolated registries never replace the public lookup. `canvas-operations/operationAccess.ts` binds application operation capabilities to engines through a weak map.
+
Public engine handle splits into capability groups such as `CanvasDocumentCapability`, `CanvasExportCapability`, `CanvasLayerCapability`, `CanvasLifecycleCapability`, and interaction/store capabilities. Production consumers request smallest aggregate they need. `canvas-construction-private` rule in `src/architecture/dependencyPolicy.ts` limits full `CanvasEngine` type to `canvas-operations/createCanvasEngine.ts` and `canvas-operations/engineRegistry.ts`; tests may construct full-engine fakes. Unused `fflate` dependency removed.
`CanvasCoreStores` holds interaction state only. `canvas-operations` creates and owns Filter and Select Object snapshots; application-session state cannot leak into core store contract.
@@ -327,3 +341,33 @@ Real-Canvas2D suite verifies transformed composition, clipping, alpha and blend
- New application coordinator: place under `canvas-operations/`, acquire edit lease, capture through narrow document/export capabilities, own its session store and cancellation, publish through preview/layer capabilities.
Deterministic CI assertions use operation counters and byte totals. Wall-clock timing is informational only.
+
+Vector point editing is owned by `controllers/vectorEditingController.ts` and the dedicated `spline` tool. The toolbar uses Lucide SplinePointer as its last button; the working cursor is a crosshair. `vectorEditSession` stores point/path selection and in-flight gesture geometry only. Each completed gesture or command writes a structural vector-config edit into global history; there is no Apply/Cancel session or separate local undo stack. Escape cancels the current gesture and clears point selection, without leaving the tool. Layer changes retarget the tool to the selected editable vector layer; other layer types expose no editable geometry. Properties renders point commands through `layers.vectorEdit` and never edits geometry itself.
+
+Move always moves the whole selected layer. Shapes creates paths independently of the point tool. Whole vector layers use the existing Transform tool and Bezier content bounds: previews update the guide matrix, and Transform Apply records one layer-transform history step without rasterization. Switching away from the point tool cancels any unfinished gesture; completed edits are already saved.
+
+Spline context menus resolve anchor/curve hits in CSS viewport coordinates through `layers.vectorEdit.targetContextMenu`. The UI checks its captured layer/path against the live point-tool selection before running commands. Path deletion is separate from Delete-selection semantics; both use global history.
+
+Extract Path immediately copies the active spline into a new vector layer above the source, with a fresh path ID and preserved geometry/transform/appearance. Its stack-insertion command retains the selected source layer, active spline and selected points. It is one global history step, undoable without leaving the point tool.
+
+Spline point/topology controls are presented by `tool-options/SplineOptions.tsx` as the `spline` tool form. Vector layer Properties owns path count, optional `guideColor`, and Trace/Fill appearance settings. This display property is parsed by Canvas migration and patched through vector config edits; missing colors resolve to `DEFAULT_VECTOR_GUIDE_COLOR`. The existing structural preview/commit seam supplies live color preview and one history step. Overlay guide descriptors carry the color independently of point-selection chrome and raster compositing. Extract and layer duplication preserve it.
+
+The spline tool owns an optional active-path transform frame in `vectorEditSession.pathTransform`, reusing transformMath for hit testing and gestures. The controller holds immutable source geometry and applies the cumulative local transform to its anchors and handles. Frame chrome projects through the existing layer matrix; other contours and the layer contract transform stay unchanged. Completed gestures commit through ordinary vector-config history. Global document replays invalidate the frame; no separate transform tool or layer-level Apply/Cancel session is opened for a path.
+
+Vector layer Properties owns Trace controls. Stroke color and width, Fill/Stroke switches and colors, and optional traceTaperEnds/traceTaper config properties persist per layer. New layers store black strokes at 50 pixels. Appearance edits use structural preview/commit and global undo/redo. vectorTraceController samples Bezier curves and renders ordinary round strokes or v6-style tapered pressure outlines into layer-local paint pixels. It uses the standard mutation transaction and publishAddedRasterLayer for reserved allocation, atomic insertion, pixel persistence and global replay. The new raster layer inherits the vector transform; source geometry and display guide color are unaffected.
+
+Input reset releases tool-owned Space, Alt and Shift holds after restoring any temporary tool. This clears modifiers whose keyup was lost while the window was unfocused, including between polygon clicks.
+
+### Vector layer Trace/Fill and path-menu scope
+
+Layer Properties exposes Shapes-style Appearance rows with independent Fill/Stroke toggles and colors, stroke width, taper settings, and one Trace/Fill action. Fill defaults off and Stroke defaults on. The required `strokeColor` and `strokeWidth`, and optional `fillColor`, `fillEnabled`, `strokeEnabled`, `traceTaperEnds` and `traceTaper` properties persist on the vector layer. Trace Path, Fill Path and layer-wide Trace/Fill read that layer snapshot. Brush changes do not change vector appearance. New layers store black strokes at 50 pixels.
+
+Intersection-based filling belongs exclusively to the layer action. When Fill is enabled, `math/vectorFillRegions.ts` discovers bounded faces across all sampled paths in the active vector layer, including self-intersections and intersections between open paths. Free tails are excluded from filled areas; an isolated crossing does not create a region. Source paths are never closed, split or otherwise rewritten. Fill and optional strokes are published together into one raster layer with one global Undo/Redo step, preserving the selected vector layer on insertion and redo.
+
+The path context menu deliberately has narrower semantics: Trace Path strokes only the targeted path, while Fill Path fills only the targeted explicitly closed path (at least three points), using the layer fill color regardless of the Appearance toggles. It does not discover regions involving other curves. There is no context-menu Fill Region or cursor-based region selection.
+
+Region discovery runs only when the layer action executes, not when opening a context menu or moving points. It yields bounded work chunks to the browser and checks AbortSignal between chunks. Cancel or Escape interrupts it; document edits, engine cooldown and disposal abort pending work. Results are fenced against the captured document before admission and publication. The prototype uses 24 samples per Bezier segment, x-sorted bounding-box candidate rejection, segment splitting and directed planar-face traversal. Worst-case intersection work is quadratic, bounded by 24,000 input segments, 2,000,000 candidate comparisons and 120,000 directed edges. Exceeding a limit returns a distinct too-complex result instead of publishing partial output. Approximation can miss small features; gap snapping, coincident-segment repair, robust tangency handling and intentional holes are outside the current scope. Numerical endpoint coincidences may connect. Live Trace/Fill preview is not implemented.
+
+Trace/Fill capabilities return `Promise<VectorTraceResult>` with distinct empty, canceled/stale, busy, memory-budget and complexity outcomes. Properties offers Cancel while its request runs; the path menu closes immediately and reports actionable failures. Raster bounds include the tension curve control-point hull and actual taper outline. Geometry preparation is browser-independent; Path2D construction can be injected for recording tests.
+
+Spline editing reattaches to the selected vector layer when its engine activates after cooldown. Join eligibility and welding share viewport-distance semantics under non-uniform scales. The controller owns a bounded hit-test cache (50,000 retained samples, at most 64 path entries), invalidated by immutable path identity and projection; bounds reject distant curves before sampling, and per-segment sampling is capped at 128. Completed edit refusals restore committed geometry and notify; Shapes retains a refused draft for Enter retry, while Escape or a fresh press abandons it explicitly. The Move tool has no vector-editor delegation.
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/api.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/api.ts
index 9ecf71472f..6b7d7d1103 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/api.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/api.ts
@@ -7,6 +7,7 @@
*/
export * from './capabilities';
export { CONTROL_TYPES } from './contracts';
+export { DEFAULT_VECTOR_GUIDE_COLOR, DEFAULT_VECTOR_STROKE_COLOR, DEFAULT_VECTOR_STROKE_WIDTH } from './contracts';
export {
controlDetectionInputKey,
getControlDetectionInput,
@@ -15,4 +16,5 @@ export {
restoreControlOriginal,
} from './document/controlDerivation';
export { createControlLayer, type CreateControlLayerInput, nextControlLayerName } from './document/layerFactories';
+export { createVectorLayer, nextVectorLayerName } from './document/vectorLayerFactories';
export { shapeDrawsOnLayer } from './tools/shapeTarget';
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
index 2487f13864..1f816d6c44 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
@@ -13,7 +13,9 @@ import type {
import type { CanvasMutationOrigin } from '@workbench/canvas-engine/mutationContracts';
import type { StrokeCommittedEvent } from '@workbench/canvas-engine/tools/tool';
import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';
+import type { VectorEditSession } from '@workbench/canvas-engine/vectorEditState';
+import type { CanvasVectorLayerContract } from './contracts';
import type { BooleanRasterResult } from './controllers/booleanMergeController';
import type { CopyLayerResult } from './controllers/copyLayerController';
import type { CropAllLayersResult, CropLayerResult } from './controllers/cropLayerController';
@@ -190,6 +192,8 @@ export type CommitMaskImageResult = { status: 'committed'; layerId: string } | {
export type PsdExportStatus = 'idle' | 'preparing' | 'serializing' | 'downloading' | 'cancelling';
export interface CanvasInteractionState {
+ vectorEditSession: VectorEditSession | null;
+ vectorToolsStatus: 'idle' | 'loading' | 'ready' | 'failed';
psdExportStatus: PsdExportStatus;
activeTool: ToolId;
bboxGrid: number;
@@ -786,7 +790,46 @@ export type BeginTransformResult =
| 'ineligible'
| SubsetOf<CanvasTransactionOutcome, 'busy'>;
+export interface CanvasVectorEditCapability {
+ /** Loads vector support before exposing its synchronous editing commands. */
+ prepare(): Promise<boolean>;
+ createLayer(input: { id: string; name?: string }): Promise<CanvasVectorLayerContract | null>;
+ transformPath(): void;
+ extractPath(): void;
+ targetContextMenu(screenPoint: Vec2): boolean;
+ deletePath(): void;
+ nudge(dx: number, dy: number): void;
+ setPointType(type: 'corner' | 'smooth' | 'symmetric'): void;
+ smooth(selectedOnly: boolean): void;
+ deleteSelection(): void;
+ copyPath(): void;
+ split(): void;
+ join(): void;
+ canSplit(): boolean;
+ canJoin(): boolean;
+}
+
+export type VectorTraceResult = {
+ status:
+ | 'committed'
+ | 'empty'
+ | 'aborted'
+ | 'stale'
+ | 'too-complex'
+ | 'busy'
+ | 'gesture-active'
+ | 'not-ready'
+ | 'over-budget'
+ | 'failed';
+};
+
export interface CanvasEngineLayerCapability extends CanvasLayerCapability {
+ /** Omit pathId to trace all paths; otherwise trace only that exact curve using the layer's Trace settings. */
+ traceVectorLayer(layerId: string, pathId?: string): Promise<VectorTraceResult>;
+ traceFillVectorLayer(layerId: string): Promise<VectorTraceResult>;
+ fillVectorPath(layerId: string, pathId: string): Promise<VectorTraceResult>;
+ cancelVectorTrace(): void;
+ readonly vectorEdit: CanvasVectorEditCapability;
applyTransform(): void;
/**
* Selects `layerId`, switches to the transform tool and opens its session, even when transform is already active.
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts
index 6e6e9d1632..21f59bca54 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts
@@ -63,7 +63,7 @@ export interface CanvasStagingAreaContract {
areThumbnailsVisible: boolean;
}
-// Four top-first stack forests hold raster, control, regional guidance and inpaint nodes. Leaves use transforms
+// Top-first stack forests hold raster, control, vector, regional guidance and inpaint nodes. Leaves use transforms
// and stable image names, never ephemeral URLs. Groups gate descendant enabled, locked and hidden state.
export type CanvasBlendMode =
@@ -346,6 +346,39 @@ export interface CanvasRasterLayerContractV2 extends CanvasLayerBaseContract {
filter?: { type: string; settings: Record<string, unknown> };
}
+export interface CanvasBezierPointContract {
+ anchor: { x: number; y: number };
+ /** Layer-local coordinates, rather than offsets from the anchor. */
+ inHandle: { x: number; y: number } | null;
+ outHandle: { x: number; y: number } | null;
+ type: 'corner' | 'smooth' | 'symmetric';
+}
+
+export interface CanvasBezierPathContract {
+ id: string;
+ name: string | null;
+ isClosed: boolean;
+ points: CanvasBezierPointContract[];
+}
+
+/** Editable guide geometry; no raster source and no contribution to image generation. */
+export { DEFAULT_VECTOR_GUIDE_COLOR, DEFAULT_VECTOR_STROKE_COLOR, DEFAULT_VECTOR_STROKE_WIDTH } from './vectorDefaults';
+
+export interface CanvasVectorLayerContract extends CanvasLayerBaseContract {
+ type: 'vector';
+ paths: CanvasBezierPathContract[];
+ /** Display-only guide color; absent uses DEFAULT_VECTOR_GUIDE_COLOR. */
+ guideColor?: string;
+ fillColor?: string;
+ strokeColor: string;
+ strokeWidth: number;
+ fillEnabled?: boolean;
+ strokeEnabled?: boolean;
+ traceTaperEnds?: boolean;
+ traceTaper?: number;
+ isHidden?: boolean;
+}
+
/** What a control layer's image should control; a closed set, so an unknown value refuses the document. */
export const CONTROL_TYPES = ['pose', 'depth', 'edges', 'softedge', 'lineart', 'sketch', 'color', 'tile'] as const;
export type ControlType = (typeof CONTROL_TYPES)[number];
@@ -447,6 +480,7 @@ export interface CanvasInpaintMaskLayerContract extends CanvasLayerBaseContract
}
export type CanvasLayerContract =
+ | CanvasVectorLayerContract
| CanvasRasterLayerContractV2
| CanvasControlLayerContract
| CanvasRegionalGuidanceLayerContract
@@ -479,12 +513,16 @@ export interface CanvasGroupContract {
export type CanvasNodeContract = CanvasLayerContract | CanvasGroupContract;
/** One top-first forest per stack; a node's stack is the forest it lives in. */
-export type CanvasStackForests = Record<CanvasLayerStackKind, CanvasNodeContract[]>;
+export type CanvasStackForests = Record<Exclude<CanvasLayerStackKind, 'vector'>, CanvasNodeContract[]> & {
+ /** Absent until first used so projects without vectors retain their existing schema. */
+ vector?: CanvasNodeContract[];
+};
/** The composition order, bottom stack first; the one table every consumer reads. */
export const LAYER_STACK_ORDER: readonly CanvasLayerStackKind[] = [
'raster',
'control',
+ 'vector',
'regional_guidance',
'inpaint_mask',
];
@@ -498,12 +536,13 @@ export const CANVAS_MAX_NODE_COUNT = 10_000;
export interface CanvasDocumentContractV3 {
/**
* Schema this document needs: 3 for plain content, 4 for custom-font typography, 5 for noise or spatial
- * (clarity, texture, dehaze) adjustments, 6 for control-layer derivation fields. Each document mutation raises it to
- * the newer of its content's need and the canvas state's version. A restored snapshot's document keeps its own,
+ * (clarity, texture, dehaze) adjustments, 6 for control-layer derivation fields, 7 for vector geometry and
+ * layer appearance. Each mutation
+ * raises it to the newer of its content's need and the canvas state's version. A restored snapshot keeps its own,
* possibly lower, version until the next mutation; the state's version and the project's compatibility floor stay
* put meanwhile.
*/
- version: 3 | 4 | 5 | 6;
+ version: 3 | 4 | 5 | 6 | 7;
width: number;
height: number;
background: 'transparent' | { color: string };
@@ -545,10 +584,11 @@ export interface CanvasStagingAreaContractV2 extends CanvasStagingAreaContract {
export interface CanvasStateContractV3 {
/**
* Newest schema the state needs: the newest of its previous version, the live document's and every snapshot's
- * (3 plain, 4 custom-font typography, 5 noise or spatial adjustments, 6 control-layer derivation fields). Sticky:
+ * (3 plain, 4 custom-font typography, 5 noise or spatial adjustments, 6 control-layer derivation fields,
+ * 7 vector geometry and layer appearance). Sticky:
* removing that content never lowers it.
*/
- version: 3 | 4 | 5 | 6;
+ version: 3 | 4 | 5 | 6 | 7;
document: CanvasDocumentContractV3;
/**
* Monotonic wholesale-replacement counter. The mirror clears pixel history whenever it changes, including
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts
index 69ee3836d4..b36e30ea91 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts
@@ -123,6 +123,9 @@ const cropEligibility = (
* written by persistence once the cropped pixels land.
*/
const croppedLayerContract = (layer: CanvasLayerContract, rect: Rect): CanvasLayerContract => {
+ if (layer.type === 'vector') {
+ return layer;
+ }
const before = structuredClone(layer);
const identity = { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 };
const offset = { x: rect.x, y: rect.y };
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editSteps.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editSteps.ts
index 3d65effaba..7f8ce97fa5 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editSteps.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editSteps.ts
@@ -270,6 +270,8 @@ export interface AddedRasterLayerEdit {
readonly anchor: CanvasNodeInsertionAnchor;
/** The selection undo restores. */
readonly selectedLayerId: string | null;
+ /** Keep the existing selection when inserting and replaying this edit. Defaults to selecting the new layer. */
+ readonly preserveSelection?: boolean;
/** Enabled flags the edit sets on other layers, and the values undo restores. */
readonly enabled?: { readonly before: EnabledUpdates; readonly after: EnabledUpdates };
readonly heldAssetRefs?: HeldAssetRefs;
@@ -288,12 +290,13 @@ export const publishAddedRasterLayer = (
edit: AddedRasterLayerEdit
): EditPublishResult => {
const { anchor, layer, pixels, rect, selectedLayerId } = edit;
+ const nextSelectedLayerId = edit.preserveSelection ? selectedLayerId : layer.id;
const after = edit.enabled?.after ?? [];
const before = edit.enabled?.before ?? [];
const forward: CanvasProjectMutation = {
add: [{ anchor, nodes: [layer] }],
enabledUpdates: after,
- selectedLayerId: layer.id,
+ selectedLayerId: nextSelectedLayerId,
type: 'applyCanvasLayerStackMutation',
};
const inverse: CanvasProjectMutation = {
@@ -305,7 +308,7 @@ export const publishAddedRasterLayer = (
const hasEnabled = (document: CanvasDocumentContractV3 | null, updates: EnabledUpdates): boolean =>
updates.every((update) => getDocumentLayer(document, update.id)?.isEnabled === update.isEnabled);
const added = (document: CanvasDocumentContractV3 | null): boolean =>
- document?.selectedLayerId === layer.id &&
+ document?.selectedLayerId === nextSelectedLayerId &&
getDocumentLayer(document, layer.id) === layer &&
hasEnabled(document, after);
const removed = (document: CanvasDocumentContractV3 | null): boolean =>
@@ -333,3 +336,24 @@ export const publishAddedRasterLayer = (
ctx.applyStep({ accepted: removed, mutation: inverse, rollback: { mutation: forward, restored: added } }),
});
};
+
+/** Structural pair for a newly created vector layer. Callers choose whether insertion selects it. */
+export const addedVectorLayerMutations = (
+ layer: Extract<CanvasLayerContract, { type: 'vector' }>,
+ anchor: CanvasNodeInsertionAnchor,
+ selectedBefore: string | null,
+ selectNew = true
+): { forward: CanvasProjectMutation; inverse: CanvasProjectMutation } => ({
+ forward: {
+ type: 'applyCanvasLayerStackMutation',
+ enabledUpdates: [],
+ add: [{ anchor, nodes: [layer] }],
+ selectedLayerId: selectNew ? layer.id : selectedBefore,
+ },
+ inverse: {
+ type: 'applyCanvasLayerStackMutation',
+ enabledUpdates: [],
+ removeIds: [layer.id],
+ selectedLayerId: selectedBefore,
+ },
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/interactionController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/interactionController.test.ts
index 9899877ab8..86a460f780 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/interactionController.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/interactionController.test.ts
@@ -12,9 +12,13 @@ const createHarness = () => {
const updateCursor = vi.fn();
const invalidateOverlay = vi.fn();
const order: string[] = [];
- const beforeSwitch = vi.fn(() => order.push('beforeSwitch'));
+ const beforeSwitch = vi.fn(() => {
+ order.push('beforeSwitch');
+ });
const cancelGesture = vi.fn(() => order.push('cancelGesture'));
- vi.mocked(view.onDeactivate!).mockImplementation(() => order.push('view:deactivate'));
+ vi.mocked(view.onDeactivate!).mockImplementation(() => {
+ order.push('view:deactivate');
+ });
const stepBrushSize = vi.fn();
const controller = new InteractionController({
beforeSwitch,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/interactionController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/interactionController.ts
index b1ad828671..37b0bfde40 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/interactionController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/interactionController.ts
@@ -8,7 +8,7 @@ export interface InteractionControllerOptions {
readonly getToolContext: () => ToolContext;
/** Cancels an in-flight gesture through the still-active outgoing tool. */
readonly cancelGesture?: () => void;
- readonly beforeSwitch?: (from: ToolId, to: ToolId, options?: { temporary?: boolean }) => void;
+ readonly beforeSwitch?: (from: ToolId, to: ToolId, options?: { temporary?: boolean }) => void | boolean;
readonly publishActiveTool: (toolId: ToolId) => void;
readonly updateCursor: () => void;
readonly invalidateOverlay: () => void;
@@ -53,7 +53,9 @@ export class InteractionController {
}
}
const previous = this.activeToolId;
- this.options.beforeSwitch?.(previous, toolId, switchOptions);
+ if (this.options.beforeSwitch?.(previous, toolId, switchOptions) === false) {
+ return;
+ }
this.options.getTool(previous)?.onDeactivate?.(this.options.getToolContext(), switchOptions);
this.activeToolId = toolId;
this.options.getTool(toolId)?.onActivate?.(this.options.getToolContext(), switchOptions);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts
index 470fcd4462..21c68e2651 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts
@@ -273,7 +273,7 @@ export class LayerMutationController {
if (duplicate.source.type === 'paint') {
duplicate.source = { bitmap: null, type: 'paint' };
}
- } else {
+ } else if (duplicate.type === 'inpaint_mask' || duplicate.type === 'regional_guidance') {
duplicate.mask = { ...duplicate.mask, bitmap: null, offset: { x: 0, y: 0 } };
}
}
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 5e1093f7d5..0b84cd56ac 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.ts
@@ -126,7 +126,7 @@ export class TransformEditingController {
const document = this.deps.getDocument();
const leaf = lookupDocumentLeaf(document, layerId);
const layer = leaf?.layer;
- if (!document || !layer || !isLeafEditable(leaf) || !hittableLayerSize(layer, document)) {
+ if (!document || !layer || !this.deps.canEdit() || !isLeafEditable(leaf) || !hittableLayerSize(layer, document)) {
return;
}
this.cancel();
@@ -316,7 +316,7 @@ export class TransformEditingController {
!document ||
!layer ||
!size ||
- !isRenderableLayer(layer) ||
+ (layer.type !== 'vector' && !isRenderableLayer(layer)) ||
!isLeafEditable(lookupDocumentLeaf(document, session.layerId)) ||
unchanged(session.transform, session.startTransform)
) {
@@ -346,6 +346,7 @@ export class TransformEditingController {
const source = layer.type === 'raster' || layer.type === 'control' ? layer.source : null;
// A mask keeps its transform like an image, so its coverage is resampled only when composited, never baked.
if (
+ layer.type === 'vector' ||
isMaskLayer(layer) ||
source?.type === 'image' ||
source?.type === 'shape' ||
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/vectorEditingController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/vectorEditingController.test.ts
new file mode 100644
index 0000000000..08ea3d5dbf
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/vectorEditingController.test.ts
@@ -0,0 +1,271 @@
+import type { CanvasEditRefusal } from '@workbench/canvas-engine/capabilities';
+import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
+import type { ToolContext } from '@workbench/canvas-engine/tools/tool';
+import type { PointerInput } from '@workbench/canvas-engine/types';
+import type { VectorEditSession, VectorPointRef } from '@workbench/canvas-engine/vectorEditState';
+
+import { documentFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
+import { captureInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';
+import { createVectorLayer } from '@workbench/canvas-engine/document/vectorLayerFactories';
+import { anchorsToBezierPoints } from '@workbench/canvas-engine/math/bezierPath';
+import { createViewport } from '@workbench/canvas-engine/viewport';
+import { normalizeCanvasDocumentContract } from '@workbench/canvasMigration';
+import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';
+import { createInitialWorkbenchState } from '@workbench/workbenchState';
+import { describe, expect, it, vi } from 'vitest';
+
+import { VectorEditingController } from './vectorEditingController';
+
+const pointer = (x: number, y: number): PointerInput => ({
+ documentPoint: { x, y },
+ screenPoint: { x, y },
+ buttons: 1,
+ pressure: 0.5,
+ pointerType: 'mouse',
+ timeStamp: 0,
+ modifiers: { alt: false, shift: false, ctrl: false, meta: false },
+});
+const harness = () => {
+ const layer = createVectorLayer({ id: 'v', name: 'Vector' });
+ Object.assign(layer, {
+ guideColor: '#123456',
+ fillColor: '#abcdef',
+ fillEnabled: true,
+ strokeEnabled: false,
+ traceTaperEnds: true,
+ traceTaper: 250,
+ });
+ layer.paths = [
+ {
+ id: 'p',
+ name: null,
+ isClosed: false,
+ points: anchorsToBezierPoints([
+ { x: 0, y: 0 },
+ { x: 100, y: 0 },
+ { x: 100, y: 100 },
+ ]),
+ },
+ ];
+ let project = applyCanvasProjectMutation(createInitialWorkbenchState().projects[0]!, {
+ type: 'replaceCanvasDocument',
+ document: documentFrom([layer], layer.id),
+ });
+ let session: VectorEditSession | null = null,
+ refuse = false,
+ nextId = 0;
+ const edits: { forward: CanvasProjectMutation; inverse: CanvasProjectMutation }[] = [],
+ refusals: CanvasEditRefusal[] = [];
+ const viewport = createViewport();
+ const controller = new VectorEditingController({
+ session: {
+ get: () => session,
+ set: (value) => {
+ session = value;
+ },
+ },
+ getDocument: () => project.canvas.document,
+ canEdit: () => true,
+ isGestureActive: () => false,
+ getToolId: () => 'spline',
+ createId: () => `new-${++nextId}`,
+ invalidate: vi.fn(),
+ viewport,
+ reportRefusal: (reason) => refusals.push(reason),
+ captureInsertionAnchor: (id) =>
+ captureInsertionAnchor(project.canvas.document.stacks, {
+ projectId: project.id,
+ stack: 'vector',
+ editRevision: 0,
+ aboveId: id,
+ }),
+ commit: (_label, forward, inverse) => {
+ if (refuse) {
+ return { status: 'over-budget' };
+ }
+ edits.push({ forward, inverse });
+ project = applyCanvasProjectMutation(project, forward);
+ controller.onDocumentChanged();
+ return { status: 'committed' };
+ },
+ });
+ controller.onActivate();
+ const apply = (mutation: CanvasProjectMutation) => {
+ project = applyCanvasProjectMutation(project, mutation);
+ controller.onDocumentChanged();
+ };
+ return {
+ controller,
+ edits,
+ refusals,
+ state: () => session!,
+ document: () => project.canvas.document,
+ refuse: () => {
+ refuse = true;
+ },
+ apply,
+ select: (refs: VectorPointRef[]) => {
+ session = { ...session!, selectedPoints: refs };
+ controller.refreshAvailability();
+ },
+ selectEndpoints: () => {
+ session = {
+ ...session!,
+ selectedPoints: [
+ { pathId: 'p', pointIndex: 0 },
+ { pathId: 'p', pointIndex: 2 },
+ ],
+ };
+ controller.refreshAvailability();
+ },
+ };
+};
+
+describe('permanent vector editing', () => {
+ it('starts neutral, nudges a selected path through history, then clears activation on Escape', () => {
+ const h = harness();
+ expect(h.state().activePathId).toBeNull();
+ expect(h.controller.targetContextMenu({ x: 50, y: 0 })).toBe(true);
+ h.controller.nudge(10, 0);
+ expect(h.state().paths[0]!.points[0]!.anchor.x).toBe(10);
+ expect(h.edits).toHaveLength(1);
+ h.apply(h.edits[0]!.inverse);
+ expect(h.state().paths[0]!.points[0]!.anchor.x).toBe(0);
+ h.apply(h.edits[0]!.forward);
+ expect(h.state().paths[0]!.points[0]!.anchor.x).toBe(10);
+ h.controller.onKeyCommand({} as ToolContext, 'cancel');
+ expect(h.state().activePathId).toBeNull();
+ });
+ it('keeps the individual transform frame during nudge and cancels an unfinished point drag', () => {
+ const h = harness();
+ h.controller.targetContextMenu({ x: 50, y: 0 });
+ h.controller.transformPath();
+ h.controller.nudge(1, 10);
+ expect(h.state().pathTransform?.transform).toMatchObject({ x: 1, y: 10 });
+ expect(h.state().paths[0]!.points[0]!.anchor).toEqual({ x: 1, y: 10 });
+ h.controller.onKeyCommand({} as ToolContext, 'cancel');
+ h.controller.onPointerDown({} as ToolContext, pointer(1, 10));
+ h.controller.onPointerMove({ updateCursor: vi.fn() } as unknown as ToolContext, pointer(20, 20));
+ h.controller.onPointerCancel();
+ expect(h.state().paths[0]!.points[0]!.anchor).toEqual({ x: 1, y: 10 });
+ expect(h.edits).toHaveLength(1);
+ });
+ it('uses viewport distance consistently for three-point Join under non-uniform scaling', () => {
+ const h = harness();
+ const layer = h.document().stacks.vector![0]!;
+ if (layer.type !== 'vector') {
+ throw new Error('Expected vector');
+ }
+ h.apply({
+ type: 'updateCanvasLayerConfig',
+ id: layer.id,
+ config: {
+ layerType: 'vector',
+ paths: [
+ {
+ ...layer.paths[0]!,
+ points: anchorsToBezierPoints([
+ { x: 0, y: 0 },
+ { x: 5, y: 5 },
+ { x: 10, y: 0 },
+ ]),
+ },
+ ],
+ },
+ });
+ h.apply({
+ type: 'updateCanvasLayer',
+ id: layer.id,
+ patch: { transform: { ...layer.transform, scaleX: 100, scaleY: 0.01 } },
+ });
+ h.selectEndpoints();
+ expect(h.state().canJoin).toBe(true);
+ h.controller.join();
+ expect(h.state().paths[0]!.isClosed).toBe(true);
+ });
+ it('splits and rejoins endpoints, nudges only a selected point and replays history', () => {
+ const h = harness();
+ h.controller.targetContextMenu({ x: 100, y: 0 });
+ h.controller.nudge(0, 10);
+ expect(h.state().paths[0]!.points.map((point) => point.anchor)).toEqual([
+ { x: 0, y: 0 },
+ { x: 100, y: 10 },
+ { x: 100, y: 100 },
+ ]);
+ h.controller.split();
+ expect(h.state().paths).toHaveLength(2);
+ const [a, b] = h.state().paths;
+ h.select([
+ { pathId: a!.id, pointIndex: a!.points.length - 1 },
+ { pathId: b!.id, pointIndex: 0 },
+ ]);
+ expect(h.state().canJoin).toBe(true);
+ h.controller.join();
+ expect(h.state().paths).toHaveLength(1);
+ expect(h.state().paths[0]!.points).toHaveLength(3);
+ const last = h.edits.at(-1)!;
+ h.apply(last.inverse);
+ expect(h.state().paths).toHaveLength(2);
+ h.apply(last.forward);
+ expect(h.state().paths).toHaveLength(1);
+ });
+ it('disables three-point welding when endpoints are close on screen despite a large local distance', () => {
+ const h = harness(),
+ layer = h.document().stacks.vector![0]!;
+ if (layer.type !== 'vector') {
+ throw new Error('Expected vector');
+ }
+ h.apply({
+ type: 'updateCanvasLayerConfig',
+ id: 'v',
+ config: {
+ layerType: 'vector',
+ paths: [
+ {
+ ...layer.paths[0]!,
+ points: anchorsToBezierPoints([
+ { x: 0, y: 0 },
+ { x: 5, y: 5 },
+ { x: 0, y: 10 },
+ ]),
+ },
+ ],
+ },
+ });
+ h.apply({
+ type: 'updateCanvasLayer',
+ id: 'v',
+ patch: { transform: { ...layer.transform, scaleX: 100, scaleY: 0.01 } },
+ });
+ h.selectEndpoints();
+ expect(h.state().canJoin).toBe(false);
+ h.controller.join();
+ expect(h.edits).toHaveLength(0);
+ });
+ it('reports refused edits, restores committed geometry, and extracts a copy without retargeting', () => {
+ const h = harness();
+ h.apply({
+ type: 'updateCanvasLayerConfig',
+ id: 'v',
+ config: { layerType: 'vector', strokeColor: '#987654', strokeWidth: 19 },
+ });
+ h.controller.targetContextMenu({ x: 50, y: 0 });
+ h.controller.extractPath();
+ expect(h.document().selectedLayerId).toBe('v');
+ expect(h.document().stacks.vector).toHaveLength(2);
+ const copy = h.document().stacks.vector![0]!;
+ if (copy.type !== 'vector') {
+ throw new Error('Expected vector');
+ }
+ expect(copy).toMatchObject({ strokeColor: '#987654', strokeWidth: 19 });
+ expect(copy.paths[0]!.id).not.toBe('p');
+ expect(copy.paths[0]!.points).toEqual(h.state().paths[0]!.points);
+ const loaded = normalizeCanvasDocumentContract(JSON.parse(JSON.stringify(h.document())));
+ expect(loaded?.version).toBe(7);
+ expect(loaded?.stacks.vector?.[0]).toEqual(copy);
+ h.refuse();
+ h.controller.nudge(10, 0);
+ expect(h.refusals).toEqual(['over-budget']);
+ expect(h.state().paths[0]!.points[0]!.anchor.x).toBe(0);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/vectorEditingController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/vectorEditingController.ts
new file mode 100644
index 0000000000..9f19e6a1ef
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/vectorEditingController.ts
@@ -0,0 +1,995 @@
+import type { CanvasEditRefusal, StructuralCommitResult } from '@workbench/canvas-engine/capabilities';
+import type {
+ CanvasBezierPathContract,
+ CanvasBezierPointContract,
+ CanvasDocumentContractV3,
+ CanvasVectorLayerContract,
+} from '@workbench/canvas-engine/contracts';
+import type { CanvasNodeInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';
+import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
+import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';
+import type { LayerTransform, TransformTarget } from '@workbench/canvas-engine/transform/transformMath';
+import type { Mat2d, PointerInput, ToolId, Vec2 } from '@workbench/canvas-engine/types';
+import type { VectorEditSession, VectorPointRef } from '@workbench/canvas-engine/vectorEditState';
+import type { Viewport } from '@workbench/canvas-engine/viewport';
+
+import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';
+import { getDocumentIndex } from '@workbench/canvas-engine/document/documentIndex';
+import { leafEditRefusal } from '@workbench/canvas-engine/document/layerEligibility';
+import { createVectorLayer, nextVectorLayerName } from '@workbench/canvas-engine/document/vectorLayerFactories';
+import {
+ getBezierPathBounds,
+ transformBezierPath,
+ getBezierPointPullHandleType,
+ setBezierPointHandle,
+ setBezierPointType,
+ smoothBezierPathPoints,
+ splitBezierSegmentAt,
+} from '@workbench/canvas-engine/math/bezierPath';
+import { applyToPoint, getScale, invert, multiply } from '@workbench/canvas-engine/math/mat2d';
+import { vectorHandleLayout } from '@workbench/canvas-engine/math/vectorHandleLayout';
+import { VectorHitTestCache } from '@workbench/canvas-engine/math/vectorHitTest';
+import {
+ canJoinVectorPathEndpoints,
+ canSplitVectorPathAtPoints,
+ deleteVectorPathPoints,
+ joinVectorPathEndpoints,
+ splitVectorPathAtPoints,
+} from '@workbench/canvas-engine/math/vectorPathTopology';
+import {
+ applyMove,
+ applyRotate,
+ applyScale,
+ layerTransformMatrix,
+ resizeCursorForHandle,
+ transformTargetAt,
+} from '@workbench/canvas-engine/transform/transformMath';
+
+import { addedVectorLayerMutations } from './editSteps';
+
+interface Options {
+ session: { get(): VectorEditSession | null; set(value: VectorEditSession | null): void };
+ getDocument(): CanvasDocumentContractV3 | null;
+ canEdit(): boolean;
+ isGestureActive(): boolean;
+ getToolId(): ToolId;
+ commit(label: string, forward: CanvasProjectMutation, inverse: CanvasProjectMutation): StructuralCommitResult;
+ invalidate(): void;
+ reportRefusal?(refusal: CanvasEditRefusal): void;
+ createId(): string;
+ captureInsertionAnchor(layerId: string): CanvasNodeInsertionAnchor;
+ viewport: Viewport;
+}
+
+type Snapshot = Pick<VectorEditSession, 'paths' | 'activePathId' | 'selectedPoints'>;
+type Drag = {
+ before: Snapshot;
+ cancelBefore?: Snapshot;
+ start: Vec2;
+ screen: Vec2;
+ kind: 'anchor' | 'path' | 'pull' | 'maybe-pull' | 'inHandle' | 'outHandle' | 'rect';
+ ref?: VectorPointRef;
+ additive?: boolean;
+ missing?: 'inHandle' | 'outHandle';
+ handleOrigin?: Vec2;
+};
+const sameRef = (a: VectorPointRef, b: VectorPointRef): boolean =>
+ a.pathId === b.pathId && a.pointIndex === b.pointIndex;
+const distance = (a: Vec2, b: Vec2): number => Math.hypot(a.x - b.x, a.y - b.y);
+// Hit radii are CSS viewport pixels: project geometry through screenMatrix() before comparing.
+const ANCHOR_HIT_RADIUS_PX = 12;
+const HANDLE_HIT_RADIUS_PX = 12;
+const snapshot = (state: VectorEditSession): Snapshot => ({
+ paths: state.paths,
+ activePathId: state.activePathId,
+ selectedPoints: state.selectedPoints,
+});
+const samePaths = (a: CanvasBezierPathContract[], b: CanvasBezierPathContract[]): boolean =>
+ a === b || JSON.stringify(a) === JSON.stringify(b);
+
+/** Owns point selection and gesture previews; completed changes commit directly to document history. */
+export class VectorEditingController implements Tool {
+ readonly id = 'spline';
+ private base: CanvasVectorLayerContract | null = null;
+ private readonly hits = new VectorHitTestCache();
+ private drag: Drag | null = null;
+ private hoverPath = false;
+ private transformOrigin: CanvasBezierPathContract | null = null;
+ private transformDrag: { target: TransformTarget; start: Vec2; transform: LayerTransform; before: Snapshot } | null =
+ null;
+ private transformCursor: string | null = null;
+
+ constructor(private readonly options: Options) {}
+
+ hasSession = (): boolean => this.options.session.get() !== null;
+ private availability(state: VectorEditSession): Pick<VectorEditSession, 'canSplit' | 'canJoin'> {
+ return {
+ canSplit: canSplitVectorPathAtPoints(state.paths, state.selectedPoints),
+ canJoin: this.canJoinState(state),
+ };
+ }
+ private canJoinState(state: VectorEditSession): boolean {
+ if (!this.base) {
+ return false;
+ }
+ const matrix = this.screenMatrix();
+ return canJoinVectorPathEndpoints(state.paths, state.selectedPoints, 32, (point) => applyToPoint(matrix, point));
+ }
+ private reportRefusal(result: StructuralCommitResult): void {
+ const { status } = result;
+ if (status === 'committed') {
+ return;
+ }
+ this.options.reportRefusal?.(
+ status === 'busy' || status === 'gesture-active' || status === 'not-ready' || status === 'over-budget'
+ ? status
+ : 'not-ready'
+ );
+ }
+ refreshAvailability = (): void => {
+ const state = this.options.session.get();
+ if (!state || !this.base) {
+ return;
+ }
+ const next = this.availability(state);
+ if (next.canSplit !== state.canSplit || next.canJoin !== state.canJoin) {
+ this.publish(next);
+ }
+ };
+ private publish(patch: Partial<VectorEditSession>): void {
+ const state = this.options.session.get();
+ if (!state) {
+ return;
+ }
+ const next = { ...state, ...patch };
+ this.options.session.set({ ...next, ...this.availability(next) });
+ this.options.invalidate();
+ }
+
+ private record(keepTransform = false): void {
+ if (!keepTransform && this.options.session.get()?.pathTransform) {
+ this.transformOrigin = null;
+ this.publish({ pathTransform: null });
+ }
+ const state = this.options.session.get();
+ const base = this.base;
+ if (!state || !base || samePaths(base.paths, state.paths)) {
+ return;
+ }
+ this.base = { ...base, paths: state.paths };
+ const result = this.options.commit(
+ 'Edit vector paths',
+ {
+ type: 'updateCanvasLayerConfig',
+ id: base.id,
+ config: { layerType: 'vector', paths: state.paths },
+ },
+ { type: 'updateCanvasLayerConfig', id: base.id, config: { layerType: 'vector', paths: base.paths } }
+ );
+ if (result.status !== 'committed') {
+ this.reportRefusal(result);
+ this.base = base;
+ this.transformOrigin = null;
+ this.transformCursor = null;
+ this.publish({ paths: base.paths, selectedPoints: [], selectionRect: null, pathTransform: null });
+ }
+ }
+
+ private ready(): boolean {
+ return this.hasSession() && this.options.canEdit();
+ }
+ private actionReady(): boolean {
+ return this.ready() && !this.options.isGestureActive();
+ }
+ private matrix(): Mat2d {
+ return lookupDocumentLeaf(this.options.getDocument()!, this.base!.id)!.worldTransform;
+ }
+ private screenMatrix(): Mat2d {
+ return multiply(this.options.viewport.viewMatrix(1), this.matrix());
+ }
+
+ begin = (layerId: string): boolean => {
+ if (this.options.session.get()?.layerId === layerId) {
+ return true;
+ }
+ this.discard();
+ if (this.options.isGestureActive()) {
+ return false;
+ }
+ const doc = this.options.getDocument();
+ const leaf = doc ? lookupDocumentLeaf(doc, layerId) : null;
+ if (
+ !leaf ||
+ leaf.layer.type !== 'vector' ||
+ leaf.documentHidden ||
+ leafEditRefusal(leaf) ||
+ !invert(leaf.worldTransform)
+ ) {
+ return false;
+ }
+ this.base = leaf.layer;
+ const state: VectorEditSession = {
+ layerId,
+ paths: leaf.layer.paths,
+ activePathId: null,
+ selectedPoints: [],
+ selectionRect: null,
+ pathTransform: null,
+ canSplit: false,
+ canJoin: false,
+ };
+ this.options.session.set(state);
+ this.options.invalidate();
+ return true;
+ };
+
+ discard = (): void => {
+ this.base = null;
+ this.hits.clear();
+ this.drag = null;
+ this.hoverPath = false;
+ this.transformOrigin = null;
+ this.transformDrag = null;
+ this.transformCursor = null;
+ this.options.session.set(null);
+ this.options.invalidate();
+ };
+
+ onActivate = (): void => {
+ const id = this.options.getDocument()?.selectedLayerId;
+ if (id) {
+ this.begin(id);
+ }
+ };
+
+ onDocumentChanged = (): void => {
+ const doc = this.options.getDocument();
+ const state = this.options.session.get();
+ const leaf = doc?.selectedLayerId ? lookupDocumentLeaf(doc, doc.selectedLayerId) : null;
+ if (!leaf || leaf.layer.type !== 'vector' || leaf.documentHidden || leafEditRefusal(leaf)) {
+ if (state) {
+ this.discard();
+ }
+ return;
+ }
+ if (!state) {
+ if (this.options.getToolId() === 'spline') {
+ this.begin(leaf.id);
+ }
+ return;
+ }
+ if (state.layerId !== leaf.id) {
+ this.begin(leaf.id);
+ return;
+ }
+ if (leaf.layer.paths !== this.base?.paths || leaf.layer.transform !== this.base?.transform) {
+ this.drag = null;
+ this.transformDrag = null;
+ this.transformOrigin = null;
+ this.transformCursor = null;
+ this.base = leaf.layer;
+ const paths = leaf.layer.paths;
+ this.publish({
+ paths,
+ activePathId: paths.some((path) => path.id === state.activePathId) ? state.activePathId : null,
+ selectedPoints: state.selectedPoints.filter(
+ (ref) => !!paths.find((path) => path.id === ref.pathId)?.points[ref.pointIndex]
+ ),
+ selectionRect: null,
+ pathTransform: null,
+ });
+ }
+ };
+
+ private mapPoints(
+ paths: CanvasBezierPathContract[],
+ refs: VectorPointRef[],
+ edit: (point: CanvasBezierPointContract, ref: VectorPointRef) => void
+ ): CanvasBezierPathContract[] {
+ return paths.map((path) => {
+ const indices = refs.filter((ref) => ref.pathId === path.id);
+ if (indices.length === 0) {
+ return path;
+ }
+ const points = [...path.points];
+ for (const ref of indices) {
+ const point = points[ref.pointIndex];
+ if (!point) {
+ continue;
+ }
+ const copy = structuredClone(point);
+ edit(copy, ref);
+ points[ref.pointIndex] = copy;
+ }
+ return { ...path, points };
+ });
+ }
+ /** Arrow deltas are document pixels, independent of the layer's scale and rotation. */
+ nudge = (dx: number, dy: number): void => {
+ if (!this.actionReady() || !Number.isFinite(dx) || !Number.isFinite(dy) || (dx === 0 && dy === 0)) {
+ return;
+ }
+ const state = this.options.session.get()!;
+ if (!state.pathTransform && state.selectedPoints.length === 0 && state.activePathId === null) {
+ return;
+ }
+ const inverse = invert(this.matrix());
+ if (!inverse) {
+ return;
+ }
+ const x = inverse.a * dx + inverse.c * dy;
+ const y = inverse.b * dx + inverse.d * dy;
+ if (state.pathTransform) {
+ const frame = state.pathTransform;
+ const origin = this.transformOrigin;
+ if (!origin || origin.id !== frame.pathId) {
+ return;
+ }
+ const transform = { ...frame.transform, x: frame.transform.x + x, y: frame.transform.y + y };
+ const matrix = layerTransformMatrix(transform);
+ const path = transformBezierPath(origin, matrix);
+ this.publish({
+ paths: state.paths.map((candidate) => (candidate.id === frame.pathId ? path : candidate)),
+ pathTransform: { ...frame, transform },
+ });
+ this.record(true);
+ return;
+ }
+ const refs =
+ state.selectedPoints.length > 0
+ ? state.selectedPoints
+ : (state.paths.find((path) => path.id === state.activePathId)?.points ?? []).map((_, pointIndex) => ({
+ pathId: state.activePathId!,
+ pointIndex,
+ }));
+ this.publish({
+ paths: this.mapPoints(state.paths, refs, (point) => {
+ point.anchor = { x: point.anchor.x + x, y: point.anchor.y + y };
+ if (point.inHandle) {
+ point.inHandle = { x: point.inHandle.x + x, y: point.inHandle.y + y };
+ }
+ if (point.outHandle) {
+ point.outHandle = { x: point.outHandle.x + x, y: point.outHandle.y + y };
+ }
+ }),
+ });
+ this.record();
+ };
+ setPointType = (type: CanvasBezierPointContract['type']): void => {
+ if (!this.actionReady()) {
+ return;
+ }
+ const state = this.options.session.get()!;
+ this.publish({
+ paths: this.mapPoints(state.paths, state.selectedPoints, (point) => setBezierPointType(point, type)),
+ });
+ this.record();
+ };
+ smooth = (selectedOnly: boolean): void => {
+ if (!this.actionReady()) {
+ return;
+ }
+ const state = this.options.session.get()!;
+ const paths = state.paths.map((path) => {
+ const refs = state.selectedPoints.filter((ref) => ref.pathId === path.id);
+ if (selectedOnly ? refs.length === 0 : path.id !== state.activePathId) {
+ return path;
+ }
+ const smoothed = smoothBezierPathPoints(path.points, path.isClosed);
+ return {
+ ...path,
+ points: selectedOnly
+ ? path.points.map((point, index) => (refs.some((ref) => ref.pointIndex === index) ? smoothed[index]! : point))
+ : smoothed,
+ };
+ });
+ this.publish({ paths });
+ this.record();
+ };
+ deleteSelection = (): void => {
+ if (!this.actionReady()) {
+ return;
+ }
+ const state = this.options.session.get()!;
+ const paths =
+ state.selectedPoints.length > 0
+ ? deleteVectorPathPoints(state.paths, state.selectedPoints).paths
+ : state.paths.filter((path) => path.id !== state.activePathId);
+ this.publish({
+ paths,
+ selectedPoints: [],
+ activePathId: paths.some((path) => path.id === state.activePathId) ? state.activePathId : null,
+ });
+ this.record();
+ };
+ extractPath = (): void => {
+ if (!this.actionReady() || !this.base) {
+ return;
+ }
+ const state = this.options.session.get()!;
+ const base = this.base;
+ const path = state.paths.find((candidate) => candidate.id === state.activePathId);
+ const doc = this.options.getDocument();
+ const leaf = doc ? lookupDocumentLeaf(doc, base.id) : null;
+ if (
+ !path ||
+ !doc ||
+ !leaf ||
+ leaf.layer.type !== 'vector' ||
+ leaf.layer.paths !== base.paths ||
+ leaf.layer.transform !== base.transform ||
+ leaf.documentHidden ||
+ leafEditRefusal(leaf)
+ ) {
+ return;
+ }
+ const layer = createVectorLayer({
+ id: this.options.createId(),
+ name: nextVectorLayerName(getDocumentIndex(doc).nodes.map((entry) => entry.node.name)),
+ });
+ layer.paths = [{ ...structuredClone(path), id: this.options.createId() }];
+ layer.transform = { ...base.transform };
+ layer.opacity = leaf.layer.opacity;
+ layer.blendMode = leaf.layer.blendMode;
+ layer.guideColor = leaf.layer.guideColor;
+ layer.fillColor = leaf.layer.fillColor;
+ layer.strokeColor = leaf.layer.strokeColor;
+ layer.strokeWidth = leaf.layer.strokeWidth;
+ layer.fillEnabled = leaf.layer.fillEnabled;
+ layer.strokeEnabled = leaf.layer.strokeEnabled;
+ layer.traceTaperEnds = leaf.layer.traceTaperEnds;
+ layer.traceTaper = leaf.layer.traceTaper;
+ // Export the active draft version without committing or changing the source draft.
+ const mutations = addedVectorLayerMutations(
+ layer,
+ this.options.captureInsertionAnchor(base.id),
+ doc.selectedLayerId,
+ false
+ );
+ this.reportRefusal(this.options.commit('Extract vector path', mutations.forward, mutations.inverse));
+ };
+ copyPath = (): void => {
+ if (!this.actionReady()) {
+ return;
+ }
+ const state = this.options.session.get()!;
+ const index = state.paths.findIndex((path) => path.id === state.activePathId);
+ if (index < 0) {
+ return;
+ }
+ const copy = { ...structuredClone(state.paths[index]!), id: this.options.createId() };
+ const paths = [...state.paths];
+ paths.splice(index + 1, 0, copy);
+ this.publish({
+ paths,
+ activePathId: copy.id,
+ selectedPoints: copy.points.map((_, pointIndex) => ({ pathId: copy.id, pointIndex })),
+ });
+ this.record();
+ };
+ canSplit = (): boolean => {
+ const state = this.options.session.get();
+ return !!state && canSplitVectorPathAtPoints(state.paths, state.selectedPoints);
+ };
+ canJoin = (): boolean => {
+ const state = this.options.session.get();
+ return !!state && this.canJoinState(state);
+ };
+ split = (): void => {
+ if (!this.actionReady()) {
+ return;
+ }
+ const state = this.options.session.get()!;
+ if (!canSplitVectorPathAtPoints(state.paths, state.selectedPoints)) {
+ return;
+ }
+ let selected: VectorPointRef | null = null;
+ const paths = state.paths.flatMap((path) => {
+ const result = splitVectorPathAtPoints(
+ path,
+ state.selectedPoints.filter((ref) => ref.pathId === path.id).map((ref) => ref.pointIndex),
+ this.options.createId
+ );
+ if (!result) {
+ return [path];
+ }
+ selected = { pathId: result.activePathId, pointIndex: result.activePointIndex };
+ return result.paths;
+ });
+ this.publish({
+ paths,
+ activePathId: selected ? (selected as VectorPointRef).pathId : state.activePathId,
+ selectedPoints: selected ? [selected] : [],
+ });
+ this.record();
+ };
+ join = (): void => {
+ if (!this.actionReady()) {
+ return;
+ }
+ const state = this.options.session.get()!;
+ if (!this.canJoinState(state)) {
+ return;
+ }
+ const [from, to] = state.selectedPoints as [VectorPointRef, VectorPointRef];
+ const a = state.paths.find((path) => path.id === from.pathId)!;
+ const b = state.paths.find((path) => path.id === to.pathId)!;
+ const matrix = this.screenMatrix();
+ const weld =
+ distance(
+ applyToPoint(matrix, a.points[from.pointIndex]!.anchor),
+ applyToPoint(matrix, b.points[to.pointIndex]!.anchor)
+ ) <= 32;
+ const result = joinVectorPathEndpoints(a, from.pointIndex, b, to.pointIndex, weld);
+ if (!result) {
+ return;
+ }
+ const paths = state.paths.flatMap((path) => (path.id === a.id ? [result.path] : path.id === b.id ? [] : [path]));
+ this.publish({
+ paths,
+ activePathId: result.path.id,
+ selectedPoints: [{ pathId: result.path.id, pointIndex: result.activePointIndex }],
+ });
+ this.record();
+ };
+
+ transformPath = (): void => {
+ if (!this.actionReady()) {
+ return;
+ }
+ const state = this.options.session.get()!;
+ const path = state.paths.find((candidate) => candidate.id === state.activePathId);
+ if (!path || path.points.length < 2) {
+ return;
+ }
+ const bounds = getBezierPathBounds(path.points, path.isClosed);
+ this.transformOrigin = path;
+ this.transformCursor = null;
+ this.hoverPath = false;
+ this.publish({
+ selectedPoints: [],
+ pathTransform: {
+ pathId: path.id,
+ rect: { ...bounds, width: Math.max(1, bounds.width), height: Math.max(1, bounds.height) },
+ transform: { x: 0, y: 0, rotation: 0, scaleX: 1, scaleY: 1 },
+ },
+ });
+ };
+ private transformTarget(input: PointerInput): TransformTarget | null {
+ const frame = this.options.session.get()?.pathTransform;
+ if (!frame) {
+ return null;
+ }
+ const matrix = this.matrix();
+ return transformTargetAt({
+ point: input.screenPoint,
+ rect: frame.rect,
+ transform: frame.transform,
+ toScreen: (point) => this.options.viewport.documentToScreen(applyToPoint(matrix, point)),
+ });
+ }
+ private cursorForTransform(target: TransformTarget | null): string | null {
+ const frame = this.options.session.get()?.pathTransform;
+ if (!target || !frame) {
+ return null;
+ }
+ return target.kind === 'scale'
+ ? resizeCursorForHandle(
+ { ...frame.transform, rotation: frame.transform.rotation + (this.base?.transform.rotation ?? 0) },
+ target.handle
+ )
+ : target.kind === 'rotate'
+ ? 'grab'
+ : 'move';
+ }
+ cursor = (): string => this.transformCursor ?? (this.drag?.kind === 'path' || this.hoverPath ? 'move' : 'crosshair');
+ private updateHover(ctx: ToolContext, input: PointerInput): void {
+ const state = this.options.session.get();
+ let movable = false;
+ if (state && this.ready() && !input.modifiers.shift) {
+ const matrix = this.screenMatrix();
+ const scale = this.options.viewport.getZoom() * getScale(this.matrix());
+ const overAnchor = state.paths.some((path) =>
+ this.hits.hitAnchor(path, matrix, input.screenPoint, scale, ANCHOR_HIT_RADIUS_PX)
+ );
+ const overHandle = state.selectedPoints.some((ref) => {
+ const path = state.paths.find((path) => path.id === ref.pathId);
+ if (!path?.points[ref.pointIndex]) {
+ return false;
+ }
+ const handles = vectorHandleLayout(path, ref.pointIndex, matrix);
+ return [handles.inHandle, handles.outHandle].some(
+ (point) => !!point && distance(point, input.screenPoint) <= HANDLE_HIT_RADIUS_PX
+ );
+ });
+ movable =
+ !overAnchor &&
+ !overHandle &&
+ state.paths.some((path) => {
+ const hit = this.nearSegment(path, input);
+ return !!hit && hit.distance <= 10;
+ });
+ }
+ if (movable !== this.hoverPath) {
+ this.hoverPath = movable;
+ ctx.updateCursor();
+ }
+ }
+ private nearSegment(path: CanvasBezierPathContract, input: Pick<PointerInput, 'screenPoint'>) {
+ const matrix = this.screenMatrix();
+ return this.hits.find(path, matrix, input.screenPoint, this.options.viewport.getZoom() * getScale(this.matrix()));
+ }
+ targetContextMenu = (screenPoint: Vec2): boolean => {
+ if (!this.actionReady()) {
+ return false;
+ }
+ const state = this.options.session.get()!;
+ const matrix = this.screenMatrix();
+ let anchorHit: VectorPointRef | null = null;
+ let pathHit: string | null = null;
+ let anchorDistance = ANCHOR_HIT_RADIUS_PX;
+ let pathDistance = 10;
+ const paths = [
+ ...state.paths.filter((path) => path.id === state.activePathId),
+ ...state.paths.filter((path) => path.id !== state.activePathId),
+ ];
+ for (const path of paths) {
+ path.points.forEach((point, pointIndex) => {
+ const d = distance(applyToPoint(matrix, point.anchor), screenPoint);
+ if (d <= anchorDistance && (!anchorHit || d < anchorDistance)) {
+ anchorHit = { pathId: path.id, pointIndex };
+ anchorDistance = d;
+ }
+ });
+ const hit = this.nearSegment(path, { screenPoint });
+ if (hit && hit.distance <= pathDistance && (!pathHit || hit.distance < pathDistance)) {
+ pathHit = path.id;
+ pathDistance = hit.distance;
+ }
+ }
+ const ref = anchorHit as VectorPointRef | null;
+ const pathId = ref?.pathId ?? pathHit;
+ if (!pathId) {
+ return false;
+ }
+ if (state.pathTransform && state.pathTransform.pathId !== pathId) {
+ this.transformOrigin = null;
+ this.transformCursor = null;
+ this.publish({ pathTransform: null });
+ }
+ const selectedPoints = ref
+ ? state.selectedPoints.some((selected) => sameRef(selected, ref))
+ ? state.selectedPoints
+ : [ref]
+ : pathId === state.activePathId
+ ? state.selectedPoints
+ : [];
+ this.publish({ activePathId: pathId, selectedPoints });
+ return true;
+ };
+ deletePath = (): void => {
+ if (!this.actionReady()) {
+ return;
+ }
+ const state = this.options.session.get()!;
+ const paths = state.paths.filter((path) => path.id !== state.activePathId);
+ this.publish({
+ paths,
+ activePathId: paths[0]?.id ?? null,
+ selectedPoints: state.selectedPoints.filter((ref) => ref.pathId !== state.activePathId),
+ });
+ this.record();
+ };
+ onPointerDown = (_ctx: ToolContext, input: PointerInput): void => {
+ if (!this.ready() || (input.buttons & 1) === 0) {
+ return;
+ }
+ const state = this.options.session.get()!;
+ const inverse = invert(this.matrix())!;
+ const local = applyToPoint(inverse, input.documentPoint);
+ const matrix = this.screenMatrix();
+ if (state.pathTransform) {
+ const target = this.transformTarget(input);
+ if (target && this.transformOrigin) {
+ this.transformDrag = {
+ target,
+ start: local,
+ transform: state.pathTransform.transform,
+ before: snapshot(state),
+ };
+ this.transformCursor = this.cursorForTransform(target);
+ return;
+ }
+ this.transformOrigin = null;
+ this.transformCursor = null;
+ this.publish({ pathTransform: null });
+ }
+ const begin = (kind: Drag['kind'], refs: VectorPointRef[], ref?: VectorPointRef, missing?: Drag['missing']) => {
+ this.hoverPath = kind === 'path';
+ const activePathId = ref?.pathId ?? state.activePathId;
+ this.publish({ selectedPoints: refs, activePathId });
+ this.drag = {
+ kind,
+ before: snapshot(this.options.session.get()!),
+ start: local,
+ screen: input.screenPoint,
+ ref,
+ missing,
+ };
+ };
+ for (const ref of [...state.selectedPoints].reverse()) {
+ const path = state.paths.find((path) => path.id === ref.pathId);
+ const point = path?.points[ref.pointIndex];
+ if (!path || !point) {
+ continue;
+ }
+ const handles = vectorHandleLayout(path, ref.pointIndex, matrix);
+ for (const handle of ['inHandle', 'outHandle'] as const) {
+ const marker = handles[handle];
+ if (marker && distance(marker, input.screenPoint) <= HANDLE_HIT_RADIUS_PX) {
+ begin(handle, [...state.selectedPoints.filter((other) => !sameRef(ref, other)), ref], ref);
+ const origin = point[handle] ?? applyToPoint(invert(matrix)!, marker);
+ this.drag!.handleOrigin = origin;
+ if (!point[handle]) {
+ this.publish({
+ paths: this.mapPoints(state.paths, [ref], (copy) => setBezierPointHandle(copy, handle, origin)),
+ });
+ }
+ return;
+ }
+ }
+ }
+ const ordered = [
+ ...state.paths.filter((path) => path.id === state.activePathId),
+ ...state.paths.filter((path) => path.id !== state.activePathId),
+ ];
+ for (const path of ordered) {
+ for (let pointIndex = 0; pointIndex < path.points.length; pointIndex += 1) {
+ const point = path.points[pointIndex]!;
+ if (distance(applyToPoint(matrix, point.anchor), input.screenPoint) > ANCHOR_HIT_RADIUS_PX) {
+ continue;
+ }
+ const ref = { pathId: path.id, pointIndex };
+ const selected = state.selectedPoints.some((other) => sameRef(ref, other));
+ const refs =
+ input.modifiers.ctrl || input.modifiers.meta || selected
+ ? [...state.selectedPoints.filter((other) => !sameRef(ref, other)), ref]
+ : [ref];
+ const last = state.selectedPoints.at(-1);
+ const repeated = last && sameRef(last, ref) && refs.length === 1;
+ const missing =
+ point.type === 'corner' && Boolean(point.inHandle) !== Boolean(point.outHandle)
+ ? point.inHandle
+ ? 'outHandle'
+ : 'inHandle'
+ : undefined;
+ begin(
+ repeated && !point.inHandle && !point.outHandle ? 'pull' : repeated && missing ? 'maybe-pull' : 'anchor',
+ refs,
+ ref,
+ missing
+ );
+ return;
+ }
+ }
+ const active = state.paths.find((path) => path.id === state.activePathId);
+ if (input.modifiers.shift && active) {
+ const hit = this.nearSegment(active, input);
+ if (hit && hit.distance <= 10) {
+ const points = active.points.map((point) => structuredClone(point));
+ const from = points[hit.segmentIndex]!;
+ const to = points[(hit.segmentIndex + 1) % points.length]!;
+ const split = splitBezierSegmentAt(from, to, hit.t);
+ from.outHandle = split.fromOutHandle;
+ to.inHandle = split.toInHandle;
+ const ref = { pathId: active.id, pointIndex: hit.segmentIndex + 1 };
+ points.splice(ref.pointIndex, 0, split.insertPoint);
+ this.publish({
+ paths: state.paths.map((path) => (path.id === active.id ? { ...path, points } : path)),
+ selectedPoints: [ref],
+ });
+ this.drag = {
+ kind: 'anchor',
+ before: snapshot(this.options.session.get()!),
+ cancelBefore: snapshot(state),
+ start: local,
+ screen: input.screenPoint,
+ ref,
+ };
+ return;
+ }
+ }
+ for (const path of ordered) {
+ const hit = this.nearSegment(path, input);
+ if (hit && hit.distance <= 10) {
+ begin('path', [], { pathId: path.id, pointIndex: 0 });
+ return;
+ }
+ }
+ const additive = input.modifiers.ctrl || input.modifiers.meta;
+ this.hoverPath = false;
+ this.drag = {
+ kind: 'rect',
+ before: snapshot(state),
+ start: input.documentPoint,
+ screen: input.screenPoint,
+ additive,
+ };
+ this.publish({
+ activePathId: additive ? state.activePathId : null,
+ selectedPoints: additive ? state.selectedPoints : [],
+ selectionRect: { ...input.documentPoint, width: 0, height: 0 },
+ });
+ };
+
+ onPointerMove = (ctx: ToolContext, input: PointerInput): void => {
+ const frame = this.options.session.get()?.pathTransform;
+ if (frame && this.ready()) {
+ const gesture = this.transformDrag;
+ if (!gesture || !this.transformOrigin) {
+ const cursor = this.cursorForTransform(this.transformTarget(input));
+ if (cursor !== this.transformCursor) {
+ this.transformCursor = cursor;
+ ctx.updateCursor();
+ }
+ return;
+ }
+ const pointer = applyToPoint(invert(this.matrix())!, input.documentPoint);
+ const args = {
+ rect: frame.rect,
+ start: gesture.transform,
+ startPointerDoc: gesture.start,
+ pointerDoc: pointer,
+ shift: input.modifiers.shift,
+ };
+ const transform =
+ gesture.target.kind === 'move'
+ ? applyMove(
+ gesture.transform,
+ { x: pointer.x - gesture.start.x, y: pointer.y - gesture.start.y },
+ input.modifiers.shift,
+ 0
+ )
+ : gesture.target.kind === 'scale'
+ ? applyScale({ ...args, handle: gesture.target.handle, alt: input.modifiers.alt, grid: 0 })
+ : applyRotate(args);
+ const matrix = layerTransformMatrix(transform);
+ const path = transformBezierPath(this.transformOrigin, matrix);
+ this.publish({
+ paths: gesture.before.paths.map((candidate) => (candidate.id === path.id ? path : candidate)),
+ pathTransform: { ...frame, transform },
+ });
+ return;
+ }
+ const drag = this.drag;
+ if (!drag) {
+ this.updateHover(ctx, input);
+ return;
+ }
+ if (!this.ready()) {
+ return;
+ }
+ if (drag.kind === 'rect') {
+ const x = Math.min(drag.screen.x, input.screenPoint.x),
+ y = Math.min(drag.screen.y, input.screenPoint.y);
+ const width = Math.abs(input.screenPoint.x - drag.screen.x),
+ height = Math.abs(input.screenPoint.y - drag.screen.y);
+ const matrix = this.screenMatrix();
+ const refs = drag.before.paths.flatMap((path) =>
+ path.points.flatMap((point, pointIndex) => {
+ const p = applyToPoint(matrix, point.anchor);
+ return p.x >= x && p.x <= x + width && p.y >= y && p.y <= y + height ? [{ pathId: path.id, pointIndex }] : [];
+ })
+ );
+ const selectedPoints = drag.additive
+ ? [
+ ...drag.before.selectedPoints,
+ ...refs.filter((ref) => !drag.before.selectedPoints.some((old) => sameRef(old, ref))),
+ ]
+ : refs;
+ this.publish({
+ selectedPoints,
+ activePathId: selectedPoints.at(-1)?.pathId ?? (drag.additive ? drag.before.activePathId : null),
+ selectionRect: {
+ x: Math.min(drag.start.x, input.documentPoint.x),
+ y: Math.min(drag.start.y, input.documentPoint.y),
+ width: Math.abs(input.documentPoint.x - drag.start.x),
+ height: Math.abs(input.documentPoint.y - drag.start.y),
+ },
+ });
+ return;
+ }
+ const ref = drag.ref!;
+ const path = drag.before.paths.find((candidate) => candidate.id === ref.pathId)!;
+ const point = path.points[ref.pointIndex]!;
+ const local = applyToPoint(invert(this.matrix())!, input.documentPoint);
+ if (distance(drag.screen, input.screenPoint) < 3 && !drag.handleOrigin) {
+ this.publish({ paths: drag.before.paths });
+ return;
+ }
+ if (drag.kind === 'maybe-pull') {
+ const handle = point[drag.missing === 'inHandle' ? 'outHandle' : 'inHandle']!;
+ const dot =
+ (local.x - point.anchor.x) * (handle.x - point.anchor.x) +
+ (local.y - point.anchor.y) * (handle.y - point.anchor.y);
+ drag.kind = dot < 0 ? drag.missing! : 'anchor';
+ }
+ if (drag.kind === 'anchor' || drag.kind === 'path') {
+ const dx = local.x - drag.start.x,
+ dy = local.y - drag.start.y;
+ const refs =
+ drag.kind === 'path'
+ ? path.points.map((_, pointIndex) => ({ pathId: path.id, pointIndex }))
+ : drag.before.selectedPoints;
+ this.publish({
+ paths: this.mapPoints(drag.before.paths, refs, (copy) => {
+ copy.anchor = { x: copy.anchor.x + dx, y: copy.anchor.y + dy };
+ if (copy.inHandle) {
+ copy.inHandle = { x: copy.inHandle.x + dx, y: copy.inHandle.y + dy };
+ }
+ if (copy.outHandle) {
+ copy.outHandle = { x: copy.outHandle.x + dx, y: copy.outHandle.y + dy };
+ }
+ }),
+ });
+ } else {
+ const handle =
+ drag.kind === 'pull'
+ ? getBezierPointPullHandleType(path.points, path.isClosed, ref.pointIndex, local)
+ : drag.kind === 'inHandle'
+ ? 'inHandle'
+ : 'outHandle';
+ const target = drag.handleOrigin
+ ? { x: drag.handleOrigin.x + local.x - drag.start.x, y: drag.handleOrigin.y + local.y - drag.start.y }
+ : local;
+ this.publish({
+ paths: this.mapPoints(drag.before.paths, [ref], (copy) => setBezierPointHandle(copy, handle, target)),
+ });
+ }
+ };
+ onPointerUp = (): void => {
+ if (this.transformDrag) {
+ this.transformDrag = null;
+ this.record(true);
+ return;
+ }
+ if (!this.drag) {
+ return;
+ }
+ this.drag = null;
+ this.publish({ selectionRect: null });
+ this.record();
+ };
+ onPointerCancel = (): void => {
+ if (this.transformDrag) {
+ const gesture = this.transformDrag;
+ this.transformDrag = null;
+ const frame = this.options.session.get()?.pathTransform;
+ this.publish({
+ ...gesture.before,
+ ...(frame ? { pathTransform: { ...frame, transform: gesture.transform } } : {}),
+ });
+ }
+ if (this.drag) {
+ const before = this.drag.cancelBefore ?? this.drag.before;
+ this.drag = null;
+ this.publish({ ...before, selectionRect: null });
+ }
+ };
+ onDeactivate = (_ctx: ToolContext, options?: { temporary?: boolean }): void => {
+ this.onPointerCancel();
+ if (!options?.temporary) {
+ this.discard();
+ }
+ };
+ onKeyCommand = (_ctx: ToolContext, command: 'apply' | 'cancel'): boolean => {
+ if (!this.hasSession() || command !== 'cancel') {
+ return false;
+ }
+ this.onPointerCancel();
+ this.transformOrigin = null;
+ this.transformCursor = null;
+ this.publish({ activePathId: null, selectedPoints: [], selectionRect: null, pathTransform: null });
+ return true;
+ };
+}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/vectorTraceController.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/vectorTraceController.browser.test.ts
new file mode 100644
index 0000000000..3558475fa0
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/vectorTraceController.browser.test.ts
@@ -0,0 +1,198 @@
+import { documentFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
+import { stackTopAnchor } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
+import { createVectorLayer } from '@workbench/canvas-engine/document/vectorLayerFactories';
+import { anchorsToBezierPoints } from '@workbench/canvas-engine/math/bezierPath';
+import { createDomRasterBackend } from '@workbench/canvas-engine/render/raster';
+import { describe, expect, it } from 'vitest';
+
+import { createLayerOperationHarness } from './layerOperationHarness.testing';
+import { traceVectorLayer } from './vectorTraceController';
+
+describe('vector Trace/Fill pixels', () => {
+ it('fills an intersecting open path without painting its tails and retains vector geometry', async () => {
+ const layer = createVectorLayer({ id: 'v', name: 'Vector' });
+ layer.fillEnabled = true;
+ layer.strokeEnabled = false;
+ layer.fillColor = '#ff0000';
+ layer.paths = [
+ {
+ id: 'p',
+ name: null,
+ isClosed: false,
+ points: anchorsToBezierPoints([
+ { x: -20, y: -20 },
+ { x: 20, y: 20 },
+ { x: -20, y: 20 },
+ { x: 20, y: -20 },
+ ]),
+ },
+ ];
+ const h = createLayerOperationHarness(documentFrom([layer], 'v'), { backend: createDomRasterBackend() });
+ const doc = h.document();
+ try {
+ expect(
+ await traceVectorLayer({
+ document: doc,
+ layerId: 'v',
+ appearance: true,
+
+ ctx: h.ctx,
+ backend: h.backend,
+ id: 'output',
+ anchor: stackTopAnchor(h.ctx.projectId),
+ isCurrent: () => h.document() === doc,
+ })
+ ).toEqual({ status: 'committed' });
+ const entry = h.installed[0]!;
+ const rgba = (x: number, y: number) =>
+ Array.from(
+ entry.surface.ctx.getImageData(Math.round(x - entry.rect.x), Math.round(y - entry.rect.y), 1, 1).data
+ );
+ expect(rgba(0, 10)).toEqual([255, 0, 0, 255]);
+ expect(rgba(0, -10)[3]).toBe(0);
+ expect(h.document().stacks.vector).toBe(doc.stacks.vector);
+ expect(h.document().selectedLayerId).toBe('v');
+ } finally {
+ h.ctx.dispose();
+ h.layers.dispose();
+ }
+ });
+ it('renders independent fill and stroke colors and tapers an open stroke', async () => {
+ const layer = createVectorLayer({ id: 'v', name: 'Vector' });
+ layer.fillEnabled = true;
+ layer.fillColor = '#00ff00';
+ layer.strokeColor = '#0000ff';
+ layer.strokeWidth = 8;
+ layer.paths = [
+ {
+ id: 'p',
+ name: null,
+ isClosed: true,
+ points: anchorsToBezierPoints([
+ { x: 0, y: 0 },
+ { x: 100, y: 0 },
+ { x: 100, y: 100 },
+ { x: 0, y: 100 },
+ ]),
+ },
+ ];
+ const h = createLayerOperationHarness(documentFrom([layer], 'v'), { backend: createDomRasterBackend() });
+ const doc = h.document();
+ try {
+ expect(
+ (
+ await traceVectorLayer({
+ document: doc,
+ layerId: 'v',
+ appearance: true,
+
+ ctx: h.ctx,
+ backend: h.backend,
+ id: 'output',
+ anchor: stackTopAnchor(h.ctx.projectId),
+ isCurrent: () => h.document() === doc,
+ })
+ ).status
+ ).toBe('committed');
+ const entry = h.installed[0]!;
+ const pixel = (x: number, y: number) =>
+ Array.from(entry.surface.ctx.getImageData(x - entry.rect.x, y - entry.rect.y, 1, 1).data);
+ expect(pixel(50, 50)).toEqual([0, 255, 0, 255]);
+ expect(pixel(0, 50)).toEqual([0, 0, 255, 255]);
+ } finally {
+ h.ctx.dispose();
+ h.layers.dispose();
+ }
+ layer.fillEnabled = false;
+ layer.traceTaperEnds = true;
+ layer.strokeWidth = 20;
+ layer.paths = [
+ {
+ id: 'line',
+ name: null,
+ isClosed: false,
+ points: anchorsToBezierPoints([
+ { x: 0, y: 0 },
+ { x: 100, y: 0 },
+ ]),
+ },
+ ];
+ const tapered = createLayerOperationHarness(documentFrom([layer], 'v'), { backend: createDomRasterBackend() });
+ const before = tapered.document();
+ try {
+ expect(
+ (
+ await traceVectorLayer({
+ document: before,
+ layerId: 'v',
+
+ ctx: tapered.ctx,
+ backend: tapered.backend,
+ id: 'taper',
+ anchor: stackTopAnchor(tapered.ctx.projectId),
+ isCurrent: () => tapered.document() === before,
+ })
+ ).status
+ ).toBe('committed');
+ const entry = tapered.installed[0]!;
+ const alpha = (x: number) => entry.surface.ctx.getImageData(x - entry.rect.x, -entry.rect.y, 1, 1).data[3]!;
+ expect(alpha(50)).toBe(255);
+ expect(alpha(1)).toBeLessThan(alpha(50));
+ } finally {
+ tapered.ctx.dispose();
+ tapered.layers.dispose();
+ }
+ });
+});
+
+it('uses each layer’s stroke color and width for individual path rendering', async () => {
+ const paths = [
+ {
+ id: 'line',
+ name: null,
+ isClosed: false,
+ points: anchorsToBezierPoints([
+ { x: 0, y: 0 },
+ { x: 100, y: 0 },
+ ]),
+ },
+ ];
+ const thin = { ...createVectorLayer({ id: 'thin', name: 'Thin' }), paths, strokeColor: '#ff0000', strokeWidth: 4 };
+ const thick = {
+ ...createVectorLayer({ id: 'thick', name: 'Thick' }),
+ paths,
+ strokeColor: '#0000ff',
+ strokeWidth: 20,
+ };
+ for (const [id, expected, edgeAlpha] of [
+ ['thin', [255, 0, 0, 255], 0],
+ ['thick', [0, 0, 255, 255], 255],
+ ] as const) {
+ const h = createLayerOperationHarness(documentFrom([thin, thick], id), {
+ backend: createDomRasterBackend(),
+ });
+ const document = h.document();
+ try {
+ expect(
+ await traceVectorLayer({
+ document,
+ layerId: id,
+ pathId: 'line',
+ ctx: h.ctx,
+ backend: h.backend,
+ id: 'raster',
+ anchor: stackTopAnchor(h.ctx.projectId),
+ isCurrent: () => h.document() === document,
+ })
+ ).toEqual({ status: 'committed' });
+ const entry = h.installed[0]!;
+ const pixel = (y: number) =>
+ Array.from(entry.surface.ctx.getImageData(50 - entry.rect.x, y - entry.rect.y, 1, 1).data);
+ expect(pixel(0)).toEqual(expected);
+ expect(pixel(4)[3]).toBe(edgeAlpha);
+ } finally {
+ h.ctx.dispose();
+ h.layers.dispose();
+ }
+ }
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/vectorTraceController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/vectorTraceController.test.ts
new file mode 100644
index 0000000000..dbe2919735
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/vectorTraceController.test.ts
@@ -0,0 +1,93 @@
+import { documentFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
+import { stackTopAnchor } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
+import { createVectorLayer } from '@workbench/canvas-engine/document/vectorLayerFactories';
+import { anchorsToBezierPoints, approximateBezierPath } from '@workbench/canvas-engine/math/bezierPath';
+import { getTraceLineBounds } from '@workbench/canvas-engine/math/vectorTrace';
+import { describe, expect, it } from 'vitest';
+
+import { createLayerOperationHarness } from './layerOperationHarness.testing';
+import { traceVectorLayer } from './vectorTraceController';
+
+const setup = (historyBytes?: number) => {
+ const layer = createVectorLayer({ id: 'v', name: 'Vector' });
+ layer.paths = [
+ {
+ id: 'p',
+ name: null,
+ isClosed: true,
+ points: anchorsToBezierPoints([
+ { x: 0, y: 0 },
+ { x: 100, y: 0 },
+ { x: 100, y: 100 },
+ ]),
+ },
+ ];
+ layer.fillEnabled = true;
+ layer.strokeEnabled = true;
+ layer.fillColor = '#ff0000';
+ layer.strokeWidth = 4;
+ const h = createLayerOperationHarness(documentFrom([layer], 'v'), { historyBytes });
+ const doc = h.document();
+ const createPath = () =>
+ ({ moveTo() {}, lineTo() {}, closePath() {}, quadraticCurveTo() {}, bezierCurveTo() {} }) as unknown as Path2D;
+ const run = (signal?: AbortSignal, isCurrent = () => h.document() === doc) =>
+ traceVectorLayer({
+ document: doc,
+ layerId: 'v',
+ appearance: true,
+
+ id: 'output',
+ ctx: h.ctx,
+ backend: h.backend,
+ anchor: stackTopAnchor(h.ctx.projectId),
+ signal,
+ isCurrent,
+ createPath,
+ });
+ return { h, doc, run };
+};
+describe('vector trace transaction', () => {
+ it('publishes one raster while preserving selection, supports Undo/Redo and releases reservations', async () => {
+ const { h, doc, run } = setup();
+ expect(await run()).toEqual({ status: 'committed' });
+ expect(h.document().selectedLayerId).toBe('v');
+ expect(h.document().stacks.raster[0]?.id).toBe('output');
+ expect(h.document().stacks.vector).toBe(doc.stacks.vector);
+ expect(h.reservedBytes()).toBe(0);
+ await h.history.undo();
+ expect(h.document().stacks.raster).toHaveLength(0);
+ await h.history.redo();
+ expect(h.document().stacks.raster[0]?.id).toBe('output');
+ expect(h.document().selectedLayerId).toBe('v');
+ });
+ it('does not publish or retain allocations after cancel, stale input or budget refusal', async () => {
+ const a = setup(),
+ controller = new AbortController(),
+ pending = a.run(controller.signal);
+ controller.abort();
+ expect(await pending).toEqual({ status: 'aborted' });
+ expect(a.h.installed).toHaveLength(0);
+ expect(a.h.reservedBytes()).toBe(0);
+ const b = setup();
+ let current = true;
+ const stale = b.run(undefined, () => current);
+ current = false;
+ expect(await stale).toEqual({ status: 'stale' });
+ expect(b.h.installed).toHaveLength(0);
+ const c = setup(1);
+ expect(await c.run()).toEqual({ status: 'over-budget' });
+ expect(c.h.reservedBytes()).toBe(0);
+ });
+ it('bounds tension control points rather than only the original samples', () => {
+ const coordinates = approximateBezierPath(
+ anchorsToBezierPoints([
+ { x: 0, y: 0 },
+ { x: 12000, y: 0 },
+ { x: 12000, y: 12000 },
+ ]),
+ false
+ );
+ const bounds = getTraceLineBounds(coordinates);
+ expect(bounds.x + bounds.width).toBeGreaterThan(12004.05);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/vectorTraceController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/vectorTraceController.ts
new file mode 100644
index 0000000000..a21030fc81
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/vectorTraceController.ts
@@ -0,0 +1,206 @@
+import type { VectorTraceResult } from '@workbench/canvas-engine/capabilities';
+import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';
+import type { CanvasNodeInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';
+import type { RasterBackend } from '@workbench/canvas-engine/render/raster';
+import type { Rect, Vec2 } from '@workbench/canvas-engine/types';
+
+import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';
+import { approximateBezierPath } from '@workbench/canvas-engine/math/bezierPath';
+import { polygonBounds, roundOut, union } from '@workbench/canvas-engine/math/rect';
+import {
+ findVectorFillRegionsAsync,
+ VectorFillLimitError,
+ VECTOR_FILL_LIMITS,
+} from '@workbench/canvas-engine/math/vectorFillRegions';
+import {
+ buildTaperedTracePoints,
+ buildTraceLinePath,
+ buildTraceOutlinePath,
+ getTraceLineBounds,
+} from '@workbench/canvas-engine/math/vectorTrace';
+import { getStroke } from 'perfect-freehand';
+
+import type { CanvasMutationContext } from './mutationContext';
+
+import { addedLayerHistoryBytes, paintLayerAt, publishAddedRasterLayer, rgbaBytes } from './editSteps';
+
+type Options = {
+ document: CanvasDocumentContractV3;
+ layerId: string;
+ pathId?: string;
+ appearance?: boolean;
+ fillOnly?: boolean;
+ ctx: CanvasMutationContext;
+ backend: RasterBackend;
+ id: string;
+ anchor: CanvasNodeInsertionAnchor;
+ signal?: AbortSignal;
+ isCurrent(): boolean;
+ /** The controller can be tested against recording surfaces without browser globals. */
+ createPath?: (data?: string) => Path2D;
+};
+
+/** Prepare against one immutable snapshot; admit pixels/history only after cancelable geometry work. */
+export const traceVectorLayer = async (o: Options): Promise<VectorTraceResult> => {
+ const current = () => !o.signal?.aborted && o.isCurrent();
+ if (!current()) {
+ return { status: o.signal?.aborted ? 'aborted' : 'stale' };
+ }
+ if (!o.ctx.canEdit()) {
+ return { status: 'busy' };
+ }
+ if (o.ctx.isGestureActive()) {
+ return { status: 'gesture-active' };
+ }
+ const leaf = lookupDocumentLeaf(o.document, o.layerId);
+ if (
+ !leaf ||
+ leaf.layer.type !== 'vector' ||
+ !leaf.contributionEnabled ||
+ leaf.documentHidden ||
+ leaf.effectiveLocked
+ ) {
+ return { status: 'not-ready' };
+ }
+ const layer = leaf.layer;
+ const fill = o.fillOnly === true || (o.appearance === true && (layer.fillEnabled ?? false));
+ const stroke = !o.fillOnly && (o.appearance !== true || (layer.strokeEnabled ?? true));
+ if (!fill && !stroke) {
+ return { status: 'empty' };
+ }
+ const width = Math.max(1, Math.min(600, Math.round(layer.strokeWidth)));
+ const color = layer.strokeColor;
+ const paths = o.pathId === undefined ? layer.paths : layer.paths.filter((path) => path.id === o.pathId);
+ const sampleCount = paths.reduce(
+ (sum, path) => sum + Math.max(0, path.points.length - (path.isClosed ? 0 : 1)) * 24,
+ 0
+ );
+ if (sampleCount > (fill && !o.fillOnly ? VECTOR_FILL_LIMITS.segments : 200_000)) {
+ return { status: 'too-complex' };
+ }
+ const createPath = o.createPath ?? ((data?: string) => (data ? new Path2D(data) : new Path2D()));
+ try {
+ const traces: { coordinates: Vec2[]; closed: boolean; outline: number[][] | null; bounds: Rect }[] = [];
+ for (const path of paths) {
+ o.signal?.throwIfAborted();
+ const coordinates = approximateBezierPath(path.points, path.isClosed);
+ if (coordinates.length < 2) {
+ continue;
+ }
+ const outline =
+ stroke && layer.traceTaperEnds && !path.isClosed
+ ? getStroke(buildTaperedTracePoints(coordinates, width, layer.traceTaper ?? 100), {
+ size: width / 2,
+ simulatePressure: false,
+ last: true,
+ thinning: 1,
+ })
+ : null;
+ const bounds = outline
+ ? polygonBounds(outline.map((point) => ({ x: point[0]!, y: point[1]! })))
+ : stroke
+ ? getTraceLineBounds(coordinates)
+ : polygonBounds(coordinates);
+ traces.push({ coordinates, closed: path.isClosed, outline, bounds });
+ }
+ const regions = !fill
+ ? []
+ : o.fillOnly
+ ? traces.filter((trace) => trace.closed && trace.coordinates.length >= 3).map((trace) => trace.coordinates)
+ : await findVectorFillRegionsAsync(
+ traces.map((trace) => trace.coordinates),
+ { signal: o.signal }
+ );
+ if (!current()) {
+ return { status: o.signal?.aborted ? 'aborted' : 'stale' };
+ }
+ let bounds: Rect | null = null;
+ for (const region of regions) {
+ bounds = bounds ? union(bounds, polygonBounds(region)) : polygonBounds(region);
+ }
+ if (stroke) {
+ for (const trace of traces) {
+ bounds = bounds ? union(bounds, trace.bounds) : trace.bounds;
+ }
+ }
+ if (!bounds) {
+ return { status: 'empty' };
+ }
+ // Control-point hulls bound all tension curves; actual pressure outlines bound taper. Include stroke + AA.
+ const padding = stroke ? width / 2 + 2 : 2;
+ const rect = roundOut({
+ x: bounds.x - padding,
+ y: bounds.y - padding,
+ width: bounds.width + padding * 2,
+ height: bounds.height + padding * 2,
+ });
+ const txn = o.ctx.begin({ historyBytes: addedLayerHistoryBytes(rect) });
+ if (!('publish' in txn)) {
+ return txn;
+ }
+ try {
+ if (!current()) {
+ return { status: o.signal?.aborted ? 'aborted' : 'stale' };
+ }
+ if (!txn.reserveRaster(rgbaBytes(rect))) {
+ return { status: 'over-budget' };
+ }
+ const pixels = o.backend.createSurface(rect.width, rect.height),
+ draw = pixels.ctx;
+ draw.setTransform(1, 0, 0, 1, -rect.x, -rect.y);
+ draw.fillStyle = color;
+ draw.strokeStyle = color;
+ draw.lineWidth = width;
+ draw.lineCap = 'round';
+ draw.lineJoin = 'round';
+ if (regions.length > 0) {
+ const regionPath = createPath();
+ for (const region of regions) {
+ regionPath.moveTo(region[0]!.x, region[0]!.y);
+ for (const point of region.slice(1)) {
+ regionPath.lineTo(point.x, point.y);
+ }
+ regionPath.closePath();
+ }
+ draw.fillStyle = layer.fillColor ?? '#ffffff';
+ draw.fill(regionPath);
+ draw.fillStyle = color;
+ }
+ if (stroke) {
+ for (const trace of traces) {
+ if (trace.outline) {
+ draw.fill(buildTraceOutlinePath(trace.outline, createPath));
+ } else {
+ draw.stroke(buildTraceLinePath(trace.coordinates, createPath));
+ }
+ }
+ }
+ const raster = paintLayerAt(
+ o.id,
+ `${layer.name} ${o.fillOnly ? 'Fill' : o.appearance ? 'Trace-Fill' : 'Trace'}`,
+ rect
+ );
+ raster.transform = { ...layer.transform };
+ const result = publishAddedRasterLayer(o.ctx, txn, {
+ label: o.fillOnly ? 'Fill vector path' : o.appearance ? 'Trace/Fill vector paths' : 'Trace vector paths',
+ layer: raster,
+ rect,
+ pixels,
+ anchor: o.anchor,
+ preserveSelection: true,
+ selectedLayerId: o.document.selectedLayerId,
+ });
+ return {
+ status:
+ result.status === 'committed' ? 'committed' : result.status === 'over-budget' ? 'over-budget' : 'failed',
+ };
+ } finally {
+ txn.end();
+ }
+ } catch (error) {
+ if (o.signal?.aborted) {
+ return { status: 'aborted' };
+ }
+ return { status: error instanceof VectorFillLimitError ? 'too-complex' : 'failed' };
+ }
+};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentFixtures.testStub.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentFixtures.testStub.ts
index 8403848115..bc8776e4f8 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentFixtures.testStub.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentFixtures.testStub.ts
@@ -8,7 +8,6 @@ import type {
import { createEmptyStacks } from '@workbench/canvas-engine/document/documentTree';
import { LAYER_STACK_ORDER, layerStackOf } from '@workbench/canvas-engine/document/layerStacks';
-
const base = (id: string) => ({
blendMode: 'normal' as const,
id,
@@ -29,6 +28,8 @@ export const layerContract = (
): CanvasLayerContract => {
const contract = ((): CanvasLayerContract => {
switch (type) {
+ case 'vector':
+ return { ...base(id), paths: [], strokeColor: '#000000', strokeWidth: 50, type };
case 'raster':
return { ...base(id), source: { bitmap: null, type: 'paint' }, type };
case 'control':
@@ -87,7 +88,7 @@ const stackOfNode = (node: CanvasNodeContract): CanvasLayerContract['type'] | nu
export const stacksFrom = (nodes: readonly CanvasNodeContract[]): CanvasStackForests => {
const stacks = createEmptyStacks();
for (const node of nodes) {
- stacks[stackOfNode(node) ?? 'raster'].push(node);
+ (stacks[stackOfNode(node) ?? 'raster'] ??= []).push(node);
}
return stacks;
};
@@ -155,7 +156,7 @@ export const createLargeTreeDocument = (
};
const perStack = Math.ceil(count / LAYER_STACK_ORDER.length);
for (const stack of LAYER_STACK_ORDER) {
- stacks[stack].push(...build(stack, perStack, 0));
+ (stacks[stack] ??= []).push(...build(stack, perStack, 0));
}
return documentFrom(stacks, selectedLayerId);
};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.budget.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.budget.test.ts
index 5bd6e2372d..1a080ba3fd 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.budget.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.budget.test.ts
@@ -195,10 +195,10 @@ describe(`document model budgets over ${NODE_COUNT} nodes`, () => {
type: 'set-enabled',
updates: Array.from({ length: 10 }, (_, index) => ({ id: `l${index}`, isEnabled: false })),
},
- { builds: 1, ids: 10, stacks: 4 },
+ { builds: 1, ids: 10, stacks: 5 },
],
['hide', { type: 'set-hidden', updates: [{ id: 'l1', isHidden: true }] }, { builds: 1, ids: 1, stacks: 1 }],
- ['move', { ids: ['l8', 'l12', 'l16'], kind: 'forward', type: 'move' }, { builds: 1, ids: 4, stacks: 1 }],
+ ['move', { ids: ['l8', 'l12', 'l16'], kind: 'forward', type: 'move' }, { builds: 1, ids: 6, stacks: 3 }],
// Removal repairs the selection over the projected forest, which costs one more index.
['remove', { ids: ['l1', 'l2'], type: 'remove' }, { builds: 2, ids: 2, stacks: 2 }],
])('prepares a %s edit with exact touched ids and stacks and no leaf compilation', (_label, command, expected) => {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.fuzz.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.fuzz.test.ts
index 58d1bd59fd..43d13bff6b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.fuzz.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.fuzz.test.ts
@@ -255,7 +255,7 @@ const projectFor = (document: CanvasDocumentContractV3): Project =>
const outcomes = { locked: 0, nestedDuplicate: 0, nestedUngroup: 0, reparentInside: 0 };
describe('document model fuzzing', () => {
- it.each(Array.from({ length: 160 }, (_, seed) => seed + 1))(
+ it.each(Array.from({ length: 240 }, (_, seed) => seed + 1))(
'keeps every invariant and round-trips undo through random edits (seed %i)',
(seed) => {
const random = rng(seed);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.test.ts
index 5136e2782a..82f29ce443 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.test.ts
@@ -851,7 +851,7 @@ describe('createDocumentModel', () => {
model.prepare({ config: { adjustments: stack, layerType: 'raster' }, id: 'G', type: 'patch-config' })
).toEqual({
actual: 'group',
- expected: ['raster', 'control', 'regional_guidance', 'inpaint_mask'],
+ expected: ['raster', 'control', 'regional_guidance', 'inpaint_mask', 'vector'],
status: 'wrong-type',
});
@@ -1159,7 +1159,11 @@ describe('createDocumentModel', () => {
[
'a config patch on a group',
{ config: { layerType: 'raster', isTransparencyLocked: true }, id: 'G', type: 'patch-config' },
- { actual: 'group', expected: ['raster', 'control', 'regional_guidance', 'inpaint_mask'], status: 'wrong-type' },
+ {
+ actual: 'group',
+ expected: ['raster', 'control', 'regional_guidance', 'inpaint_mask', 'vector'],
+ status: 'wrong-type',
+ },
],
[
'a source patch on a mask',
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.ts
index 54ce3a8beb..4da68a1f05 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.ts
@@ -655,7 +655,7 @@ export const createDocumentModel = (
const removedSet = new Set(removedIds);
const remaining = { ...stacks };
for (const stack of new Set(outer.map((entry) => entry.stack))) {
- remaining[stack] = stacks[stack]
+ remaining[stack] = (stacks[stack] ?? [])
.filter((node) => !removedSet.has(node.id))
.map((node) => stripRemoved(node, removedSet));
}
@@ -1131,7 +1131,7 @@ export const createDocumentModel = (
touchedIds.push(group.id, ...childIds);
expected = {
...expected,
- [entry.stack]: dissolve(expected[entry.stack], dissolved),
+ [entry.stack]: dissolve(expected[entry.stack] ?? [], dissolved),
};
}
for (const key of unique(
@@ -1175,7 +1175,7 @@ export const createDocumentModel = (
if (unsupported) {
return {
actual: 'group',
- expected: ['raster', 'control', 'regional_guidance', 'inpaint_mask'],
+ expected: ['raster', 'control', 'regional_guidance', 'inpaint_mask', 'vector'],
status: 'wrong-type',
};
}
@@ -1222,7 +1222,7 @@ export const createDocumentModel = (
if (isGroupNode(entry.node)) {
return {
actual: 'group',
- expected: ['raster', 'control', 'regional_guidance', 'inpaint_mask'],
+ expected: ['raster', 'control', 'regional_guidance', 'inpaint_mask', 'vector'],
status: 'wrong-type',
};
}
@@ -1551,7 +1551,7 @@ export const createDocumentModel = (
return node && !isGroupNode(node) ? node : null;
},
getNode: (id) => index.byId.get(id)?.node ?? null,
- getStack: (kind) => stacks[kind],
+ getStack: (kind) => stacks[kind] ?? [],
prepare: (command) => {
switch (command.type) {
case 'insert':
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/screenComposition.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/screenComposition.ts
index 7389c4fd71..3a6b5a6eaa 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/screenComposition.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/screenComposition.ts
@@ -6,7 +6,7 @@ import type { SemanticLeaf } from './semanticLeaf';
/** Screen-only state that never enters the document: overlay stack switches and isolation. */
export interface CanvasScreenViewState {
- readonly showOverlayStacks: Readonly<Record<OverlayStackKind, boolean>>;
+ readonly showOverlayStacks: Readonly<Record<Exclude<OverlayStackKind, 'vector'>, boolean> & { vector?: boolean }>;
/** A leaf or a group; a group isolates its descendant leaves. */
readonly isolationLayerId: string | null;
}
@@ -22,10 +22,11 @@ export const ALL_OVERLAY_STACKS_SHOWN: Readonly<Record<OverlayStackKind, boolean
control: true,
inpaint_mask: true,
regional_guidance: true,
+ vector: true,
};
const isStackShown = (stack: LayerStackKind, view: CanvasScreenViewState): boolean =>
- stack === 'raster' || view.showOverlayStacks[stack];
+ stack === 'raster' || view.showOverlayStacks[stack] !== false;
export const isLeafIsolated = (leaf: SemanticLeaf, isolationLayerId: string | null): boolean =>
isolationLayerId !== null && (leaf.id === isolationLayerId || leaf.parentIds.includes(isolationLayerId));
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentIndex.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentIndex.ts
index a613a63361..c8a86eee4e 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentIndex.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentIndex.ts
@@ -272,7 +272,7 @@ const build = (stacks: CanvasStackForests): CanvasDocumentIndex => {
});
};
for (const stack of LAYER_STACKS_TOP_FIRST) {
- visit(stacks[stack], stack, null, [], true, false, false);
+ visit(stacks[stack] ?? [], stack, null, [], true, false, false);
}
return { byId, leaves, maxDepth, nodes, stacks };
};
@@ -317,7 +317,7 @@ const deriveIndexForValueEdit = (
// Ancestors were rebuilt along each changed path; find their new objects from the new roots.
for (const id of changed.keys()) {
const entry = previous.byId.get(id)!;
- let siblings: readonly CanvasNodeContract[] = nextStacks[entry.stack];
+ let siblings: readonly CanvasNodeContract[] = nextStacks[entry.stack] ?? [];
for (const ancestorId of entry.path) {
const ancestor = replacedNodes.get(ancestorId) ?? siblings[previous.byId.get(ancestorId)!.siblingIndex];
if (!ancestor || ancestor.id !== ancestorId || !isGroupNode(ancestor)) {
@@ -495,7 +495,11 @@ export const updateNodeValues = (
};
let result = stacks;
for (const stack of LAYER_STACKS_TOP_FIRST) {
- const roots = rebuild(rootKey(stack), stacks[stack]);
+ const current = stacks[stack];
+ if (!current) {
+ continue;
+ }
+ const roots = rebuild(rootKey(stack), current);
if (roots !== stacks[stack]) {
result = result === stacks ? { ...stacks } : result;
result[stack] = roots as CanvasNodeContract[];
@@ -567,7 +571,7 @@ export const childrenAt = (
parentId: string | null
): readonly CanvasNodeContract[] | null => {
if (parentId === null) {
- return index.stacks[stack];
+ return index.stacks[stack] ?? [];
}
const parent = index.byId.get(parentId);
return parent && parent.stack === stack && isGroupNode(parent.node) ? parent.node.children : null;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.ts
index 78dbaaf166..1619d6bb57 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.ts
@@ -66,11 +66,15 @@ const bboxEqual = (a: Bbox, b: Bbox): boolean =>
a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;
/**
- * Raster invalidation identity is raster/control `source` or mask `bitmap`. Property edits preserve it; mask fill
- * changes must preserve unflushed alpha-cache strokes.
+ * Content invalidation identity is raster/control `source`, mask `bitmap`, or vector `paths`. Property edits
+ * preserve it; mask fill changes must preserve unflushed alpha-cache strokes.
*/
-const rasterSourceRef = (layer: CanvasLayerContract): unknown =>
- layer.type === 'raster' || layer.type === 'control' ? layer.source : layer.mask.bitmap;
+const rasterSourceRef = (layer: CanvasLayerContract): unknown => {
+ if (layer.type === 'vector') {
+ return layer.paths;
+ }
+ return layer.type === 'raster' || layer.type === 'control' ? layer.source : layer.mask.bitmap;
+};
const effectiveKey = (entry: CanvasNodeEntry): string =>
`${entry.ancestorsEnabled ? 1 : 0}${entry.ancestorsLocked ? 1 : 0}${entry.ancestorsHidden ? 1 : 0}`;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentTree.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentTree.ts
index 8f75dce5f9..677679d6fe 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentTree.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentTree.ts
@@ -17,9 +17,9 @@ export const childrenOf = (
parentId: string | null
): readonly CanvasNodeContract[] | null => {
if (parentId === null) {
- return stacks[stack];
+ return stacks[stack] ?? [];
}
- const group = findNode(stacks[stack], parentId);
+ const group = findNode(stacks[stack] ?? [], parentId);
return group && isGroupNode(group) ? group.children : null;
};
@@ -80,7 +80,11 @@ export const cloneSubtree = (
const children = node.children.map((child) => cloneSubtree(child, createId, ids).node);
return { ids, node: { ...node, children, id } };
}
- return { ids, node: { ...structuredClone(node), id } };
+ const copy = { ...structuredClone(node), id };
+ if (copy.type === 'vector') {
+ copy.paths = copy.paths.map((path) => ({ ...path, id: createId() }));
+ }
+ return { ids, node: copy };
};
const replaceIn = (
@@ -111,7 +115,7 @@ export const replaceChildren = (
parentId: string | null,
children: readonly CanvasNodeContract[]
): CanvasStackForests => {
- const roots = parentId === null ? children : replaceIn(stacks[stack], parentId, () => children);
+ const roots = parentId === null ? children : replaceIn(stacks[stack] ?? [], parentId, () => children);
return roots === stacks[stack] ? stacks : { ...stacks, [stack]: [...roots] };
};
@@ -142,7 +146,7 @@ export const removeNodes = (stacks: CanvasStackForests, ids: ReadonlySet<string>
};
let result = stacks;
for (const stack of Object.keys(stacks) as CanvasLayerStackKind[]) {
- const roots = visit(stacks[stack]);
+ const roots = visit(stacks[stack] ?? []);
if (roots !== stacks[stack]) {
result = result === stacks ? { ...stacks } : result;
result[stack] = [...roots];
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/insertionAnchors.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/insertionAnchors.ts
index fd8f7e099a..332e2e79db 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/insertionAnchors.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/insertionAnchors.ts
@@ -70,7 +70,7 @@ export const captureInsertionAnchor = (
if (above && above.stack === stack) {
const siblings =
above.parentId === null
- ? stacks[stack]
+ ? (stacks[stack] ?? [])
: (index.byId.get(above.parentId)!.node as { children: CanvasNodeContract[] }).children;
return {
afterId: siblings[above.siblingIndex - 1]?.id ?? null,
@@ -83,7 +83,7 @@ export const captureInsertionAnchor = (
}
return {
afterId: null,
- beforeId: stacks[stack][0]?.id ?? null,
+ beforeId: stacks[stack]?.[0]?.id ?? null,
capturedEditRevision: editRevision,
parentPath: [],
projectId,
@@ -105,7 +105,7 @@ export const captureRestoreAnchor = (
}
const siblings =
entry.parentId === null
- ? stacks[entry.stack]
+ ? (stacks[entry.stack] ?? [])
: (index.byId.get(entry.parentId)!.node as { children: CanvasNodeContract[] }).children;
return {
afterId: siblings[entry.siblingIndex - 1]?.id ?? null,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerEligibility.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerEligibility.ts
index 6b579ceda0..29ae890b0e 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerEligibility.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerEligibility.ts
@@ -18,10 +18,16 @@ export const isLayerPaintable = (layer: CanvasLayerContract): boolean =>
isLayerEditable(layer) && layer.type !== 'control';
/** Overlay layers show where an effect applies, so they can be hidden on screen without leaving generation. */
-export type HideableLayer = Extract<CanvasLayerContract, { type: 'control' | 'inpaint_mask' | 'regional_guidance' }>;
+export type HideableLayer = Extract<
+ CanvasLayerContract,
+ { type: 'control' | 'inpaint_mask' | 'regional_guidance' | 'vector' }
+>;
export const isHideableLayer = (layer: CanvasLayerContract): layer is HideableLayer =>
- layer.type === 'control' || layer.type === 'inpaint_mask' || layer.type === 'regional_guidance';
+ layer.type === 'control' ||
+ layer.type === 'inpaint_mask' ||
+ layer.type === 'regional_guidance' ||
+ layer.type === 'vector';
/** Display only: generation and export never consult it. Groups are hideable in overlay stacks. */
export const isLayerHidden = (layer: CanvasLayerContract): boolean => isHideableLayer(layer) && layer.isHidden === true;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerFactories.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerFactories.ts
index b382ebcdc0..33e3322c66 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerFactories.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerFactories.ts
@@ -23,7 +23,7 @@ export const REGIONAL_GUIDANCE_FILL_COLORS: readonly string[] = [
'#a178d6',
];
-const nextNumberedName = (prefix: string, existingNames: readonly string[]): string => {
+export const nextNumberedName = (prefix: string, existingNames: readonly string[]): string => {
const expression = new RegExp(`^${prefix} (\\d+)$`);
const used = new Set(
existingNames
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.test.ts
index 4f81ab4262..17843a856c 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.test.ts
@@ -29,7 +29,7 @@ const ids = (forest: CanvasStackForests | null): string[] | undefined =>
describe('layer stacks', () => {
it('declares one composite order and its panel mirror', () => {
- expect(LAYER_STACK_ORDER).toEqual(['raster', 'control', 'regional_guidance', 'inpaint_mask']);
+ expect(LAYER_STACK_ORDER).toEqual(['raster', 'control', 'vector', 'regional_guidance', 'inpaint_mask']);
expect(LAYER_STACKS_TOP_FIRST).toEqual([...LAYER_STACK_ORDER].reverse());
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.ts
index 3e4cd40083..d15800aa0b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.ts
@@ -9,7 +9,7 @@ import { childrenAt, indexStacks, type CanvasDocumentIndex } from './documentInd
import { childrenOf, isGroupNode, replaceChildren } from './documentTree';
/**
- * The four stack forests of a v3 document. The compositor draws the stacks bottom to top in
+ * The stack forests of a document. The compositor draws the stacks bottom to top in
* {@link LAYER_STACK_ORDER} and the Layers panel lists them top first; within a stack, nodes are
* ordered by their depth-first preorder position, top first.
*/
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 46cd7c66d5..b27fd7650a 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.ts
@@ -87,6 +87,10 @@ export const isRenderableLayer = (layer: CanvasLayerContract): boolean => {
* unsupported sources throw.
*/
export const getSourceContentRect = (layer: CanvasLayerContract, doc: CanvasDocumentContractV3): Rect => {
+ // Guide geometry owns no pixels, even when it has paths.
+ if (layer.type === 'vector') {
+ return { height: 0, width: 0, x: 0, y: 0 };
+ }
const source = renderableSourceOf(layer);
if (!source) {
throw new Error(`getSourceContentRect: layer type '${layer.type}' has no rasterizable source`);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/vectorLayerFactories.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/vectorLayerFactories.ts
new file mode 100644
index 0000000000..ecf6c8db8a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/vectorLayerFactories.ts
@@ -0,0 +1,22 @@
+import type { CanvasVectorLayerContract } from '@workbench/canvas-engine/contracts';
+
+import { DEFAULT_VECTOR_STROKE_COLOR, DEFAULT_VECTOR_STROKE_WIDTH } from '@workbench/canvas-engine/vectorDefaults';
+
+import { nextNumberedName } from './layerFactories';
+
+// Vector creation stays separate from the raster/control factories used by non-Canvas image actions.
+export const nextVectorLayerName = (names: readonly string[]): string => nextNumberedName('Vector Layer', names);
+
+export const createVectorLayer = (input: { id: string; name: string }): CanvasVectorLayerContract => ({
+ blendMode: 'normal',
+ id: input.id,
+ isEnabled: true,
+ isLocked: false,
+ name: input.name,
+ opacity: 1,
+ paths: [],
+ strokeColor: DEFAULT_VECTOR_STROKE_COLOR,
+ strokeWidth: DEFAULT_VECTOR_STROKE_WIDTH,
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ type: 'vector',
+});
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 c2177d76e8..de0d6be25a 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -30,6 +30,8 @@ import {
type CanvasProjectMutation,
} from '@workbench/canvasProjectMutations';
+import type * as VectorRuntimeModule from './vectorRuntime';
+
type EngineTestAction = WorkbenchAction | CanvasProjectMutation;
import type { SpatialAdjustmentExecutor } from '@workbench/canvas-engine/render/spatial/spatialAdjustmentService';
@@ -38,6 +40,7 @@ import { groupContract, stacksFrom } from '@workbench/canvas-engine/document-mod
import { getDocumentLayer, getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';
import { stackTopAnchor } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
import { haveSameStructure } from '@workbench/canvas-engine/document/layerStacks';
+import { createVectorLayer } from '@workbench/canvas-engine/document/vectorLayerFactories';
import * as compositor from '@workbench/canvas-engine/render/compositor';
import { DEFAULT_CHECKER_COLORS } from '@workbench/canvas-engine/render/compositor';
import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';
@@ -298,13 +301,14 @@ const createFakeStore = (
};
};
-const createEngine = () => {
+const createEngine = (loadVectorRuntime?: TestCanvasEngineOptions['loadVectorRuntime']) => {
const doc = makeDoc();
const { store, unsubscribe } = createFakeStore(doc);
const engine = createCanvasEngine({
backend: createTestStubRasterBackend(),
imageResolver: () => Promise.resolve(new Blob()),
projectId: 'p1',
+ loadVectorRuntime,
store,
});
return { doc, engine, unsubscribe };
@@ -19266,8 +19270,10 @@ describe('Select Object canvas engine integration', () => {
if (created.type === 'raster' || created.type === 'control') {
expect(created.name).toBe(copyName);
expect(created.source).toMatchObject({ offset: { x: 0, y: 0 }, type: 'paint' });
- } else {
+ } else if (created.type === 'inpaint_mask' || created.type === 'regional_guidance') {
expect(created.mask).toMatchObject({ offset: { x: 0, y: 0 } });
+ } else {
+ throw new Error('expected a saved pixel layer');
}
expect(created.transform).toEqual({ rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 });
@@ -21216,3 +21222,282 @@ describe('edit feedback on the surface', () => {
});
});
});
+
+it('reactivates Spline Edit on the same selected vector after engine cooldown', async () => {
+ const vector = {
+ ...createVectorLayer({ id: 'v', name: 'Vector' }),
+ transform: { x: 0, y: 0, rotation: 0, scaleX: 1, scaleY: 1 },
+ paths: [],
+ };
+ const doc = { ...makeDoc(), stacks: stacksFrom([vector]), selectedLayerId: 'v' };
+ const { store } = createFakeStore(doc);
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId: 'p1',
+ store,
+ });
+ try {
+ await engine.layers.vectorEdit.prepare();
+ engine.tools.setTool('spline');
+ expect(engine.interaction.get('vectorEditSession')?.layerId).toBe('v');
+ await engine.lifecycle.beginCooldown();
+ expect(engine.interaction.get('vectorEditSession')).toBeNull();
+ engine.lifecycle.activate();
+ expect(engine.interaction.get('activeTool')).toBe('spline');
+ expect(engine.interaction.get('vectorEditSession')).toMatchObject({
+ layerId: 'v',
+ activePathId: null,
+ selectedPoints: [],
+ });
+ } finally {
+ engine.lifecycle.dispose();
+ }
+});
+
+it('aborts pending vector region work on Escape and document changes without creating raster output', async () => {
+ const vector = {
+ ...createVectorLayer({ id: 'v', name: 'Vector' }),
+ fillEnabled: true,
+ strokeEnabled: false,
+ transform: { x: 0, y: 0, rotation: 0, scaleX: 1, scaleY: 1 },
+ paths: [
+ {
+ id: 'p',
+ name: null,
+ isClosed: true,
+ points: [
+ { x: 0, y: 0 },
+ { x: 100, y: 0 },
+ { x: 0, y: 100 },
+ ].map((anchor) => ({ anchor, inHandle: null, outHandle: null, type: 'corner' as const })),
+ },
+ ],
+ };
+ const doc = { ...makeDoc(), stacks: stacksFrom([vector]), selectedLayerId: 'v' };
+ const h = createReactiveStore(doc);
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId: 'p1',
+ store: h.store,
+ });
+ try {
+ engine.tools.setTool('spline');
+ const first = engine.layers.traceFillVectorLayer('v');
+ engine.tools.handleEscapePriority({ gestureWasActive: false });
+ expect(await first).toEqual({ status: 'aborted' });
+ const second = engine.layers.traceFillVectorLayer('v');
+ h.setDocument({ ...doc, selectedLayerId: null });
+ expect(await second).toEqual({ status: 'aborted' });
+ expect(h.store.dispatch).not.toHaveBeenCalled();
+ } finally {
+ engine.lifecycle.dispose();
+ }
+});
+
+it('keeps pending vector rendering independent of brush color and size changes', async () => {
+ vi.stubGlobal(
+ 'Path2D',
+ class {
+ moveTo() {}
+ lineTo() {}
+ closePath() {}
+ quadraticCurveTo() {}
+ bezierCurveTo() {}
+ }
+ );
+ const vector = {
+ ...createVectorLayer({ id: 'v', name: 'Vector' }),
+ fillEnabled: true,
+ fillColor: '#00ff00',
+ strokeColor: '#ff0000',
+ strokeWidth: 8,
+ paths: [
+ {
+ id: 'p',
+ name: null,
+ isClosed: true,
+ points: [
+ { x: 0, y: 0 },
+ { x: 100, y: 0 },
+ { x: 100, y: 100 },
+ ].map((anchor) => ({ anchor, inHandle: null, outHandle: null, type: 'corner' as const })),
+ },
+ ],
+ };
+ const h = createReducerBackedStore({ ...makeDoc(), stacks: stacksFrom([vector]), selectedLayerId: 'v' });
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId: h.projectId,
+ store: h.store,
+ });
+ try {
+ const pending = engine.layers.traceFillVectorLayer('v');
+ engine.interaction.set('brushOptions', { ...engine.interaction.get('brushOptions'), color: '#0000ff', size: 99 });
+ expect(await pending).toEqual({ status: 'committed' });
+ expect(getDocumentLayer(h.store.getState().projects[0]!.canvas.document, 'v')).toMatchObject({
+ strokeColor: '#ff0000',
+ strokeWidth: 8,
+ fillColor: '#00ff00',
+ });
+ } finally {
+ engine.lifecycle.dispose();
+ }
+});
+
+describe('lazy vector readiness', () => {
+ const deferredModule = () => {
+ let resolve!: (module: typeof VectorRuntimeModule) => void;
+ const promise = new Promise<typeof VectorRuntimeModule>((settle) => {
+ resolve = settle;
+ });
+ return { resolve, load: vi.fn(() => promise) };
+ };
+
+ it('keeps ordinary raster tool activation independent of vector loading', () => {
+ const pending = deferredModule();
+ const { engine } = createEngine(pending.load);
+ try {
+ engine.tools.setTool('brush');
+ engine.tools.setTool('shape');
+ expect(engine.interaction.get('activeTool')).toBe('shape');
+ expect(pending.load).not.toHaveBeenCalled();
+ } finally {
+ engine.lifecycle.dispose();
+ }
+ });
+
+ it('coalesces readiness requests and produces the first layer only after support is ready', async () => {
+ const pending = deferredModule();
+ const { engine } = createEngine(pending.load);
+ try {
+ let produced = false;
+ const layer = engine.layers.vectorEdit.createLayer({ id: 'new-vector' }).then((value) => {
+ produced = true;
+ return value;
+ });
+ const ready = engine.layers.vectorEdit.prepare();
+ await vi.waitFor(() => expect(pending.load).toHaveBeenCalledOnce());
+ expect(engine.interaction.get('vectorToolsStatus')).toBe('loading');
+ expect(produced).toBe(false);
+ pending.resolve(await import('./vectorRuntime'));
+ expect(await ready).toBe(true);
+ expect(await layer).toMatchObject({
+ id: 'new-vector',
+ type: 'vector',
+ paths: [],
+ strokeColor: '#000000',
+ strokeWidth: 50,
+ });
+ expect(engine.interaction.get('vectorToolsStatus')).toBe('ready');
+ expect(pending.load).toHaveBeenCalledOnce();
+ } finally {
+ engine.lifecycle.dispose();
+ }
+ });
+
+ it('does not activate Spline after a later tool request', async () => {
+ const pending = deferredModule();
+ const { engine } = createEngine(pending.load);
+ try {
+ engine.tools.setTool('spline');
+ engine.tools.setTool('brush');
+ pending.resolve(await import('./vectorRuntime'));
+ expect(await engine.layers.vectorEdit.prepare()).toBe(true);
+ expect(engine.interaction.get('activeTool')).toBe('brush');
+ expect(engine.interaction.get('vectorEditSession')).toBeNull();
+ } finally {
+ engine.lifecycle.dispose();
+ }
+ });
+
+ it('does not instantiate vector state after the engine is disposed during loading', async () => {
+ const pending = deferredModule();
+ const module = await import('./vectorRuntime');
+ const create = vi.fn(module.createVectorRuntime);
+ const { engine } = createEngine(pending.load);
+ const ready = engine.layers.vectorEdit.prepare();
+ await vi.waitFor(() => expect(pending.load).toHaveBeenCalledOnce());
+ engine.lifecycle.dispose();
+ pending.resolve({ ...module, createVectorRuntime: create });
+ expect(await ready).toBe(false);
+ expect(create).not.toHaveBeenCalled();
+ });
+
+ it('cancels an old layer request across cooldown and permits a fresh request after activation', async () => {
+ const pending = deferredModule();
+ const { engine } = createEngine(pending.load);
+ try {
+ const abandoned = engine.layers.vectorEdit.createLayer({ id: 'abandoned' });
+ await engine.lifecycle.beginCooldown();
+ engine.lifecycle.activate();
+ pending.resolve(await import('./vectorRuntime'));
+ expect(await abandoned).toBeNull();
+ expect(await engine.layers.vectorEdit.createLayer({ id: 'fresh' })).toMatchObject({
+ id: 'fresh',
+ type: 'vector',
+ });
+ } finally {
+ engine.lifecycle.dispose();
+ }
+ });
+
+ it('handles the first path hit synchronously once the requested Spline tool is ready', async () => {
+ const pending = deferredModule();
+ const vector = createVectorLayer({ id: 'v', name: 'Vector' });
+ vector.paths = [
+ {
+ id: 'p',
+ name: null,
+ isClosed: false,
+ points: [
+ { anchor: { x: 0, y: 0 }, inHandle: null, outHandle: null, type: 'corner' },
+ { anchor: { x: 100, y: 0 }, inHandle: null, outHandle: null, type: 'corner' },
+ ],
+ },
+ ];
+ const { store } = createFakeStore({ ...makeDoc(), stacks: stacksFrom([vector]), selectedLayerId: 'v' });
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId: 'p1',
+ store,
+ loadVectorRuntime: pending.load,
+ });
+ try {
+ engine.tools.setTool('spline');
+ expect(engine.interaction.get('activeTool')).not.toBe('spline');
+ pending.resolve(await import('./vectorRuntime'));
+ await engine.layers.vectorEdit.prepare();
+ expect(engine.interaction.get('activeTool')).toBe('spline');
+ expect(engine.layers.vectorEdit.targetContextMenu({ x: 50, y: 0 })).toBe(true);
+ expect(engine.interaction.get('vectorEditSession')?.activePathId).toBe('p');
+ } finally {
+ engine.lifecycle.dispose();
+ }
+ });
+
+ it('reports a failed load and allows an explicit retry', async () => {
+ const outage = new Error('Vector module unavailable');
+ const load = vi
+ .fn<NonNullable<TestCanvasEngineOptions['loadVectorRuntime']>>()
+ .mockRejectedValueOnce(outage)
+ .mockImplementation(() => import('./vectorRuntime'));
+ const { engine } = createEngine(load);
+ try {
+ expect(await engine.layers.vectorEdit.prepare()).toBe(false);
+ expect(engine.interaction.get('vectorToolsStatus')).toBe('failed');
+ expect(reportedErrors.at(-1)).toMatchObject({
+ message: 'Vector tools could not be loaded',
+ context: { error: outage },
+ });
+ expect(await engine.layers.vectorEdit.prepare()).toBe(true);
+ expect(engine.interaction.get('vectorToolsStatus')).toBe('ready');
+ expect(load).toHaveBeenCalledTimes(2);
+ } finally {
+ engine.lifecycle.dispose();
+ }
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index 8c15952fa4..2cc8babbcc 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -45,6 +45,7 @@ import type {
} from '@workbench/canvas-engine/rasterTransactions';
import type { TransformResampler } from './controllers/transformEditingController';
+import type * as VectorRuntimeModule from './vectorRuntime';
export type {
BooleanRasterResult,
CanvasDiagnosticsCapability,
@@ -98,6 +99,7 @@ import type { SpatialAdjustmentExecutor } from '@workbench/canvas-engine/render/
import type { SamVisualInput } from '@workbench/canvas-engine/samInteraction';
import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';
import type { Rect, RenderFlags, ToolId, Vec2 } from '@workbench/canvas-engine/types';
+import type { VectorRuntime } from '@workbench/canvas-engine/vectorRuntime';
import type { CanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';
import { createItemId } from '@platform/browser/randomUuid';
@@ -258,6 +260,7 @@ export interface CanvasEngineErrorReport {
/** The raw failure; notifications show its message and diagnostics keep its stack. */
context: { error: unknown; layerId?: string; label?: string };
message:
+ | 'Vector tools could not be loaded'
| 'PSD export failed'
| 'Layer thumbnail rasterization failed'
| 'Bitmap persistence failed'
@@ -277,6 +280,7 @@ export interface CanvasEngineErrorReport {
export interface CanvasEngineOptions {
resampleTransform?: TransformResampler;
projectId: string;
+ loadVectorRuntime?: () => Promise<typeof VectorRuntimeModule>;
/** Undo steps the project's previous engine was disposed with; History reports them until it is next cleared. */
droppedHistorySteps?: number;
mutationPort: CanvasProjectMutationPort;
@@ -424,6 +428,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
snapToGrid: stores.snapToGrid,
stagingHidesOverlays: stores.stagingHidesOverlays,
textEditSession: stores.textEditSession,
+ vectorEditSession: stores.vectorEditSession,
+ vectorToolsStatus: stores.vectorToolsStatus,
textOptions: stores.textOptions,
transformOptions: stores.transformOptions,
transformSession: stores.transformSession,
@@ -450,12 +456,27 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
['brush', createBrushTool()],
['eraser', createEraserTool()],
['move', createMoveTool()],
+ [
+ 'spline',
+ {
+ id: 'spline',
+ usesAltKey: true,
+ cursor: () => vectorRuntime?.editor.cursor() ?? 'crosshair',
+ onActivate: () => vectorRuntime?.editor.onActivate(),
+ onDeactivate: (ctx, options) => vectorRuntime?.editor.onDeactivate(ctx, options),
+ onPointerDown: (ctx, input) => vectorRuntime?.editor.onPointerDown(ctx, input),
+ onPointerMove: (ctx, input) => vectorRuntime?.editor.onPointerMove(ctx, input),
+ onPointerUp: () => vectorRuntime?.editor.onPointerUp(),
+ onPointerCancel: () => vectorRuntime?.editor.onPointerCancel(),
+ onKeyCommand: (ctx, command) => vectorRuntime?.editor.onKeyCommand(ctx, command) ?? false,
+ },
+ ],
['transform', createTransformTool()],
['bbox', createBboxTool()],
['colorPicker', createColorPickerTool()],
['lasso', createLassoTool()],
['marquee', createMarqueeTool()],
- ['shape', createShapeTool()],
+ ['shape', createShapeTool({ getVectorTool: () => vectorRuntime?.shape ?? null })],
['gradient', createGradientTool()],
['text', createTextTool()],
['sam', createSamTool()],
@@ -475,6 +496,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
let disposed = false;
let lifecycleState: 'active' | 'cooling' | 'cool' | 'disposed' = 'active';
let lifecycleGeneration = 0;
+ let vectorWorkEpoch = 0;
let cooldownPromise: Promise<'cooled' | 'dirty'> | null = null;
// The brush/eraser cursor ring, drawn on the overlay (set by the active tool).
@@ -687,8 +709,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
structuralController.endPreview();
},
canEdit: () => canEditDocument(),
- canRedoStore: stores.canRedo,
- canUndoStore: stores.canUndo,
+ canRedoStore: { set: (value) => stores.canRedo.set(value) },
+ canUndoStore: { set: (value) => stores.canUndo.set(value) },
isGestureActive: () => pipeline.isGestureActive(),
reportFailure: (label, error) =>
opts.reportError({
@@ -1370,6 +1392,76 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
};
const canEditDocument = (owner?: symbol): boolean => mutationContext.canEdit(owner);
+ let vectorTraceAbort: AbortController | null = null;
+ let vectorRuntime: VectorRuntime | null = null;
+ let vectorPreparation: Promise<boolean> | null = null;
+ const prepareVectors = (): Promise<boolean> => {
+ if (disposed) {
+ return Promise.resolve(false);
+ }
+ if (vectorRuntime) {
+ return Promise.resolve(true);
+ }
+ if (vectorPreparation) {
+ return vectorPreparation;
+ }
+ vectorPreparation = Promise.resolve()
+ .then(() => (opts.loadVectorRuntime ? opts.loadVectorRuntime() : import('./vectorRuntime')))
+ .then(({ createVectorRuntime }) => {
+ if (disposed) {
+ return false;
+ }
+ vectorRuntime = createVectorRuntime({
+ captureInsertionAnchor: (layerId) => captureInsertionAnchor('vector', layerId),
+ session: {
+ get: () => stores.vectorEditSession.get(),
+ set: (value) => {
+ stores.vectorEditSession.set(value);
+ stores.canUndo.set(history.canUndo());
+ stores.canRedo.set(history.canRedo());
+ },
+ },
+ getDocument: () => mirror.getDocument(),
+ canEdit: () => canEditDocument(),
+ isGestureActive: () => pipeline.isGestureActive(),
+ getToolId: () => interactionController.getActiveToolId(),
+ commit: (label, forward, inverse) => commitToolStructural(label, forward, inverse),
+ invalidate: () => scheduler.invalidate({ overlay: true }),
+ createId: createLayerId,
+ reportRefusal: reportEditRefusal,
+ viewport,
+ });
+ if (lifecycleState === 'active') {
+ if (interactionController.getActiveToolId() === 'spline') {
+ vectorRuntime?.editor.onActivate();
+ } else {
+ vectorRuntime?.editor.refreshAvailability();
+ }
+ }
+ stores.vectorToolsStatus.set('ready');
+ scheduler.invalidate({ overlay: true });
+ return true;
+ })
+ .catch((error: unknown) => {
+ if (!disposed) {
+ stores.vectorToolsStatus.set('failed');
+ opts.reportError({
+ area: 'canvas-engine',
+ namespace: 'canvas',
+ projectId,
+ message: 'Vector tools could not be loaded',
+ context: { error },
+ });
+ }
+ return false;
+ })
+ .finally(() => {
+ vectorPreparation = null;
+ });
+ stores.vectorToolsStatus.set('loading');
+ return vectorPreparation;
+ };
+
const rasterExportController = new RasterExportController({
backend,
captureGuard: captureLayerExportGuard,
@@ -1518,7 +1610,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
const viewportSize = cssSize.width > 0 ? cssSize : { height: overlay.height / dpr, width: overlay.width / dpr };
renderOverlay(
overlay,
- overlayFrame.describe(doc, { dpr, view: viewport.viewMatrix(1), viewportSize }, floatRender, samPreview)
+ overlayFrame.describe(doc, { dpr, view: viewport.viewMatrix(1), viewportSize }, floatRender, samPreview),
+ vectorRuntime?.render
);
};
@@ -1672,12 +1765,15 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
let toolsReady = false;
const mirror: DocumentMirror = createDocumentMirror(mutationPort, {
onDocumentChanged: () => {
+ vectorTraceAbort?.abort();
editingController.transform.onDocumentChanged();
syncSessionEditsStagingHiddenStack();
stores.documentEpoch.set(stores.documentEpoch.get() + 1);
// A tool's cursor reads the selected layer (not-allowed over a locked or hidden one), which this may change.
// Skipped until the interaction controller exists, which the cursor reads.
if (toolsReady) {
+ vectorRuntime?.editor.onDocumentChanged();
+ tools.get('shape')?.onDocumentChanged?.(toolContext);
updateCursor();
}
},
@@ -1685,6 +1781,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
onBboxChanged: () => scheduler.invalidate({ overlay: true }),
onDocumentReplaced: () => {
const cleanup = createCleanupAccumulator();
+ cleanup.run(() => vectorRuntime?.editor.discard());
cleanup.run(() => groupSurfaces.clear());
cleanup.run(() => editingController.invalidateDocument());
cleanup.run(() => pipeline.cancelActiveGesture());
@@ -1713,6 +1810,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
cleanup.run(() => structuralController.dropPreview());
cleanup.run(() => editingController.discardSelection());
cleanup.run(() => stores.lassoPreview.set(null));
+ cleanup.run(() => tools.get('shape')?.onPointerCancel?.(toolContext));
cleanup.run(() => stores.marqueePreview.set(null));
const doc = mirror.getDocument();
const present = new Set(doc ? getDocumentLeaves(doc).map((layer) => layer.id) : []);
@@ -1930,6 +2028,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
const unsubscribeViewport = viewport.subscribe(() => {
stores.zoom.set(viewport.getZoom());
+ vectorRuntime?.editor.refreshAvailability();
if (!suppressViewportInvalidate) {
scheduler.invalidate({ view: true });
}
@@ -2012,7 +2111,24 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
updateCursor();
}
});
+ let toolRequest = 0;
const setTool = (toolId: ToolId, options?: { temporary?: boolean }): void => {
+ const request = ++toolRequest;
+ if (toolId === 'spline' && !vectorRuntime) {
+ const generation = vectorWorkEpoch;
+ void prepareVectors().then((ready) => {
+ if (
+ ready &&
+ !disposed &&
+ request === toolRequest &&
+ vectorWorkEpoch === generation &&
+ lifecycleState === 'active'
+ ) {
+ setTool(toolId, options);
+ }
+ });
+ return;
+ }
colorSamples.onToolChange(toolId);
interactionController.setTool(toolId, options);
};
@@ -2024,6 +2140,18 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
* with pipeline wiring and node tests.
*/
const handleEscapePriority = ({ gestureWasActive }: { gestureWasActive: boolean }): void => {
+ if (vectorTraceAbort) {
+ vectorTraceAbort.abort();
+ return;
+ }
+ if (tools.get('shape')?.hasSession?.()) {
+ tools.get('shape')?.onKeyCommand?.(toolContext, 'cancel');
+ return;
+ }
+ if (vectorRuntime?.editor.hasSession()) {
+ vectorRuntime?.editor.onKeyCommand(toolContext, 'cancel');
+ return;
+ }
if (colorSamples.onEscape()) {
return;
}
@@ -2140,10 +2268,12 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
lifecycleGeneration += 1;
lifecycleState = 'active';
editingController.activate();
+ vectorRuntime?.editor.onDocumentChanged();
cooldownPromise = null;
};
const beginCooldown = (): Promise<'cooled' | 'dirty'> => {
+ vectorWorkEpoch += 1;
if (disposed) {
return Promise.resolve('cooled');
}
@@ -2158,6 +2288,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
lifecycleGeneration += 1;
const generation = lifecycleGeneration;
lifecycleState = 'cooling';
+ vectorTraceAbort?.abort();
+ vectorRuntime?.editor.discard();
editingController.cooldown();
clearStagedPreview();
clearStagedPreviewCache();
@@ -2687,6 +2819,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
return;
}
disposed = true;
+ vectorWorkEpoch += 1;
paintLineEnds.dispose();
disposeLayerRasterizer();
releaseActiveSnapshots();
@@ -2702,6 +2835,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
cleanup.run(() => generatedResultController.dispose());
cleanup.run(() => stagedResultController.dispose());
cleanup.run(() => editingController.dispose());
+ cleanup.run(() => vectorTraceAbort?.abort());
+ cleanup.run(() => vectorRuntime?.editor.discard());
cleanup.run(() => layerController.dispose());
cleanup.run(() => layerMutationController.dispose());
cleanup.run(() => maskResultController.dispose());
@@ -2805,6 +2940,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
*/
const canTargetLayerFromContextMenu = (): boolean =>
!pipeline.isGestureActive() &&
+ !vectorRuntime?.editor.hasSession() &&
!stores.transformSession.get() &&
!stores.textEditSession.get() &&
mirror.getDocument() !== null;
@@ -3051,6 +3187,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
};
const toolsCapability: CanvasEngineToolCapability = {
...interactionController.tools,
+ setTool,
canTargetLayerFromContextMenu,
handleEscapePriority,
onEditRefused,
@@ -3058,8 +3195,81 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
requestColorSample: () => colorSamples.requestSample(),
setColorSampleRouter: (router) => colorSamples.setRouter(router),
};
+ const runVectorTrace = async (layerId: string, mode: 'trace' | 'fill' | 'appearance', pathId?: string) => {
+ vectorTraceAbort?.abort();
+ const controller = new AbortController();
+ vectorTraceAbort = controller;
+ const document = mirror.getDocument();
+ try {
+ if (!document) {
+ return { status: 'not-ready' as const };
+ }
+ if (!(await prepareVectors()) || !vectorRuntime) {
+ return { status: 'not-ready' as const };
+ }
+ return await vectorRuntime.trace({
+ document,
+ layerId,
+ pathId,
+ appearance: mode === 'appearance',
+ fillOnly: mode === 'fill',
+ ctx: mutationContext,
+ backend,
+ id: createLayerId(),
+ anchor: captureInsertionAnchor('raster', null),
+ signal: controller.signal,
+ isCurrent: () => !disposed && mirror.getDocument() === document,
+ });
+ } finally {
+ if (vectorTraceAbort === controller) {
+ vectorTraceAbort = null;
+ }
+ }
+ };
const layersCapability: CanvasEngineLayerCapability = {
...layerController.layers,
+ traceVectorLayer: (layerId, pathId) => runVectorTrace(layerId, 'trace', pathId),
+ fillVectorPath: (layerId, pathId) => runVectorTrace(layerId, 'fill', pathId),
+ traceFillVectorLayer: (layerId) => runVectorTrace(layerId, 'appearance'),
+ cancelVectorTrace: () => vectorTraceAbort?.abort(),
+ vectorEdit: {
+ prepare: prepareVectors,
+ createLayer: async (input) => {
+ const document = mirror.getDocument();
+ const generation = vectorWorkEpoch;
+ if (!document) {
+ return null;
+ }
+ if (
+ !(await prepareVectors()) ||
+ !vectorRuntime ||
+ disposed ||
+ lifecycleState !== 'active' ||
+ vectorWorkEpoch !== generation ||
+ mirror.getDocument() !== document
+ ) {
+ return null;
+ }
+ return vectorRuntime.createLayer({
+ ...input,
+ name:
+ input.name || vectorRuntime.nextLayerName(getDocumentIndex(document).nodes.map((entry) => entry.node.name)),
+ });
+ },
+ setPointType: (type) => vectorRuntime?.editor.setPointType(type),
+ targetContextMenu: (point) => vectorRuntime?.editor.targetContextMenu(point) ?? false,
+ deletePath: () => vectorRuntime?.editor.deletePath(),
+ nudge: (dx, dy) => vectorRuntime?.editor.nudge(dx, dy),
+ smooth: (selectedOnly) => vectorRuntime?.editor.smooth(selectedOnly),
+ deleteSelection: () => vectorRuntime?.editor.deleteSelection(),
+ copyPath: () => vectorRuntime?.editor.copyPath(),
+ extractPath: () => vectorRuntime?.editor.extractPath(),
+ transformPath: () => vectorRuntime?.editor.transformPath(),
+ split: () => vectorRuntime?.editor.split(),
+ join: () => vectorRuntime?.editor.join(),
+ canSplit: () => vectorRuntime?.editor.canSplit() ?? false,
+ canJoin: () => vectorRuntime?.editor.canJoin() ?? false,
+ },
applyTransform,
beginTransform: (layerId) => editingController.transform.request(layerId),
booleanMergeRasterLayers,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
index cc05e40ecf..21bb10071d 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
@@ -12,9 +12,11 @@ import type {
ParametricShapeKind,
} from '@workbench/canvas-engine/contracts';
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 { Rect, SelectionOp, ToolId, Vec2 } from '@workbench/canvas-engine/types';
+import type { VectorEditSession } from '@workbench/canvas-engine/vectorEditState';
import { type CheckerColors, DEFAULT_CHECKER_COLORS } from '@workbench/canvas-engine/render/compositor';
@@ -503,6 +505,10 @@ export interface EngineStores {
textEditSession: ScalarStore<TextEditSession | null>;
/** Document-space shape preview replaces dispatch during drag; null when idle, cleared on commit/cancel. */
shapePreview: ScalarStore<{ rect: Rect; kind: ParametricShapeKind } | null>;
+ /** Vector creation preview is guide geometry, never a rasterization source. */
+ vectorShapePreview: ScalarStore<VectorShapePreview | null>;
+ vectorEditSession: ScalarStore<VectorEditSession | null>;
+ vectorToolsStatus: ScalarStore<'idle' | 'loading' | 'ready' | 'failed'>;
/** Document-space gradient drag vector; overlay shows a linear ramp or radial circle. Cleared on commit/cancel. */
gradientPreview: ScalarStore<GradientPreview | null>;
hasSelection: ScalarStore<boolean>;
@@ -754,6 +760,9 @@ export const createEngineStores = (initialTool: ToolId = 'view'): EngineStores =
samInteraction: createScalarStore(null),
shapeOptions: createScalarStore<ShapeToolOptions>({ ...DEFAULT_SHAPE_OPTIONS }, shapeOptionsEqual),
shapePreview: createScalarStore<{ rect: Rect; kind: ParametricShapeKind } | null>(null, rectShapePreviewEqual),
+ vectorShapePreview: createScalarStore<VectorShapePreview | null>(null),
+ vectorEditSession: createScalarStore<VectorEditSession | null>(null),
+ vectorToolsStatus: createScalarStore<'idle' | 'loading' | 'ready' | 'failed'>('idle'),
showBbox: createScalarStore<boolean>(true),
showGrid: createScalarStore<boolean>(false),
snapToGrid: createScalarStore<boolean>(true),
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.ts
index 8c9640e909..0112e232df 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.ts
@@ -8,6 +8,9 @@
import type { Rect, Vec2 } from '@workbench/canvas-engine/types';
+import { polygonBounds } from '@workbench/canvas-engine/math/rect';
+export { polygonBounds } from '@workbench/canvas-engine/math/rect';
+
import { getStrokeOutlinePoints, getStrokePoints } from 'perfect-freehand';
/** A single pressure-sampled input point for a stroke. */
@@ -219,32 +222,6 @@ export const traceSmoothPolygon = (path: Path2D, polygon: readonly Vec2[]): void
path.closePath();
};
-/** Axis-aligned bounds of an outline polygon; an empty polygon yields a zero-size rect. */
-export const polygonBounds = (polygon: readonly Vec2[]): Rect => {
- if (polygon.length === 0) {
- return { height: 0, width: 0, x: 0, y: 0 };
- }
- let minX = Infinity;
- let minY = Infinity;
- let maxX = -Infinity;
- let maxY = -Infinity;
- for (const p of polygon) {
- if (p.x < minX) {
- minX = p.x;
- }
- if (p.y < minY) {
- minY = p.y;
- }
- if (p.x > maxX) {
- maxX = p.x;
- }
- if (p.y > maxY) {
- maxY = p.y;
- }
- }
- return { height: maxY - minY, width: maxX - minX, x: minX, y: minY };
-};
-
/** Traces an outline polygon into a fresh path and reports its bounds. */
export const polygonToPath = (
polygon: Vec2[],
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.ts
index 380cd88eee..d8fb97223e 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.ts
@@ -887,4 +887,29 @@ describe('pointer pipeline: cancellation ownership', () => {
expect(order).toEqual(['cancel:view', 'set:brush']);
expect(h.pipeline.isGestureActive()).toBe(false);
});
+
+ it('releases tool-owned modifiers on blur reset when their keyup was missed between presses', () => {
+ const h = createHarness();
+ const held = new Set<string>();
+ h.tool.onModifierKey = (_ctx, modifier, pressed) => {
+ if (pressed) {
+ held.add(modifier);
+ } else {
+ held.delete(modifier);
+ }
+ return true;
+ };
+ const moves: string[][] = [];
+ h.tool.onPointerMove = () => moves.push([...held]);
+ h.pipeline.onPointerEnter();
+ h.pipeline.onKeyDown(makeKeyEvent({ code: 'Space', target: SURFACE_TARGET }));
+ h.pipeline.onKeyDown(makeKeyEvent({ key: 'Alt', code: 'AltLeft', target: SURFACE_TARGET }));
+ h.pipeline.onKeyDown(makeKeyEvent({ key: 'Shift', target: SURFACE_TARGET }));
+ expect(held.size).toBe(3);
+ h.pipeline.reset();
+ h.pipeline.onPointerEnter();
+ h.pipeline.onPointerDown(makePointerEvent());
+ h.pipeline.onPointerMove(makePointerEvent({ clientX: 50, clientY: 50 }));
+ expect(moves).toEqual([[]]);
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts
index 4fca445379..2749917ccf 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts
@@ -445,7 +445,14 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin
return;
}
if (event.code === 'Space' && !event.repeat) {
- if (event.ctrlKey || event.metaKey || event.altKey || holdOwner(event) === null) {
+ if (event.ctrlKey || event.metaKey || holdOwner(event) === null) {
+ return;
+ }
+ if (deps.getActiveTool()?.onModifierKey?.(deps.getToolContext(), 'Space', true)) {
+ event.preventDefault();
+ return;
+ }
+ if (event.altKey) {
return;
}
beginTempTool('space', SPACE_TEMP_TOOL);
@@ -461,6 +468,9 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin
// Firefox and Windows activate the menu bar on a lone Alt unless both its press and release are prevented.
event.preventDefault();
altClaimed = true;
+ if (deps.getActiveTool()?.onModifierKey?.(deps.getToolContext(), 'Alt', true)) {
+ return;
+ }
// A tool that reads Alt as a gesture modifier keeps it; pointer events still carry `altKey`.
if (deps.getActiveTool()?.usesAltKey) {
return;
@@ -475,6 +485,9 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin
if (isBboxKey(event) && !event.repeat && ownsSessionKey(event)) {
beginBboxTempTool();
}
+ if (event.key === 'Shift' && holdOwner(event) !== null) {
+ deps.getActiveTool()?.onModifierKey?.(deps.getToolContext(), 'Shift', true);
+ }
},
heldRestoreToolId: () => (tempHold && tempSwitched ? priorToolId : null),
hoverPoint: () => hoverPoint,
@@ -483,6 +496,11 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin
pointerFocused = event.target && arrivedByPointer(event.target) ? new WeakRef(event.target) : null;
},
onKeyUp: (event) => {
+ const modifier =
+ event.code === 'Space' ? 'Space' : isAltKey(event) ? 'Alt' : event.key === 'Shift' ? 'Shift' : null;
+ if (modifier) {
+ deps.getActiveTool()?.onModifierKey?.(deps.getToolContext(), modifier, false);
+ }
if (event.code === 'Space' && tempHold === 'space') {
releaseTempTool();
} else if (isAltKey(event)) {
@@ -638,6 +656,12 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin
endTempTool();
}
clearBboxTapTimer();
+ // Tool-owned holds can outlive a press (polygon drafts) and miss keyup while the window is unfocused.
+ const tool = deps.getActiveTool();
+ const ctx = deps.getToolContext();
+ for (const modifier of ['Space', 'Alt', 'Shift'] as const) {
+ tool?.onModifierKey?.(ctx, modifier, false);
+ }
altPending = false;
altClaimed = false;
hovered = false;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/math/bezierPath.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/bezierPath.ts
new file mode 100644
index 0000000000..1faadfd93c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/bezierPath.ts
@@ -0,0 +1,790 @@
+import type { CanvasBezierPathContract, CanvasBezierPointContract } from '@workbench/canvas-engine/contracts';
+import type { Mat2d, Rect, Vec2 } from '@workbench/canvas-engine/types';
+
+/** Bezier geometry and editing math adapted from v6 feat(canvas)--Splines-tool (c4c0594261). */
+import { applyToPoint } from './mat2d';
+import { evaluateBezierSegment } from './rect';
+export { getBezierPathBounds } from './rect';
+
+type RenderableBezierPoint = Pick<CanvasBezierPointContract, 'anchor' | 'inHandle' | 'outHandle'>;
+
+type BezierPointHandleType = 'inHandle' | 'outHandle';
+
+export type BezierPointType = CanvasBezierPointContract['type'];
+
+type BezierPathSegmentHit = {
+ segmentIndex: number;
+ t: number;
+ point: Vec2;
+ distance: number;
+};
+
+type CubicBezierSegment = [Vec2, Vec2, Vec2, Vec2];
+
+const DEFAULT_BEZIER_PATH_SAMPLES_PER_SEGMENT = 24;
+
+const BEZIER_FIT_EPSILON = 1e-12;
+
+const SMOOTH_HANDLE_MAX_SEGMENT_RATIO = 2 / 3;
+
+const CENTRIPETAL_CATMULL_ROM_ALPHA = 0.5;
+
+const getDistance = (a: Vec2, b: Vec2) => Math.hypot(a.x - b.x, a.y - b.y);
+
+const lerpCoordinate = (a: Vec2, b: Vec2, t: number): Vec2 => ({
+ x: a.x + (b.x - a.x) * t,
+ y: a.y + (b.y - a.y) * t,
+});
+
+const addCoordinate = (a: Vec2, b: Vec2): Vec2 => ({ x: a.x + b.x, y: a.y + b.y });
+
+const subtractCoordinate = (a: Vec2, b: Vec2): Vec2 => ({ x: a.x - b.x, y: a.y - b.y });
+
+const scaleCoordinate = (coordinate: Vec2, scale: number): Vec2 => ({
+ x: coordinate.x * scale,
+ y: coordinate.y * scale,
+});
+
+const dotCoordinates = (a: Vec2, b: Vec2): number => a.x * b.x + a.y * b.y;
+
+const normalizeCoordinate = (coordinate: Vec2): Vec2 => {
+ const length = Math.hypot(coordinate.x, coordinate.y);
+ return length <= BEZIER_FIT_EPSILON ? { x: 0, y: 0 } : scaleCoordinate(coordinate, 1 / length);
+};
+
+const getSquaredDistance = (a: Vec2, b: Vec2): number => (a.x - b.x) ** 2 + (a.y - b.y) ** 2;
+
+const normalizeHandle = (anchor: Vec2, handle: Vec2): Vec2 | null =>
+ anchor.x === handle.x && anchor.y === handle.y ? null : handle;
+
+const mirrorHandle = (anchor: Vec2, handle: Vec2): Vec2 => ({
+ x: anchor.x + (anchor.x - handle.x),
+ y: anchor.y + (anchor.y - handle.y),
+});
+
+const getOppositeHandleType = (handleType: BezierPointHandleType): BezierPointHandleType =>
+ handleType === 'inHandle' ? 'outHandle' : 'inHandle';
+
+const getCollinearOppositeHandle = (anchor: Vec2, handle: Vec2, length: number): Vec2 | null => {
+ const sourceLength = getDistance(anchor, handle);
+ if (sourceLength === 0 || length === 0) {
+ return null;
+ }
+
+ const scale = length / sourceLength;
+ return {
+ x: anchor.x + (anchor.x - handle.x) * scale,
+ y: anchor.y + (anchor.y - handle.y) * scale,
+ };
+};
+
+const getPreferredHandleType = (
+ point: CanvasBezierPointContract,
+ preferredHandleType?: BezierPointHandleType | null
+): BezierPointHandleType | null => {
+ if (preferredHandleType && point[preferredHandleType]) {
+ return preferredHandleType;
+ }
+ if (point.outHandle) {
+ return 'outHandle';
+ }
+ if (point.inHandle) {
+ return 'inHandle';
+ }
+ return null;
+};
+
+const syncOppositeHandleForPointType = (point: CanvasBezierPointContract, sourceHandleType: BezierPointHandleType) => {
+ const sourceHandle = point[sourceHandleType];
+ const oppositeHandleType = getOppositeHandleType(sourceHandleType);
+ if (point.type === 'corner') {
+ return;
+ }
+ if (!sourceHandle) {
+ point[oppositeHandleType] = null;
+ return;
+ }
+ if (point.type === 'symmetric') {
+ point[oppositeHandleType] = normalizeHandle(point.anchor, mirrorHandle(point.anchor, sourceHandle));
+ return;
+ }
+
+ const oppositeHandle = point[oppositeHandleType];
+ const oppositeLength = oppositeHandle
+ ? getDistance(point.anchor, oppositeHandle)
+ : getDistance(point.anchor, sourceHandle);
+ point[oppositeHandleType] = normalizeHandle(
+ point.anchor,
+ getCollinearOppositeHandle(point.anchor, sourceHandle, oppositeLength) ?? point.anchor
+ );
+};
+
+export const setBezierPointType = (
+ point: CanvasBezierPointContract,
+ type: BezierPointType,
+ preferredHandleType?: BezierPointHandleType | null
+) => {
+ point.type = type;
+ const sourceHandleType = getPreferredHandleType(point, preferredHandleType);
+ if (!sourceHandleType) {
+ return;
+ }
+
+ syncOppositeHandleForPointType(point, sourceHandleType);
+};
+
+export const setBezierPointTypes = (
+ points: CanvasBezierPointContract[],
+ pointIndices: number[],
+ type: BezierPointType,
+ preferredPointIndex?: number | null,
+ preferredHandleType?: BezierPointHandleType | null
+) => {
+ for (const pointIndex of new Set(pointIndices)) {
+ const point = points[pointIndex];
+ if (!point) {
+ continue;
+ }
+ setBezierPointType(point, type, pointIndex === preferredPointIndex ? preferredHandleType : null);
+ }
+};
+
+export const setBezierPointHandle = (
+ point: CanvasBezierPointContract,
+ handleType: BezierPointHandleType,
+ handle: Vec2
+) => {
+ point[handleType] = normalizeHandle(point.anchor, handle);
+ syncOppositeHandleForPointType(point, handleType);
+};
+
+export const getBezierPointPullHandleType = (
+ points: Pick<CanvasBezierPointContract, 'anchor'>[],
+ isClosed: boolean,
+ pointIndex: number,
+ pointer: Vec2
+): 'inHandle' | 'outHandle' => {
+ const point = points[pointIndex];
+ if (!point) {
+ return 'outHandle';
+ }
+
+ if (!isClosed) {
+ if (pointIndex === 0) {
+ return 'outHandle';
+ }
+ if (pointIndex === points.length - 1) {
+ return 'inHandle';
+ }
+ }
+
+ const previousPoint = isClosed ? points.at(pointIndex - 1) : points[pointIndex - 1];
+ const nextPoint = isClosed ? points[(pointIndex + 1) % points.length] : points[pointIndex + 1];
+ if (!previousPoint) {
+ return 'outHandle';
+ }
+ if (!nextPoint) {
+ return 'inHandle';
+ }
+
+ const dragVector = {
+ x: pointer.x - point.anchor.x,
+ y: pointer.y - point.anchor.y,
+ };
+ const dragLength = Math.hypot(dragVector.x, dragVector.y);
+ if (dragLength === 0) {
+ return 'outHandle';
+ }
+
+ const getDirectionScore = (target: Vec2) => {
+ const direction = {
+ x: target.x - point.anchor.x,
+ y: target.y - point.anchor.y,
+ };
+ const directionLength = Math.hypot(direction.x, direction.y);
+ if (directionLength === 0) {
+ return -Infinity;
+ }
+
+ return (dragVector.x * direction.x + dragVector.y * direction.y) / directionLength;
+ };
+
+ return getDirectionScore(previousPoint.anchor) > getDirectionScore(nextPoint.anchor) ? 'inHandle' : 'outHandle';
+};
+
+export const anchorsToBezierPoints = (anchors: Vec2[]): CanvasBezierPointContract[] => {
+ return anchors.map((anchor) => ({
+ anchor,
+ inHandle: null,
+ outHandle: null,
+ type: 'corner',
+ }));
+};
+
+const evaluateCubicBezier = (segment: CubicBezierSegment, t: number): Vec2 => {
+ const [p0, p1, p2, p3] = segment;
+ const mt = 1 - t;
+ const mt2 = mt * mt;
+ const t2 = t * t;
+
+ return {
+ x: mt2 * mt * p0.x + 3 * mt2 * t * p1.x + 3 * mt * t2 * p2.x + t2 * t * p3.x,
+ y: mt2 * mt * p0.y + 3 * mt2 * t * p1.y + 3 * mt * t2 * p2.y + t2 * t * p3.y,
+ };
+};
+
+const evaluateCubicBezierDerivative = (segment: CubicBezierSegment, t: number): Vec2 => {
+ const [p0, p1, p2, p3] = segment;
+ const mt = 1 - t;
+
+ return scaleCoordinate(
+ addCoordinate(
+ addCoordinate(
+ scaleCoordinate(subtractCoordinate(p1, p0), mt * mt),
+ scaleCoordinate(subtractCoordinate(p2, p1), 2 * mt * t)
+ ),
+ scaleCoordinate(subtractCoordinate(p3, p2), t * t)
+ ),
+ 3
+ );
+};
+
+const evaluateCubicBezierSecondDerivative = (segment: CubicBezierSegment, t: number): Vec2 => {
+ const [p0, p1, p2, p3] = segment;
+ const first = addCoordinate(subtractCoordinate(p2, scaleCoordinate(p1, 2)), p0);
+ const second = addCoordinate(subtractCoordinate(p3, scaleCoordinate(p2, 2)), p1);
+ return scaleCoordinate(addCoordinate(scaleCoordinate(first, 1 - t), scaleCoordinate(second, t)), 6);
+};
+
+const chordLengthParameterize = (points: Vec2[], first: number, last: number): number[] => {
+ const parameters = [0];
+ for (let i = first + 1; i <= last; i += 1) {
+ const previous = points[i - 1];
+ const current = points[i];
+ if (!previous || !current) {
+ continue;
+ }
+ parameters.push((parameters.at(-1) ?? 0) + Math.sqrt(getSquaredDistance(previous, current)));
+ }
+
+ const totalLength = parameters.at(-1) ?? 0;
+ if (totalLength <= BEZIER_FIT_EPSILON) {
+ return parameters.map((_, index) => index / Math.max(1, parameters.length - 1));
+ }
+ return parameters.map((parameter) => parameter / totalLength);
+};
+
+const generateBezierSegment = (
+ points: Vec2[],
+ first: number,
+ last: number,
+ parameters: number[],
+ leftTangent: Vec2,
+ rightTangent: Vec2
+): CubicBezierSegment => {
+ const start = points[first];
+ const end = points[last];
+ if (!start || !end) {
+ throw new Error('Cannot fit a Bezier segment without endpoints');
+ }
+
+ let c00 = 0;
+ let c01 = 0;
+ let c11 = 0;
+ let x0 = 0;
+ let x1 = 0;
+
+ for (let i = 0; i <= last - first; i += 1) {
+ const point = points[first + i];
+ const parameter = parameters[i];
+ if (!point || parameter === undefined) {
+ continue;
+ }
+
+ const mt = 1 - parameter;
+ const b0 = mt ** 3;
+ const b1 = 3 * parameter * mt ** 2;
+ const b2 = 3 * parameter ** 2 * mt;
+ const b3 = parameter ** 3;
+ const a1 = scaleCoordinate(leftTangent, b1);
+ const a2 = scaleCoordinate(rightTangent, b2);
+ const basePoint = addCoordinate(scaleCoordinate(start, b0 + b1), scaleCoordinate(end, b2 + b3));
+ const residual = subtractCoordinate(point, basePoint);
+
+ c00 += dotCoordinates(a1, a1);
+ c01 += dotCoordinates(a1, a2);
+ c11 += dotCoordinates(a2, a2);
+ x0 += dotCoordinates(a1, residual);
+ x1 += dotCoordinates(a2, residual);
+ }
+
+ const determinant = c00 * c11 - c01 * c01;
+ let alphaLeft = determinant === 0 ? 0 : (x0 * c11 - x1 * c01) / determinant;
+ let alphaRight = determinant === 0 ? 0 : (c00 * x1 - c01 * x0) / determinant;
+ const segmentLength = Math.sqrt(getSquaredDistance(start, end));
+ const minimumAlpha = segmentLength * 1e-6;
+
+ if (alphaLeft < minimumAlpha || alphaRight < minimumAlpha) {
+ alphaLeft = segmentLength / 3;
+ alphaRight = segmentLength / 3;
+ }
+
+ return [
+ start,
+ addCoordinate(start, scaleCoordinate(leftTangent, alphaLeft)),
+ addCoordinate(end, scaleCoordinate(rightTangent, alphaRight)),
+ end,
+ ];
+};
+
+const getMaximumBezierFitError = (
+ points: Vec2[],
+ first: number,
+ last: number,
+ segment: CubicBezierSegment,
+ parameters: number[]
+): { error: number; splitPoint: number } => {
+ let maximumError = 0;
+ let splitPoint = Math.floor((first + last) / 2);
+
+ for (let i = first + 1; i < last; i += 1) {
+ const point = points[i];
+ const parameter = parameters[i - first];
+ if (!point || parameter === undefined) {
+ continue;
+ }
+ const error = getSquaredDistance(evaluateCubicBezier(segment, parameter), point);
+ if (error > maximumError) {
+ maximumError = error;
+ splitPoint = i;
+ }
+ }
+
+ return { error: maximumError, splitPoint };
+};
+
+const reparameterizeBezierFit = (
+ points: Vec2[],
+ first: number,
+ parameters: number[],
+ segment: CubicBezierSegment
+): number[] => {
+ return parameters.map((parameter, index) => {
+ const point = points[first + index];
+ if (!point) {
+ return parameter;
+ }
+
+ const curvePoint = evaluateCubicBezier(segment, parameter);
+ const firstDerivative = evaluateCubicBezierDerivative(segment, parameter);
+ const secondDerivative = evaluateCubicBezierSecondDerivative(segment, parameter);
+ const difference = subtractCoordinate(curvePoint, point);
+ const denominator = dotCoordinates(firstDerivative, firstDerivative) + dotCoordinates(difference, secondDerivative);
+ if (Math.abs(denominator) <= BEZIER_FIT_EPSILON) {
+ return parameter;
+ }
+ return Math.max(0, Math.min(1, parameter - dotCoordinates(difference, firstDerivative) / denominator));
+ });
+};
+
+const fitCubicBezierSegments = (
+ points: Vec2[],
+ first: number,
+ last: number,
+ leftTangent: Vec2,
+ rightTangent: Vec2,
+ maximumErrorSquared: number,
+ segments: CubicBezierSegment[]
+) => {
+ const start = points[first];
+ const end = points[last];
+ if (!start || !end) {
+ return;
+ }
+
+ if (last - first === 1) {
+ const handleLength = Math.sqrt(getSquaredDistance(start, end)) / 3;
+ segments.push([
+ start,
+ addCoordinate(start, scaleCoordinate(leftTangent, handleLength)),
+ addCoordinate(end, scaleCoordinate(rightTangent, handleLength)),
+ end,
+ ]);
+ return;
+ }
+
+ let parameters = chordLengthParameterize(points, first, last);
+ let segment = generateBezierSegment(points, first, last, parameters, leftTangent, rightTangent);
+ let fit = getMaximumBezierFitError(points, first, last, segment, parameters);
+
+ if (fit.error <= maximumErrorSquared) {
+ segments.push(segment);
+ return;
+ }
+
+ if (fit.error <= maximumErrorSquared * 4) {
+ for (let i = 0; i < 4; i += 1) {
+ parameters = reparameterizeBezierFit(points, first, parameters, segment);
+ segment = generateBezierSegment(points, first, last, parameters, leftTangent, rightTangent);
+ fit = getMaximumBezierFitError(points, first, last, segment, parameters);
+ if (fit.error <= maximumErrorSquared) {
+ segments.push(segment);
+ return;
+ }
+ }
+ }
+
+ const splitPoint = fit.splitPoint;
+ const beforeSplit = points[splitPoint - 1];
+ const afterSplit = points[splitPoint + 1];
+ if (!beforeSplit || !afterSplit) {
+ return;
+ }
+ const centerTangent = normalizeCoordinate(subtractCoordinate(beforeSplit, afterSplit));
+
+ fitCubicBezierSegments(points, first, splitPoint, leftTangent, centerTangent, maximumErrorSquared, segments);
+ fitCubicBezierSegments(
+ points,
+ splitPoint,
+ last,
+ scaleCoordinate(centerTangent, -1),
+ rightTangent,
+ maximumErrorSquared,
+ segments
+ );
+};
+
+export const fitPolylineToBezierPoints = (inputPoints: Vec2[], maximumError: number): CanvasBezierPointContract[] => {
+ const points = inputPoints.filter((point, index) => {
+ const previous = inputPoints[index - 1];
+ return !previous || getSquaredDistance(point, previous) > BEZIER_FIT_EPSILON;
+ });
+ const firstPoint = points[0];
+ const secondPoint = points[1];
+ const lastPoint = points.at(-1);
+ const penultimatePoint = points.at(-2);
+ if (!firstPoint || !secondPoint || !lastPoint || !penultimatePoint) {
+ return [];
+ }
+
+ const segments: CubicBezierSegment[] = [];
+ fitCubicBezierSegments(
+ points,
+ 0,
+ points.length - 1,
+ normalizeCoordinate(subtractCoordinate(secondPoint, firstPoint)),
+ normalizeCoordinate(subtractCoordinate(penultimatePoint, lastPoint)),
+ Math.max(maximumError, BEZIER_FIT_EPSILON) ** 2,
+ segments
+ );
+ const firstSegment = segments[0];
+ if (!firstSegment) {
+ return [];
+ }
+
+ const bezierPoints: CanvasBezierPointContract[] = [
+ {
+ anchor: firstSegment[0],
+ inHandle: null,
+ outHandle: normalizeHandle(firstSegment[0], firstSegment[1]),
+ type: 'smooth',
+ },
+ ];
+
+ for (const segment of segments) {
+ const previousPoint = bezierPoints.at(-1);
+ if (!previousPoint) {
+ continue;
+ }
+ previousPoint.outHandle = normalizeHandle(previousPoint.anchor, segment[1]);
+ bezierPoints.push({
+ anchor: segment[3],
+ inHandle: normalizeHandle(segment[3], segment[2]),
+ outHandle: null,
+ type: 'smooth',
+ });
+ }
+
+ return bezierPoints;
+};
+
+export const rectToBezierPoints = (rect: Rect): CanvasBezierPointContract[] => {
+ const { x, y, width, height } = rect;
+ return anchorsToBezierPoints([
+ { x, y },
+ { x: x + width, y },
+ { x: x + width, y: y + height },
+ { x, y: y + height },
+ ]);
+};
+
+export const ovalToBezierPoints = (rect: Rect): CanvasBezierPointContract[] => {
+ const controlPointRatio = (4 * (Math.sqrt(2) - 1)) / 3;
+ const radiusX = rect.width / 2;
+ const radiusY = rect.height / 2;
+ const centerX = rect.x + radiusX;
+ const centerY = rect.y + radiusY;
+ const controlOffsetX = radiusX * controlPointRatio;
+ const controlOffsetY = radiusY * controlPointRatio;
+
+ return [
+ {
+ anchor: { x: centerX, y: rect.y },
+ inHandle: { x: centerX - controlOffsetX, y: rect.y },
+ outHandle: { x: centerX + controlOffsetX, y: rect.y },
+ type: 'symmetric',
+ },
+ {
+ anchor: { x: rect.x + rect.width, y: centerY },
+ inHandle: { x: rect.x + rect.width, y: centerY - controlOffsetY },
+ outHandle: { x: rect.x + rect.width, y: centerY + controlOffsetY },
+ type: 'symmetric',
+ },
+ {
+ anchor: { x: centerX, y: rect.y + rect.height },
+ inHandle: { x: centerX + controlOffsetX, y: rect.y + rect.height },
+ outHandle: { x: centerX - controlOffsetX, y: rect.y + rect.height },
+ type: 'symmetric',
+ },
+ {
+ anchor: { x: rect.x, y: centerY },
+ inHandle: { x: rect.x, y: centerY + controlOffsetY },
+ outHandle: { x: rect.x, y: centerY - controlOffsetY },
+ type: 'symmetric',
+ },
+ ];
+};
+
+const getSmoothTangent = (previousAnchor: Vec2 | null, anchor: Vec2, nextAnchor: Vec2 | null): Vec2 => {
+ const previousDistance = previousAnchor ? getDistance(previousAnchor, anchor) : 0;
+ const nextDistance = nextAnchor ? getDistance(anchor, nextAnchor) : 0;
+ const previousInterval = previousDistance ** CENTRIPETAL_CATMULL_ROM_ALPHA;
+ const nextInterval = nextDistance ** CENTRIPETAL_CATMULL_ROM_ALPHA;
+
+ if (previousAnchor && nextAnchor && previousInterval > BEZIER_FIT_EPSILON && nextInterval > BEZIER_FIT_EPSILON) {
+ const tangent = addCoordinate(
+ subtractCoordinate(
+ scaleCoordinate(subtractCoordinate(anchor, previousAnchor), 1 / previousInterval),
+ scaleCoordinate(subtractCoordinate(nextAnchor, previousAnchor), 1 / (previousInterval + nextInterval))
+ ),
+ scaleCoordinate(subtractCoordinate(nextAnchor, anchor), 1 / nextInterval)
+ );
+ return tangent;
+ }
+
+ if (nextAnchor && nextInterval > BEZIER_FIT_EPSILON) {
+ return scaleCoordinate(subtractCoordinate(nextAnchor, anchor), 1 / nextInterval);
+ }
+
+ if (previousAnchor && previousInterval > BEZIER_FIT_EPSILON) {
+ return scaleCoordinate(subtractCoordinate(anchor, previousAnchor), 1 / previousInterval);
+ }
+
+ return { x: 0, y: 0 };
+};
+
+const getSmoothTurningAngle = (previousAnchor: Vec2 | null, anchor: Vec2, nextAnchor: Vec2 | null): number => {
+ if (!previousAnchor || !nextAnchor) {
+ return 0;
+ }
+
+ const incomingDirection = normalizeCoordinate(subtractCoordinate(anchor, previousAnchor));
+ const outgoingDirection = normalizeCoordinate(subtractCoordinate(nextAnchor, anchor));
+ const directionDot = Math.max(-1, Math.min(1, dotCoordinates(incomingDirection, outgoingDirection)));
+ return Math.acos(directionDot);
+};
+
+const getCircularArcHandleLength = (segmentLength: number, turningAngle: number): number => {
+ const cosine = Math.cos(turningAngle / 4);
+ const circularArcLength = segmentLength / (3 * cosine * cosine);
+ return Math.min(circularArcLength, segmentLength * SMOOTH_HANDLE_MAX_SEGMENT_RATIO);
+};
+
+export const smoothBezierPathPoints = (
+ points: CanvasBezierPointContract[],
+ isClosed: boolean
+): CanvasBezierPointContract[] => {
+ if (points.length < 2) {
+ return points.map((point) => ({ ...point }));
+ }
+
+ const lastPointIndex = points.length - 1;
+
+ return points.map((point, pointIndex) => {
+ if (point.type === 'symmetric' && point.inHandle && point.outHandle) {
+ return { ...point };
+ }
+
+ const previousPoint = isClosed ? points[(pointIndex - 1 + points.length) % points.length] : points[pointIndex - 1];
+ const nextPoint = isClosed ? points[(pointIndex + 1) % points.length] : points[pointIndex + 1];
+ const previousAnchor = previousPoint?.anchor ?? null;
+ const nextAnchor = nextPoint?.anchor ?? null;
+ const tangentDirection = normalizeCoordinate(getSmoothTangent(previousAnchor, point.anchor, nextAnchor));
+ const turningAngle = getSmoothTurningAngle(previousAnchor, point.anchor, nextAnchor);
+ const inHandleLength = getCircularArcHandleLength(
+ previousAnchor ? getDistance(point.anchor, previousAnchor) : 0,
+ turningAngle
+ );
+ const outHandleLength = getCircularArcHandleLength(
+ nextAnchor ? getDistance(point.anchor, nextAnchor) : 0,
+ turningAngle
+ );
+
+ return {
+ ...point,
+ inHandle:
+ !isClosed && pointIndex === 0
+ ? null
+ : normalizeHandle(point.anchor, {
+ x: point.anchor.x - tangentDirection.x * inHandleLength,
+ y: point.anchor.y - tangentDirection.y * inHandleLength,
+ }),
+ outHandle:
+ !isClosed && pointIndex === lastPointIndex
+ ? null
+ : normalizeHandle(point.anchor, {
+ x: point.anchor.x + tangentDirection.x * outHandleLength,
+ y: point.anchor.y + tangentDirection.y * outHandleLength,
+ }),
+ type: 'smooth',
+ };
+ });
+};
+
+export const splitBezierSegmentAt = (
+ from: CanvasBezierPointContract,
+ to: CanvasBezierPointContract,
+ t: number
+): {
+ fromOutHandle: Vec2 | null;
+ insertPoint: CanvasBezierPointContract;
+ toInHandle: Vec2 | null;
+} => {
+ const p0 = from.anchor;
+ const p1 = from.outHandle ?? from.anchor;
+ const p2 = to.inHandle ?? to.anchor;
+ const p3 = to.anchor;
+
+ const q0 = lerpCoordinate(p0, p1, t);
+ const q1 = lerpCoordinate(p1, p2, t);
+ const q2 = lerpCoordinate(p2, p3, t);
+ const r0 = lerpCoordinate(q0, q1, t);
+ const r1 = lerpCoordinate(q1, q2, t);
+ const s = lerpCoordinate(r0, r1, t);
+
+ return {
+ fromOutHandle: normalizeHandle(from.anchor, q0),
+ insertPoint: {
+ anchor: s,
+ inHandle: normalizeHandle(s, r0),
+ outHandle: normalizeHandle(s, r1),
+ type: 'smooth',
+ },
+ toInHandle: normalizeHandle(to.anchor, q2),
+ };
+};
+
+export const findNearestBezierPathSegment = (
+ points: RenderableBezierPoint[],
+ isClosed: boolean,
+ point: Vec2,
+ samplesPerSegment = DEFAULT_BEZIER_PATH_SAMPLES_PER_SEGMENT
+): BezierPathSegmentHit | null => {
+ if (points.length < 2) {
+ return null;
+ }
+
+ let nearestHit: BezierPathSegmentHit | null = null;
+ const segmentCount = isClosed ? points.length : points.length - 1;
+
+ for (let segmentIndex = 0; segmentIndex < segmentCount; segmentIndex += 1) {
+ const from = points[segmentIndex];
+ const to = points[(segmentIndex + 1) % points.length];
+ if (!from || !to) {
+ continue;
+ }
+
+ let previous = from.anchor;
+ for (let sampleIndex = 1; sampleIndex <= samplesPerSegment; sampleIndex += 1) {
+ const t = sampleIndex / samplesPerSegment;
+ const current = evaluateBezierSegment(from, to, t);
+ const segmentVector = {
+ x: current.x - previous.x,
+ y: current.y - previous.y,
+ };
+ const segmentLengthSquared = segmentVector.x ** 2 + segmentVector.y ** 2;
+ const projectedT =
+ segmentLengthSquared === 0
+ ? 0
+ : ((point.x - previous.x) * segmentVector.x + (point.y - previous.y) * segmentVector.y) /
+ segmentLengthSquared;
+ const clampedProjectedT = Math.max(0, Math.min(1, projectedT));
+ const nearestPoint = {
+ x: previous.x + segmentVector.x * clampedProjectedT,
+ y: previous.y + segmentVector.y * clampedProjectedT,
+ };
+ const distance = getDistance(point, nearestPoint);
+
+ if (!nearestHit || distance < nearestHit.distance) {
+ nearestHit = {
+ segmentIndex,
+ t: (sampleIndex - 1 + clampedProjectedT) / samplesPerSegment,
+ point: nearestPoint,
+ distance,
+ };
+ }
+
+ previous = current;
+ }
+ }
+
+ return nearestHit;
+};
+
+export const getBezierPathHitSamplesPerSegment = (stageScale: number): number => {
+ const normalizedScale = Math.max(1, stageScale);
+ return Math.min(128, Math.ceil(DEFAULT_BEZIER_PATH_SAMPLES_PER_SEGMENT * Math.sqrt(normalizedScale)));
+};
+
+export const approximateBezierPath = (
+ points: RenderableBezierPoint[],
+ isClosed: boolean,
+ samplesPerSegment = DEFAULT_BEZIER_PATH_SAMPLES_PER_SEGMENT
+): Vec2[] => {
+ const firstPoint = points[0];
+ if (!firstPoint) {
+ return [];
+ }
+
+ if (points.length === 1) {
+ return [firstPoint.anchor];
+ }
+
+ const approximatedPoints: Vec2[] = [firstPoint.anchor];
+ const segmentCount = isClosed ? points.length : points.length - 1;
+
+ for (let segmentIndex = 0; segmentIndex < segmentCount; segmentIndex += 1) {
+ const from = points[segmentIndex];
+ const to = points[(segmentIndex + 1) % points.length];
+ if (!from || !to) {
+ continue;
+ }
+
+ for (let sampleIndex = 1; sampleIndex <= samplesPerSegment; sampleIndex += 1) {
+ approximatedPoints.push(evaluateBezierSegment(from, to, sampleIndex / samplesPerSegment));
+ }
+ }
+
+ return approximatedPoints;
+};
+
+/** Preserve path identity fields while applying one affine transform to anchors and handles. */
+export const transformBezierPath = (path: CanvasBezierPathContract, matrix: Mat2d): CanvasBezierPathContract => ({
+ ...path,
+ points: path.points.map((point) => ({
+ ...point,
+ anchor: applyToPoint(matrix, point.anchor),
+ inHandle: point.inHandle ? applyToPoint(matrix, point.inHandle) : null,
+ outHandle: point.outHandle ? applyToPoint(matrix, point.outHandle) : null,
+ })),
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/math/rect.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/rect.ts
index 4d1fb13576..39f66a47f8 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/math/rect.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/rect.ts
@@ -1,3 +1,4 @@
+import type { CanvasBezierPointContract } from '@workbench/canvas-engine/contracts';
import type { Mat2d, Rect, Vec2 } from '@workbench/canvas-engine/types';
import { applyToPoint } from './mat2d';
@@ -144,3 +145,93 @@ export const mergeDirtyRects = (rects: Rect[], maxRegions = 4): Rect[] => {
return current;
};
+
+type RenderableBezierPoint = Pick<CanvasBezierPointContract, 'anchor' | 'inHandle' | 'outHandle'>;
+
+export const evaluateBezierSegment = (from: RenderableBezierPoint, to: RenderableBezierPoint, t: number): Vec2 => {
+ const p0 = from.anchor;
+ const p1 = from.outHandle ?? from.anchor;
+ const p2 = to.inHandle ?? to.anchor;
+ const p3 = to.anchor;
+ const mt = 1 - t;
+ const mt2 = mt * mt;
+ const t2 = t * t;
+
+ return {
+ x: mt2 * mt * p0.x + 3 * mt2 * t * p1.x + 3 * mt * t2 * p2.x + t2 * t * p3.x,
+ y: mt2 * mt * p0.y + 3 * mt2 * t * p1.y + 3 * mt * t2 * p2.y + t2 * t * p3.y,
+ };
+};
+
+export const getBezierPathBounds = (points: RenderableBezierPoint[], isClosed: boolean): Rect => {
+ if (points.length === 0) {
+ return { x: 0, y: 0, width: 0, height: 0 };
+ }
+ let minX = Infinity;
+ let minY = Infinity;
+ let maxX = -Infinity;
+ let maxY = -Infinity;
+ const include = (point: Vec2) => {
+ minX = Math.min(minX, point.x);
+ minY = Math.min(minY, point.y);
+ maxX = Math.max(maxX, point.x);
+ maxY = Math.max(maxY, point.y);
+ };
+ points.forEach((point) => include(point.anchor));
+ for (let i = 0; i < (isClosed ? points.length : points.length - 1); i++) {
+ const from = points[i]!;
+ const to = points[(i + 1) % points.length]!;
+ const p1 = from.outHandle ?? from.anchor;
+ const p2 = to.inHandle ?? to.anchor;
+ for (const axis of ['x', 'y'] as const) {
+ // Roots of the cubic's derivative, with the common factor of three removed.
+ const a = -from.anchor[axis] + 3 * p1[axis] - 3 * p2[axis] + to.anchor[axis];
+ const b = 2 * (from.anchor[axis] - 2 * p1[axis] + p2[axis]);
+ const c = p1[axis] - from.anchor[axis];
+ const roots: number[] = [];
+ if (Math.abs(a) < 1e-12) {
+ if (Math.abs(b) >= 1e-12) {
+ roots.push(-c / b);
+ }
+ } else {
+ const discriminant = b * b - 4 * a * c;
+ if (discriminant >= 0) {
+ const sqrt = Math.sqrt(discriminant);
+ roots.push((-b + sqrt) / (2 * a), (-b - sqrt) / (2 * a));
+ }
+ }
+ for (const t of roots) {
+ if (t > 0 && t < 1) {
+ include(evaluateBezierSegment(from, to, t));
+ }
+ }
+ }
+ }
+ return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
+};
+
+/** Axis-aligned bounds of an outline polygon; an empty polygon yields a zero-size rect. */
+export const polygonBounds = (polygon: readonly Vec2[]): Rect => {
+ if (polygon.length === 0) {
+ return { height: 0, width: 0, x: 0, y: 0 };
+ }
+ let minX = Infinity;
+ let minY = Infinity;
+ let maxX = -Infinity;
+ let maxY = -Infinity;
+ for (const p of polygon) {
+ if (p.x < minX) {
+ minX = p.x;
+ }
+ if (p.y < minY) {
+ minY = p.y;
+ }
+ if (p.x > maxX) {
+ maxX = p.x;
+ }
+ if (p.y > maxY) {
+ maxY = p.y;
+ }
+ }
+ return { height: maxY - minY, width: maxX - minX, x: minX, y: minY };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/math/shapeGeometry.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/shapeGeometry.ts
new file mode 100644
index 0000000000..18e6a5ebd2
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/shapeGeometry.ts
@@ -0,0 +1,23 @@
+import type { Rect, Vec2 } from '@workbench/canvas-engine/types';
+
+/** Shared outlines for raster Shapes and editable vector paths, before stroke insetting. */
+export const polygonShapeVertices = (kind: 'triangle' | 'star', rect: Rect): Vec2[] => {
+ const cx = rect.x + rect.width / 2;
+ const cy = rect.y + rect.height / 2;
+ if (kind === 'triangle') {
+ return [
+ { x: cx, y: rect.y },
+ { x: rect.x + rect.width, y: rect.y + rect.height },
+ { x: rect.x, y: rect.y + rect.height },
+ ];
+ }
+ // Match the existing Shapes pentagram: five spikes with sin(18°) / sin(54°) inner radius.
+ return Array.from({ length: 10 }, (_, index) => {
+ const radius = index % 2 === 0 ? 1 : 0.382;
+ const angle = -Math.PI / 2 + (index * Math.PI) / 5;
+ return {
+ x: cx + ((Math.cos(angle) * rect.width) / 2) * radius,
+ y: cy + ((Math.sin(angle) * rect.height) / 2) * radius,
+ };
+ });
+};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/math/vectorFillRegions.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/vectorFillRegions.test.ts
new file mode 100644
index 0000000000..e9e8498ad8
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/vectorFillRegions.test.ts
@@ -0,0 +1,129 @@
+import type { Vec2 } from '@workbench/canvas-engine/types';
+
+import { describe, expect, it } from 'vitest';
+
+import { findVectorFillRegions, findVectorFillRegionsAsync, VectorFillLimitError } from './vectorFillRegions';
+
+const area = (points: Vec2[]) =>
+ points.reduce((sum, point, i) => {
+ const next = points[(i + 1) % points.length]!;
+ return sum + point.x * next.y - next.x * point.y;
+ }, 0) / 2;
+
+describe('vector fill regions', () => {
+ it('finds a loop in an open self-crossing path without filling its tails', () => {
+ const regions = findVectorFillRegions([
+ [
+ { x: -2, y: -2 },
+ { x: 2, y: 2 },
+ { x: -2, y: 2 },
+ { x: 2, y: -2 },
+ ],
+ ]);
+ expect(regions).toHaveLength(1);
+ expect(area(regions[0]!)).toBeCloseTo(4);
+ expect(regions[0]!.every((point) => point.y >= 0)).toBe(true);
+ });
+
+ it('finds a region bounded by separate open paths and preserves the input', () => {
+ const paths = [
+ [
+ { x: -1, y: 0 },
+ { x: 3, y: 0 },
+ ],
+ [
+ { x: 2, y: -1 },
+ { x: 2, y: 3 },
+ ],
+ [
+ { x: 3, y: 2 },
+ { x: -1, y: 2 },
+ ],
+ [
+ { x: 0, y: 3 },
+ { x: 0, y: -1 },
+ ],
+ ];
+ const before = structuredClone(paths);
+ const regions = findVectorFillRegions(paths);
+ expect(regions).toHaveLength(1);
+ expect(area(regions[0]!)).toBeCloseTo(4);
+ expect(paths).toEqual(before);
+ });
+
+ it('does not fill an isolated crossing or bridge a gap', () => {
+ expect(
+ findVectorFillRegions([
+ [
+ { x: -1, y: 0 },
+ { x: 1, y: 0 },
+ ],
+ [
+ { x: 0, y: -1 },
+ { x: 0, y: 1 },
+ ],
+ ])
+ ).toEqual([]);
+ expect(
+ findVectorFillRegions([
+ [
+ { x: 0, y: 0 },
+ { x: 2, y: 0 },
+ { x: 2, y: 2 },
+ { x: 0, y: 2 },
+ { x: 0, y: 0.01 },
+ ],
+ ])
+ ).toEqual([]);
+ });
+
+ it('keeps both bounded faces of a divided closed contour', () => {
+ const regions = findVectorFillRegions([
+ [
+ { x: 0, y: 0 },
+ { x: 2, y: 0 },
+ { x: 2, y: 2 },
+ { x: 0, y: 2 },
+ { x: 0, y: 0 },
+ ],
+ [
+ { x: 1, y: -1 },
+ { x: 1, y: 3 },
+ ],
+ ]);
+ expect(regions).toHaveLength(2);
+ expect(regions.map(area)).toEqual([2, 2]);
+ });
+});
+
+it('yields for cancellation and enforces work budgets', async () => {
+ const paths = [
+ [
+ { x: 0, y: 0 },
+ { x: 10, y: 10 },
+ ],
+ [
+ { x: 0, y: 10 },
+ { x: 10, y: 0 },
+ ],
+ ];
+ const abort = new AbortController();
+ await expect(
+ findVectorFillRegionsAsync(paths, {
+ signal: abort.signal,
+ yieldControl: () => {
+ abort.abort();
+ return Promise.resolve();
+ },
+ })
+ ).rejects.toMatchObject({ name: 'AbortError' });
+ await expect(
+ findVectorFillRegionsAsync(paths, {
+ yieldControl: () => Promise.resolve(),
+ limits: { segments: 100, comparisons: 0, edges: 100 },
+ })
+ ).rejects.toBeInstanceOf(VectorFillLimitError);
+ expect(await findVectorFillRegionsAsync(paths, { yieldControl: () => Promise.resolve() })).toEqual(
+ findVectorFillRegions(paths)
+ );
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/math/vectorFillRegions.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/vectorFillRegions.ts
new file mode 100644
index 0000000000..4b7ae40833
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/vectorFillRegions.ts
@@ -0,0 +1,203 @@
+import type { Vec2 } from '@workbench/canvas-engine/types';
+
+type Segment = { a: Vec2; b: Vec2; cuts: number[]; minX: number; maxX: number; minY: number; maxY: number };
+type Vertex = { point: Vec2; outgoing: number[] };
+type Edge = { from: number; to: number; reverse: number; visited: boolean };
+
+const cross = (a: Vec2, b: Vec2) => a.x * b.y - a.y * b.x;
+const subtract = (a: Vec2, b: Vec2): Vec2 => ({ x: a.x - b.x, y: a.y - b.y });
+const EPSILON = 1e-7;
+
+/** Experimental planar-face extraction. Input is sampled in layer coordinates, independent of zoom.
+ * Only actual crossings connect paths; gaps and collinear overlaps are not repaired.
+ */
+export const VECTOR_FILL_LIMITS = { segments: 24_000, comparisons: 2_000_000, edges: 120_000 } as const;
+export class VectorFillLimitError extends Error {
+ constructor() {
+ super('Vector fill geometry exceeds the supported work budget');
+ this.name = 'VectorFillLimitError';
+ }
+}
+type Limits = { segments: number; comparisons: number; edges: number };
+
+function* regionSteps(paths: readonly (readonly Vec2[])[], limits: Limits): Generator<void, Vec2[][]> {
+ let work = 0;
+ yield;
+ const segments: Segment[] = [];
+ for (const points of paths) {
+ for (let i = 1; i < points.length; i++) {
+ const a = points[i - 1]!,
+ b = points[i]!;
+ if (Math.hypot(b.x - a.x, b.y - a.y) <= EPSILON) {
+ continue;
+ }
+ if (segments.length >= limits.segments) {
+ throw new VectorFillLimitError();
+ }
+ segments.push({
+ a,
+ b,
+ cuts: [0, 1],
+ minX: Math.min(a.x, b.x),
+ maxX: Math.max(a.x, b.x),
+ minY: Math.min(a.y, b.y),
+ maxY: Math.max(a.y, b.y),
+ });
+ }
+ }
+ segments.sort((a, b) => a.minX - b.minX);
+ let comparisons = 0;
+ for (let i = 0; i < segments.length; i++) {
+ const a = segments[i]!,
+ r = subtract(a.b, a.a);
+ for (let j = i + 1; j < segments.length; j++) {
+ if (++comparisons > limits.comparisons) {
+ throw new VectorFillLimitError();
+ }
+ if (++work % 8192 === 0) {
+ yield;
+ }
+ const b = segments[j]!;
+ if (b.minX > a.maxX + EPSILON) {
+ break;
+ }
+ if (b.minY > a.maxY + EPSILON || b.maxY < a.minY - EPSILON) {
+ continue;
+ }
+ const s = subtract(b.b, b.a),
+ denominator = cross(r, s);
+ // Relative parallel test; overlapping edges are deliberately outside this prototype's scope.
+ if (Math.abs(denominator) <= 1e-12 * Math.hypot(r.x, r.y) * Math.hypot(s.x, s.y)) {
+ continue;
+ }
+ const delta = subtract(b.a, a.a);
+ const t = cross(delta, s) / denominator,
+ u = cross(delta, r) / denominator;
+ if (t < -EPSILON || t > 1 + EPSILON || u < -EPSILON || u > 1 + EPSILON) {
+ continue;
+ }
+ a.cuts.push(Math.max(0, Math.min(1, t)));
+ b.cuts.push(Math.max(0, Math.min(1, u)));
+ }
+ }
+
+ const vertices: Vertex[] = [],
+ edges: Edge[] = [];
+ const vertexIds = new Map<string, number>(),
+ connections = new Set<string>();
+ const vertex = (point: Vec2): number => {
+ // Numerical identity only, not a user-visible snapping tolerance.
+ const key = `${Math.round(point.x / EPSILON)},${Math.round(point.y / EPSILON)}`;
+ const existing = vertexIds.get(key);
+ if (existing !== undefined) {
+ return existing;
+ }
+ const id = vertices.length;
+ vertices.push({ point, outgoing: [] });
+ vertexIds.set(key, id);
+ return id;
+ };
+ for (const segment of segments) {
+ const cuts = segment.cuts.sort((a, b) => a - b);
+ const at = (t: number): Vec2 => ({
+ x: segment.a.x + (segment.b.x - segment.a.x) * t,
+ y: segment.a.y + (segment.b.y - segment.a.y) * t,
+ });
+ for (let i = 1; i < cuts.length; i++) {
+ if (cuts[i]! - cuts[i - 1]! <= 1e-12) {
+ continue;
+ }
+ const from = vertex(at(cuts[i - 1]!)),
+ to = vertex(at(cuts[i]!));
+ const key = `${Math.min(from, to)}:${Math.max(from, to)}`;
+ if (from === to || connections.has(key)) {
+ continue;
+ }
+ if (edges.length + 2 > limits.edges) {
+ throw new VectorFillLimitError();
+ }
+ if (++work % 8192 === 0) {
+ yield;
+ }
+ connections.add(key);
+ const id = edges.length;
+ edges.push({ from, to, reverse: id + 1, visited: false }, { from: to, to: from, reverse: id, visited: false });
+ vertices[from]!.outgoing.push(id);
+ vertices[to]!.outgoing.push(id + 1);
+ }
+ }
+ for (const vertex of vertices) {
+ const angle = (id: number) => {
+ const to = vertices[edges[id]!.to]!.point;
+ return Math.atan2(to.y - vertex.point.y, to.x - vertex.point.x);
+ };
+ vertex.outgoing.sort((a, b) => angle(a) - angle(b));
+ }
+ const regions: Vec2[][] = [];
+ for (let start = 0; start < edges.length; start++) {
+ if (edges[start]!.visited) {
+ continue;
+ }
+ const points: Vec2[] = [];
+ let current = start;
+ do {
+ const edge = edges[current]!;
+ if (edge.visited) {
+ break;
+ }
+ if (++work % 8192 === 0) {
+ yield;
+ }
+ edge.visited = true;
+ points.push(vertices[edge.from]!.point);
+ const outgoing = vertices[edge.to]!.outgoing;
+ const reverseIndex = outgoing.indexOf(edge.reverse);
+ current = outgoing[(reverseIndex + outgoing.length - 1) % outgoing.length]!;
+ } while (current !== start);
+ if (current !== start || points.length < 3) {
+ continue;
+ }
+ // Bounded faces have positive signed area; the unbounded exterior has negative area.
+ const area = points.reduce((sum, point, i) => sum + cross(point, points[(i + 1) % points.length]!), 0) / 2;
+ if (area > EPSILON) {
+ regions.push(points);
+ }
+ }
+ return regions;
+}
+
+/** Synchronous pure entry for small geometry and deterministic callers. */
+export const findVectorFillRegions = (paths: readonly (readonly Vec2[])[]): Vec2[][] => {
+ const steps = regionSteps(paths, VECTOR_FILL_LIMITS);
+ let step = steps.next();
+ while (!step.done) {
+ step = steps.next();
+ }
+ return step.value;
+};
+
+/** Yield bounded chunks to the browser so edits and Escape/Cancel can interrupt region discovery. */
+export const findVectorFillRegionsAsync = async (
+ paths: readonly (readonly Vec2[])[],
+ options: { signal?: AbortSignal; yieldControl?: () => Promise<void>; limits?: Limits } = {}
+): Promise<Vec2[][]> => {
+ const steps = regionSteps(paths, options.limits ?? VECTOR_FILL_LIMITS);
+ const yieldControl =
+ options.yieldControl ??
+ (() =>
+ new Promise<void>((resolve) => {
+ setTimeout(resolve, 0);
+ }));
+ try {
+ while (true) {
+ options.signal?.throwIfAborted();
+ const step = steps.next();
+ if (step.done) {
+ return step.value;
+ }
+ await yieldControl();
+ }
+ } finally {
+ steps.return([]);
+ }
+};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/math/vectorHandleLayout.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/vectorHandleLayout.ts
new file mode 100644
index 0000000000..702cafbbe6
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/vectorHandleLayout.ts
@@ -0,0 +1,49 @@
+import type { CanvasBezierPathContract } from '@workbench/canvas-engine/contracts';
+import type { Mat2d, Vec2 } from '@workbench/canvas-engine/types';
+
+import { applyToPoint } from './mat2d';
+
+/** Missing Corner handles get grab markers; existing handles always show their real positions. */
+export const vectorHandleLayout = (
+ path: CanvasBezierPathContract,
+ pointIndex: number,
+ matrix: Mat2d
+): {
+ inHandle: Vec2 | null;
+ outHandle: Vec2 | null;
+} => {
+ const point = path.points[pointIndex]!;
+ if (point.type !== 'corner') {
+ return {
+ inHandle: point.inHandle ? applyToPoint(matrix, point.inHandle) : null,
+ outHandle: point.outHandle ? applyToPoint(matrix, point.outHandle) : null,
+ };
+ }
+ const previous = path.points[pointIndex - 1] ?? (path.isClosed ? path.points.at(-1) : undefined);
+ const next = path.points[pointIndex + 1] ?? (path.isClosed ? path.points[0] : undefined);
+ const anchor = applyToPoint(matrix, point.anchor);
+ const extend = (handle: Vec2 | null, fallback: Vec2 | undefined, minimum: number): Vec2 | null => {
+ if (handle) {
+ return applyToPoint(matrix, handle);
+ }
+ const direction = handle ?? fallback;
+ if (!direction) {
+ return null;
+ }
+ const projected = applyToPoint(matrix, direction);
+ const dx = projected.x - anchor.x,
+ dy = projected.y - anchor.y;
+ const length = Math.hypot(dx, dy);
+ if (length < 1e-6) {
+ return null;
+ }
+ return { x: anchor.x + (dx * minimum) / length, y: anchor.y + (dy * minimum) / length };
+ };
+ const inHandle = extend(point.inHandle, previous?.anchor, 28);
+ let outHandle = extend(point.outHandle, next?.anchor, 28);
+ if (inHandle && outHandle && Math.hypot(inHandle.x - outHandle.x, inHandle.y - outHandle.y) < 24) {
+ // At acute corners, stagger tips along their own tangent rays.
+ outHandle = extend(point.outHandle, next?.anchor, Math.hypot(inHandle.x - anchor.x, inHandle.y - anchor.y) + 24);
+ }
+ return { inHandle, outHandle };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/math/vectorHitTest.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/vectorHitTest.test.ts
new file mode 100644
index 0000000000..788bf9bc81
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/vectorHitTest.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from 'vitest';
+
+import { anchorsToBezierPoints, getBezierPathHitSamplesPerSegment } from './bezierPath';
+import { identity } from './mat2d';
+import { VectorHitTestCache } from './vectorHitTest';
+
+describe('cached vector hit testing', () => {
+ it('preserves segment indices and parameters, rejects distant curves and refreshes projection/geometry', () => {
+ const cache = new VectorHitTestCache();
+ const path = {
+ id: 'p',
+ name: null,
+ isClosed: false,
+ points: anchorsToBezierPoints([
+ { x: 0, y: 0 },
+ { x: 100, y: 0 },
+ { x: 100, y: 100 },
+ ]),
+ };
+ expect(cache.hitAnchor(path, identity(), { x: 100, y: 0 }, 1)).toBe(true);
+ expect(cache.hitAnchor(path, identity(), { x: 1000, y: 0 }, 1)).toBe(false);
+ const hit = cache.find(path, identity(), { x: 100, y: 50 }, 1)!;
+ expect(hit.segmentIndex).toBe(1);
+ expect(hit.t).toBeCloseTo(0.5);
+ expect(hit.distance).toBe(0);
+ expect(cache.find(path, identity(), { x: 100, y: 50 }, 1)).toEqual(hit);
+ expect(cache.find(path, identity(), { x: 1000, y: 1000 }, 1)).toBeNull();
+ const moved = { ...identity(), e: 200 };
+ expect(cache.find(path, moved, { x: 100, y: 50 }, 1)).toBeNull();
+ expect(cache.find(path, moved, { x: 300, y: 50 }, 1)?.segmentIndex).toBe(1);
+ const changed = {
+ ...path,
+ points: anchorsToBezierPoints([
+ { x: 0, y: 0 },
+ { x: 20, y: 0 },
+ ]),
+ };
+ expect(cache.find(changed, identity(), { x: 100, y: 50 }, 1)).toBeNull();
+ cache.clear();
+ expect(cache.find(path, identity(), { x: 100, y: 50 }, 1)).toEqual(hit);
+ });
+ it('caps sampling at extreme zoom/scale', () => {
+ expect(getBezierPathHitSamplesPerSegment(1e20)).toBe(128);
+ expect(getBezierPathHitSamplesPerSegment(1)).toBe(24);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/math/vectorHitTest.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/vectorHitTest.ts
new file mode 100644
index 0000000000..f89b4f921c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/vectorHitTest.ts
@@ -0,0 +1,112 @@
+import type { CanvasBezierPathContract } from '@workbench/canvas-engine/contracts';
+import type { Mat2d, Rect, Vec2 } from '@workbench/canvas-engine/types';
+
+import { approximateBezierPath, getBezierPathBounds, getBezierPathHitSamplesPerSegment } from './bezierPath';
+import { applyToPoint } from './mat2d';
+
+type Entry = { key: string; bounds: Rect; anchors: Vec2[]; samples: Vec2[]; steps: number };
+const MAX_CACHED_SAMPLES = 50_000;
+
+/** Controller-owned cache: only immutable geometry + the current projection, with bounded retained samples. */
+export class VectorHitTestCache {
+ private entries = new Map<CanvasBezierPathContract, Entry>();
+ private retained = 0;
+
+ clear(): void {
+ this.entries.clear();
+ this.retained = 0;
+ }
+
+ private entry(path: CanvasBezierPathContract, matrix: Mat2d, scale: number): Entry {
+ const steps = getBezierPathHitSamplesPerSegment(scale);
+ const key = `${matrix.a},${matrix.b},${matrix.c},${matrix.d},${matrix.e},${matrix.f},${steps}`;
+ let entry = this.entries.get(path);
+ if (entry?.key !== key) {
+ if (entry) {
+ this.retained -= entry.samples.length + entry.anchors.length;
+ this.entries.delete(path);
+ }
+ const projected = path.points.map((p) => ({
+ anchor: applyToPoint(matrix, p.anchor),
+ inHandle: p.inHandle ? applyToPoint(matrix, p.inHandle) : null,
+ outHandle: p.outHandle ? applyToPoint(matrix, p.outHandle) : null,
+ }));
+ entry = {
+ key,
+ steps,
+ bounds: getBezierPathBounds(projected, path.isClosed),
+ anchors: projected.map((p) => p.anchor),
+ samples: [],
+ };
+ this.retained += entry.anchors.length;
+ // Keep even offscreen bounds, but do not sample a distant curve just to reject it.
+ this.entries.set(path, entry);
+ }
+ this.entries.delete(path);
+ this.entries.set(path, entry);
+ return entry;
+ }
+
+ hitAnchor(path: CanvasBezierPathContract, matrix: Mat2d, point: Vec2, scale: number, radius = 12): boolean {
+ const entry = this.entry(path, matrix, scale),
+ b = entry.bounds;
+ const inside =
+ point.x >= b.x - radius &&
+ point.y >= b.y - radius &&
+ point.x <= b.x + b.width + radius &&
+ point.y <= b.y + b.height + radius;
+ const hit = inside && entry.anchors.some((anchor) => Math.hypot(anchor.x - point.x, anchor.y - point.y) <= radius);
+ this.trim();
+ return hit;
+ }
+
+ find(path: CanvasBezierPathContract, matrix: Mat2d, point: Vec2, scale: number, radius = 10) {
+ const entry = this.entry(path, matrix, scale),
+ steps = entry.steps;
+ const b = entry.bounds;
+ if (
+ point.x < b.x - radius ||
+ point.y < b.y - radius ||
+ point.x > b.x + b.width + radius ||
+ point.y > b.y + b.height + radius
+ ) {
+ this.trim();
+ return null;
+ }
+ if (entry.samples.length === 0) {
+ // Affine projection commutes with Bezier evaluation; sample once, reuse on every hover.
+ entry.samples = approximateBezierPath(path.points, path.isClosed, steps).map((p) => applyToPoint(matrix, p));
+ this.retained += entry.samples.length;
+ }
+ let best: { segmentIndex: number; t: number; point: Vec2; distance: number } | null = null;
+ for (let i = 1; i < entry.samples.length; i++) {
+ const a = entry.samples[i - 1]!,
+ b = entry.samples[i]!;
+ const dx = b.x - a.x,
+ dy = b.y - a.y,
+ length2 = dx * dx + dy * dy;
+ const t = length2 === 0 ? 0 : Math.max(0, Math.min(1, ((point.x - a.x) * dx + (point.y - a.y) * dy) / length2));
+ const nearest = { x: a.x + dx * t, y: a.y + dy * t };
+ const distance = Math.hypot(point.x - nearest.x, point.y - nearest.y);
+ if (distance <= radius && (!best || distance < best.distance)) {
+ best = {
+ segmentIndex: Math.floor((i - 1) / steps),
+ t: (((i - 1) % steps) + t) / steps,
+ point: nearest,
+ distance,
+ };
+ }
+ }
+ this.trim();
+ return best;
+ }
+
+ private trim(): void {
+ while (this.entries.size > 64 || this.retained > MAX_CACHED_SAMPLES) {
+ const oldest = this.entries.keys().next().value!;
+ const entry = this.entries.get(oldest)!;
+ this.retained -= entry.samples.length + entry.anchors.length;
+ this.entries.delete(oldest);
+ }
+ }
+}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/math/vectorPathTopology.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/vectorPathTopology.ts
new file mode 100644
index 0000000000..005b8305f6
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/vectorPathTopology.ts
@@ -0,0 +1,326 @@
+/** Path topology adapted from the v6 spline implementation (c4c0594261). */
+import type { CanvasBezierPathContract, CanvasBezierPointContract } from '@workbench/canvas-engine/contracts';
+import type { Vec2 } from '@workbench/canvas-engine/types';
+
+import { setBezierPointType } from './bezierPath';
+
+type TopologyResult = {
+ path: CanvasBezierPathContract;
+ activePointIndex: number;
+};
+
+type VectorPathPointRef = { pathId: string; pointIndex: number };
+
+type SplitVectorPathResult = {
+ paths: CanvasBezierPathContract[];
+ activePathId: string;
+ activePointIndex: number;
+};
+
+type DeleteVectorPathPointsResult = {
+ paths: CanvasBezierPathContract[];
+ didDelete: boolean;
+};
+
+const translateHandle = (handle: Vec2 | null, from: Vec2, to: Vec2): Vec2 | null =>
+ handle ? { x: handle.x + to.x - from.x, y: handle.y + to.y - from.y } : null;
+
+const reversePoints = (path: CanvasBezierPathContract): CanvasBezierPathContract['points'] =>
+ [...path.points].reverse().map((point) => ({
+ ...point,
+ inHandle: point.outHandle,
+ outHandle: point.inHandle,
+ }));
+
+const prepareJoinedEndpoint = (point: CanvasBezierPointContract, connectingHandle: 'inHandle' | 'outHandle') => {
+ if (point.type === 'corner') {
+ point[connectingHandle] = null;
+ return;
+ }
+ // Keep the existing segment's tangent and restore the handle used by the new segment.
+ setBezierPointType(point, point.type, connectingHandle === 'inHandle' ? 'outHandle' : 'inHandle');
+};
+
+export const deleteVectorPathPoints = (
+ sourcePaths: CanvasBezierPathContract[],
+ pointRefs: VectorPathPointRef[]
+): DeleteVectorPathPointsResult => {
+ const selectedPointIndices = new Map<string, Set<number>>();
+ for (const pointRef of pointRefs) {
+ const indices = selectedPointIndices.get(pointRef.pathId) ?? new Set<number>();
+ indices.add(pointRef.pointIndex);
+ selectedPointIndices.set(pointRef.pathId, indices);
+ }
+
+ let didDelete = false;
+ const paths = structuredClone(sourcePaths).filter((path) => {
+ const pointIndices = [...(selectedPointIndices.get(path.id) ?? [])]
+ .filter((pointIndex) => path.points[pointIndex] !== undefined)
+ .sort((a, b) => b - a);
+ if (pointIndices.length === 0) {
+ return true;
+ }
+
+ didDelete = true;
+ const minPointCount = path.isClosed ? 3 : 2;
+ if (path.points.length - pointIndices.length < minPointCount) {
+ return false;
+ }
+
+ const deletedIndices = new Set(pointIndices);
+ path.points = path.points.filter((point, pointIndex, points) => {
+ if (deletedIndices.has(pointIndex)) {
+ return false;
+ }
+ const previousIndex = path.isClosed ? (pointIndex - 1 + points.length) % points.length : pointIndex - 1;
+ const nextIndex = path.isClosed ? (pointIndex + 1) % points.length : pointIndex + 1;
+ const previousDeleted = deletedIndices.has(previousIndex);
+ const nextDeleted = deletedIndices.has(nextIndex);
+ if (previousDeleted || nextDeleted) {
+ // Preserve the tangent on the unchanged side of the surviving point.
+ setBezierPointType(point, point.type, nextDeleted && !previousDeleted ? 'inHandle' : 'outHandle');
+ }
+ return true;
+ });
+ return true;
+ });
+
+ return { paths, didDelete };
+};
+
+export const canSplitVectorPathAtPoints = (
+ paths: CanvasBezierPathContract[],
+ pointRefs: VectorPathPointRef[]
+): boolean => {
+ return pointRefs.some((pointRef) => {
+ const path = paths.find((candidate) => candidate.id === pointRef.pathId);
+ return Boolean(
+ path?.points[pointRef.pointIndex] &&
+ (path.isClosed || (pointRef.pointIndex > 0 && pointRef.pointIndex < path.points.length - 1))
+ );
+ });
+};
+
+export const canJoinVectorPathEndpoints = (
+ paths: CanvasBezierPathContract[],
+ pointRefs: VectorPathPointRef[],
+ weldRadius: number,
+ project: (point: Vec2) => Vec2 = (point) => point
+): boolean => {
+ if (pointRefs.length !== 2) {
+ return false;
+ }
+ const [firstRef, secondRef] = pointRefs;
+ if (
+ !firstRef ||
+ !secondRef ||
+ (firstRef.pathId === secondRef.pathId && firstRef.pointIndex === secondRef.pointIndex)
+ ) {
+ return false;
+ }
+ const firstPath = paths.find((path) => path.id === firstRef.pathId);
+ const secondPath = paths.find((path) => path.id === secondRef.pathId);
+ if (!firstPath || !secondPath || firstPath.isClosed || secondPath.isClosed) {
+ return false;
+ }
+ const isEndpoint = (path: CanvasBezierPathContract, pointIndex: number) =>
+ pointIndex === 0 || pointIndex === path.points.length - 1;
+ if (!isEndpoint(firstPath, firstRef.pointIndex) || !isEndpoint(secondPath, secondRef.pointIndex)) {
+ return false;
+ }
+ if (firstPath.id !== secondPath.id) {
+ return true;
+ }
+ const firstPoint = firstPath.points[firstRef.pointIndex];
+ const secondPoint = secondPath.points[secondRef.pointIndex];
+ if (!firstPoint || !secondPoint) {
+ return false;
+ }
+ const first = project(firstPoint.anchor),
+ second = project(secondPoint.anchor);
+ const shouldWeld = Math.hypot(first.x - second.x, first.y - second.y) <= weldRadius;
+ return !shouldWeld || firstPath.points.length >= 4;
+};
+
+export const splitVectorPathAtPoint = (
+ sourcePath: CanvasBezierPathContract,
+ pointIndex: number,
+ newPathId: string
+): SplitVectorPathResult | null => splitVectorPathAtPoints(sourcePath, [pointIndex], () => newPathId);
+
+export const splitVectorPathAtPoints = (
+ sourcePath: CanvasBezierPathContract,
+ pointIndices: number[],
+ getNewPathId: () => string
+): SplitVectorPathResult | null => {
+ const path = structuredClone(sourcePath);
+ const validPointIndices = pointIndices.filter((pointIndex) => path.points[pointIndex] !== undefined);
+ const uniquePointIndices = [...new Set(validPointIndices)].sort((a, b) => a - b);
+ if (uniquePointIndices.length === 0) {
+ return null;
+ }
+
+ if (path.isClosed) {
+ const splitPaths = uniquePointIndices.map((startIndex, splitIndex) => {
+ const endIndex = uniquePointIndices[(splitIndex + 1) % uniquePointIndices.length] ?? startIndex;
+ const points: CanvasBezierPathContract['points'] = [];
+ let pointIndex = startIndex;
+ do {
+ const point = path.points[pointIndex];
+ if (point) {
+ points.push(structuredClone(point));
+ }
+ pointIndex = (pointIndex + 1) % path.points.length;
+ } while (pointIndex !== endIndex);
+ const endPoint = path.points[endIndex];
+ if (endPoint) {
+ points.push(structuredClone(endPoint));
+ }
+ const firstPoint = points[0];
+ const lastPoint = points.at(-1);
+ if (firstPoint) {
+ firstPoint.inHandle = null;
+ }
+ if (lastPoint) {
+ lastPoint.outHandle = null;
+ }
+ return {
+ ...path,
+ id: splitIndex === 0 ? path.id : getNewPathId(),
+ isClosed: false,
+ points,
+ };
+ });
+ const activeSplitPointIndex = validPointIndices.at(-1);
+ const activePath = splitPaths[uniquePointIndices.indexOf(activeSplitPointIndex ?? -1)];
+ if (!activePath) {
+ return null;
+ }
+ return { paths: splitPaths, activePathId: activePath.id, activePointIndex: 0 };
+ }
+
+ const internalPointIndices = uniquePointIndices.filter(
+ (pointIndex) => pointIndex > 0 && pointIndex < path.points.length - 1
+ );
+ if (internalPointIndices.length === 0) {
+ return null;
+ }
+
+ const boundaries = [0, ...internalPointIndices, path.points.length - 1];
+ const splitPaths = boundaries.slice(0, -1).map((startIndex, splitIndex) => {
+ const endIndex = boundaries[splitIndex + 1] ?? startIndex;
+ const points = structuredClone(path.points.slice(startIndex, endIndex + 1));
+ const firstPoint = points[0];
+ const lastPoint = points.at(-1);
+ if (splitIndex > 0 && firstPoint) {
+ firstPoint.inHandle = null;
+ }
+ if (splitIndex < boundaries.length - 2 && lastPoint) {
+ lastPoint.outHandle = null;
+ }
+ return {
+ ...path,
+ id: splitIndex === 0 ? path.id : getNewPathId(),
+ points,
+ };
+ });
+ const activeInternalPointIndex = [...validPointIndices]
+ .reverse()
+ .find((pointIndex) => internalPointIndices.includes(pointIndex));
+ if (activeInternalPointIndex === undefined) {
+ return null;
+ }
+ const activePath = splitPaths[internalPointIndices.indexOf(activeInternalPointIndex) + 1];
+ if (!activePath) {
+ return null;
+ }
+ return { paths: splitPaths, activePathId: activePath.id, activePointIndex: 0 };
+};
+
+export const joinVectorPathEndpoints = (
+ sourcePathState: CanvasBezierPathContract,
+ sourcePointIndex: number,
+ targetPathState: CanvasBezierPathContract,
+ targetPointIndex: number,
+ shouldWeld: boolean
+): TopologyResult | null => {
+ if (sourcePathState.isClosed || targetPathState.isClosed) {
+ return null;
+ }
+ const sourcePath = structuredClone(sourcePathState);
+ const targetPath = sourcePath.id === targetPathState.id ? sourcePath : structuredClone(targetPathState);
+ const isEndpoint = (path: CanvasBezierPathContract, pointIndex: number) =>
+ pointIndex === 0 || pointIndex === path.points.length - 1;
+ if (!isEndpoint(sourcePath, sourcePointIndex) || !isEndpoint(targetPath, targetPointIndex)) {
+ return null;
+ }
+
+ const sourcePoint = sourcePath.points[sourcePointIndex];
+ const targetPoint = targetPath.points[targetPointIndex];
+ if (!sourcePoint || !targetPoint) {
+ return null;
+ }
+
+ if (sourcePath.id === targetPath.id) {
+ const firstPoint = sourcePath.points[0];
+ const lastPoint = sourcePath.points.at(-1);
+ if (!firstPoint || !lastPoint || (shouldWeld && sourcePath.points.length < 4)) {
+ return null;
+ }
+ if (shouldWeld) {
+ const joinedPoint: CanvasBezierPointContract = {
+ anchor: { ...targetPoint.anchor },
+ inHandle: translateHandle(lastPoint.inHandle, lastPoint.anchor, targetPoint.anchor),
+ outHandle: translateHandle(firstPoint.outHandle, firstPoint.anchor, targetPoint.anchor),
+ type: targetPoint.type,
+ };
+ setBezierPointType(joinedPoint, joinedPoint.type, targetPointIndex === 0 ? 'outHandle' : 'inHandle');
+ sourcePath.points = [joinedPoint, ...sourcePath.points.slice(1, -1)];
+ sourcePath.isClosed = true;
+ return { path: sourcePath, activePointIndex: 0 };
+ }
+
+ prepareJoinedEndpoint(firstPoint, 'inHandle');
+ prepareJoinedEndpoint(lastPoint, 'outHandle');
+ sourcePath.isClosed = true;
+ return { path: sourcePath, activePointIndex: targetPointIndex };
+ }
+
+ const sourcePoints = sourcePointIndex === 0 ? reversePoints(sourcePath) : sourcePath.points;
+ const targetPoints =
+ targetPointIndex === targetPath.points.length - 1 ? reversePoints(targetPath) : targetPath.points;
+ const sourceEndPoint = sourcePoints.at(-1);
+ const targetStartPoint = targetPoints[0];
+ if (!sourceEndPoint || !targetStartPoint) {
+ return null;
+ }
+
+ if (shouldWeld) {
+ const joinedPoint: CanvasBezierPointContract = {
+ anchor: { ...targetStartPoint.anchor },
+ inHandle: translateHandle(sourceEndPoint.inHandle, sourceEndPoint.anchor, targetStartPoint.anchor),
+ outHandle: targetStartPoint.outHandle,
+ type: targetStartPoint.type,
+ };
+ setBezierPointType(joinedPoint, joinedPoint.type, 'outHandle');
+ return {
+ path: {
+ ...sourcePath,
+ points: [...sourcePoints.slice(0, -1), joinedPoint, ...targetPoints.slice(1)],
+ isClosed: false,
+ },
+ activePointIndex: sourcePoints.length - 1,
+ };
+ }
+
+ prepareJoinedEndpoint(sourceEndPoint, 'outHandle');
+ prepareJoinedEndpoint(targetStartPoint, 'inHandle');
+ return {
+ path: {
+ ...sourcePath,
+ points: [...sourcePoints, ...targetPoints],
+ isClosed: false,
+ },
+ activePointIndex: sourcePoints.length,
+ };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/math/vectorTrace.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/vectorTrace.ts
new file mode 100644
index 0000000000..f3a4a7f119
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/vectorTrace.ts
@@ -0,0 +1,107 @@
+import type { Vec2 } from '@workbench/canvas-engine/types';
+
+import { polygonBounds } from '@workbench/canvas-engine/math/rect';
+
+/** v6 taper profile: smoothstep pressure over up to half the path at either end. */
+export const buildTaperedTracePoints = (
+ coordinates: Vec2[],
+ strokeWidth: number,
+ taper = 100
+): [number, number, number][] => {
+ const distances = coordinates.map(() => 0);
+ for (let i = 1; i < coordinates.length; i++) {
+ distances[i] =
+ distances[i - 1]! +
+ Math.hypot(coordinates[i]!.x - coordinates[i - 1]!.x, coordinates[i]!.y - coordinates[i - 1]!.y);
+ }
+ const total = distances.at(-1) ?? 0;
+ const length = Math.min(total / 2, Math.max(0, (strokeWidth * 6 * taper) / 100));
+ return coordinates.map((point, i) => {
+ const t = length === 0 ? 1 : Math.min(1, Math.min(distances[i]!, total - distances[i]!) / length);
+ return [point.x, point.y, t * t * (3 - 2 * t)];
+ });
+};
+
+/** Shared tension geometry for drawing and conservative convex-hull raster bounds. */
+const traceLineControls = (points: Vec2[]) => {
+ const controls: { before: Vec2; point: Vec2; after: Vec2 }[] = [];
+ for (let i = 1; i < points.length - 1; i++) {
+ const a = points[i - 1]!,
+ b = points[i]!,
+ c = points[i + 1]!;
+ const d0 = Math.hypot(b.x - a.x, b.y - a.y),
+ d1 = Math.hypot(c.x - b.x, c.y - b.y);
+ if (d0 + d1 === 0) {
+ continue;
+ }
+ const fa = (0.3 * d0) / (d0 + d1),
+ fb = (0.3 * d1) / (d0 + d1);
+ controls.push({
+ before: { x: b.x - fa * (c.x - a.x), y: b.y - fa * (c.y - a.y) },
+ point: b,
+ after: { x: b.x + fb * (c.x - a.x), y: b.y + fb * (c.y - a.y) },
+ });
+ }
+ return controls;
+};
+
+export const getTraceLineBounds = (points: Vec2[]) =>
+ polygonBounds([...points, ...traceLineControls(points).flatMap((control) => [control.before, control.after])]);
+
+/** Konva.Line's open tension-0.3 geometry, used by the v6 brush-line renderer. */
+export const buildTraceLinePath = (
+ points: Vec2[],
+ createPath: (data?: string) => Path2D = () => new Path2D()
+): Path2D => {
+ const path = createPath();
+ const first = points[0];
+ if (!first) {
+ return path;
+ }
+ path.moveTo(first.x, first.y);
+ const controls = traceLineControls(points);
+ const head = controls[0];
+ if (!head) {
+ for (const point of points.slice(1)) {
+ path.lineTo(point.x, point.y);
+ }
+ return path;
+ }
+ path.quadraticCurveTo(head.before.x, head.before.y, head.point.x, head.point.y);
+ for (let i = 1; i < controls.length; i++) {
+ const previous = controls[i - 1]!,
+ current = controls[i]!;
+ path.bezierCurveTo(
+ previous.after.x,
+ previous.after.y,
+ current.before.x,
+ current.before.y,
+ current.point.x,
+ current.point.y
+ );
+ }
+ const tail = controls.at(-1)!,
+ last = points.at(-1)!;
+ path.quadraticCurveTo(tail.after.x, tail.after.y, last.x, last.y);
+ return path;
+};
+
+/** Same Q/T outline as v6 getSvgPathFromStroke (including its two-decimal coordinates). */
+export const buildTraceOutlinePath = (
+ points: number[][],
+ createPath: (data?: string) => Path2D = (data) => (data ? new Path2D(data) : new Path2D())
+): Path2D => {
+ if (points.length < 4) {
+ return createPath();
+ }
+ const value = (n: number) => n.toFixed(2);
+ const midpoint = (a: number[], b: number[]) => `${value((a[0]! + b[0]!) / 2)},${value((a[1]! + b[1]!) / 2)}`;
+ const a = points[0]!,
+ b = points[1]!,
+ c = points[2]!;
+ let data = `M${value(a[0]!)},${value(a[1]!)} Q${value(b[0]!)},${value(b[1]!)} ${midpoint(b, c)} T`;
+ for (let i = 2; i < points.length - 1; i++) {
+ data += `${midpoint(points[i]!, points[i + 1]!)} `;
+ }
+ return createPath(`${data}Z`);
+};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.ts
index f08fa88b6a..96b018859b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.ts
@@ -3,6 +3,7 @@ import type { ProjectEvent } from '@workbench/projectEventContracts';
import type {
CanvasLayerRegionContract,
CanvasAdjustmentsContract,
+ CanvasBezierPathContract,
CanvasControlAdapterContract,
CanvasControlLayerContract,
CanvasDocumentContractV3,
@@ -46,6 +47,18 @@ export const LOCK_EXEMPT_PATCH_KEYS: readonly (keyof CanvasLayerBasePatch)[] = [
];
export type CanvasLayerConfigPatch =
+ | {
+ layerType: 'vector';
+ paths?: CanvasBezierPathContract[];
+ guideColor?: string;
+ fillColor?: string;
+ strokeColor?: string;
+ strokeWidth?: number;
+ fillEnabled?: boolean;
+ strokeEnabled?: boolean;
+ traceTaperEnds?: boolean;
+ traceTaper?: number;
+ }
| {
layerType: 'raster';
adjustments?: CanvasAdjustmentsContract;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts
index d6e9ebee87..92eeb5becf 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts
@@ -67,6 +67,7 @@ export interface CreateCompositeFrameDeps {
*/
const STAGING_OVERLAY_STACKS: Readonly<Record<OverlayStackKind, boolean>> = {
control: false,
+ vector: true,
inpaint_mask: false,
regional_guidance: false,
};
@@ -77,7 +78,7 @@ const STAGING_OVERLAY_STACKS: Readonly<Record<OverlayStackKind, boolean>> = {
*/
export const isInStagingHiddenStack = (doc: CanvasDocumentContractV3, nodeId: string | null): boolean => {
const stack = nodeId ? getDocumentIndex(doc).byId.get(nodeId)?.stack : undefined;
- return stack !== undefined && isOverlayStack(stack);
+ return stack !== undefined && isOverlayStack(stack) && !STAGING_OVERLAY_STACKS[stack];
};
/**
@@ -88,7 +89,12 @@ export const isInStagingHiddenStack = (doc: CanvasDocumentContractV3, nodeId: st
*/
const stagingHiddenSelectedLeaf = (doc: CanvasDocumentContractV3): SemanticLeaf | null => {
const leaf = doc.selectedLayerId ? lookupDocumentLeaf(doc, doc.selectedLayerId) : null;
- return leaf && isOverlayStack(leaf.stack) && isLeafDrawableForScreen(leaf, false) ? leaf : null;
+ return leaf &&
+ isOverlayStack(leaf.stack) &&
+ !STAGING_OVERLAY_STACKS[leaf.stack] &&
+ isLeafDrawableForScreen(leaf, false)
+ ? leaf
+ : null;
};
export interface CompositeFrame {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts
index 12f09da33e..b8f91c0fd0 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts
@@ -111,7 +111,7 @@ export interface CompositeOptions {
/** Isolate one leaf and suppress staged/filter previews; disabled or hidden leaves remain undrawn. */
isolationLayerId?: string | null;
/** Overlay stacks the screen draws; absence draws all. An isolated target draws whatever its stack. */
- showOverlayStacks?: Readonly<Record<OverlayStackKind, boolean>>;
+ showOverlayStacks?: Readonly<Record<Exclude<OverlayStackKind, 'vector'>, boolean> & { vector?: boolean }>;
/**
* Memoized adjusted raster surface, or null for raw pixels. Optional provider; without it adjustments are
* ignored. Cache versions prevent per-frame recomputation.
@@ -182,7 +182,7 @@ export const transformOverridesKey = (overrides: TransformOverrides | null | und
/** A stable key for the overlay stack switches; absence shows every stack. */
const overlayStacksKey = (shown: CompositeOptions['showOverlayStacks']): string => {
const stacks = shown ?? ALL_OVERLAY_STACKS_SHOWN;
- return `${+stacks.control}${+stacks.inpaint_mask}${+stacks.regional_guidance}`;
+ return `${+stacks.control}${+stacks.inpaint_mask}${+stacks.regional_guidance}${+(stacks.vector !== false)}`;
};
/**
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.ts
index 3819951ec8..63a3973e2c 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.ts
@@ -11,14 +11,20 @@ import type { FloatingSelection } from '@workbench/canvas-engine/selection/float
import type { SelectionState } from '@workbench/canvas-engine/selection/selectionState';
import type { ToolId, Vec2 } from '@workbench/canvas-engine/types';
-import { lookupDocumentLayer, lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';
+import {
+ compileDocumentLeaves,
+ lookupDocumentLayer,
+ lookupDocumentLeaf,
+} from '@workbench/canvas-engine/document-model/documentModel';
import { getDocumentIndex, type CanvasNodeEntry } from '@workbench/canvas-engine/document/documentIndex';
import { isGroupNode } from '@workbench/canvas-engine/document/documentTree';
-import { applyToPoint } from '@workbench/canvas-engine/math/mat2d';
+import { applyToPoint, fromTRS } from '@workbench/canvas-engine/math/mat2d';
import { hittableLayerRect, layerOutlineCorners } from '@workbench/canvas-engine/tools/moveHitTest';
import { transformOverlayGeometry } from '@workbench/canvas-engine/transform/transformMath';
import type { FloatingSelectionFrame } from './floatingSelectionFrame';
+import type { VectorEditOverlay } from './vectorEditOverlay';
+import type { VectorGuideLayer } from './vectorGuides';
/** The SAM preview's resting overlay opacity — it sits over the layer it describes. */
const SAM_PREVIEW_OPACITY = 0.45;
@@ -91,7 +97,7 @@ export const createOverlayFrame = (deps: CreateOverlayFrameDeps): OverlayFrame =
* tracks the preview rather than lagging a frame behind it.
*/
const moveOutlineCorners = (doc: CanvasDocumentContractV3): readonly Vec2[] | null => {
- if (getActiveToolId() !== 'move') {
+ if (getActiveToolId() !== 'move' || stores.vectorEditSession.get()) {
return null;
}
const target =
@@ -104,6 +110,22 @@ export const createOverlayFrame = (deps: CreateOverlayFrameDeps): OverlayFrame =
/** The transform-tool frame (rotated bounds + handles + rotation nub), or `null`. */
const transformFrame = (doc: CanvasDocumentContractV3): TransformFrameOverlay | null => {
+ if (getActiveToolId() === 'spline') {
+ const edit = stores.vectorEditSession.get();
+ const frame = edit?.pathTransform;
+ const leaf = edit ? lookupDocumentLeaf(doc, edit.layerId) : null;
+ if (!frame || !leaf) {
+ return null;
+ }
+ const geometry = transformOverlayGeometry(frame.transform, frame.rect);
+ const toDocument = leaf.worldTransform;
+ return {
+ center: applyToPoint(toDocument, geometry.center),
+ corners: geometry.corners.map((point) => applyToPoint(toDocument, point)),
+ handles: geometry.handles.map((point) => applyToPoint(toDocument, point)),
+ rotationAnchor: applyToPoint(toDocument, geometry.rotationAnchor),
+ };
+ }
if (getActiveToolId() !== 'transform') {
return null;
}
@@ -143,7 +165,32 @@ export const createOverlayFrame = (deps: CreateOverlayFrameDeps): OverlayFrame =
const activeTool = getActiveToolId();
const bboxPreview = stores.bboxPreview.get();
const samSession = stores.samInteraction.get();
+ const edit = stores.vectorEditSession.get();
+ let vectorEdit: VectorEditOverlay | null = null;
+ const vectorGuides: VectorGuideLayer[] = [];
+ for (const leaf of compileDocumentLeaves(doc)) {
+ if (leaf.layer.type !== 'vector' || !leaf.contributionEnabled || leaf.documentHidden) {
+ continue;
+ }
+ const transform = { ...leaf.layer.transform, ...transformOverrides.get(leaf.id) };
+ const matrix = transformOverrides.has(leaf.id)
+ ? fromTRS({ x: transform.x, y: transform.y }, transform.rotation, transform.scaleX, transform.scaleY)
+ : leaf.worldTransform;
+ if (edit?.layerId === leaf.id) {
+ vectorEdit = { session: edit, matrix };
+ }
+ vectorGuides.push({
+ paths: edit?.layerId === leaf.id ? edit.paths : leaf.layer.paths,
+ matrix,
+ opacity: leaf.layer.opacity,
+ guideColor: leaf.layer.guideColor,
+ ...(edit?.layerId === leaf.id ? { editActivePathId: edit.activePathId } : {}),
+ });
+ }
return {
+ vectorEdit,
+ vectorGuides,
+ vectorShapePreview: stores.vectorShapePreview.get(),
bbox: bboxPreview ?? doc.bbox,
bboxHandles: activeTool === 'bbox',
bboxOverlay: stores.bboxOverlay.get(),
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts
index fed90d2e51..ef062354a3 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts
@@ -16,6 +16,10 @@ import { TRANSFORM_ROTATE_NUB_PX } from '@workbench/canvas-engine/transform/tran
import type { RgbaSample } from './colorSample';
import type { RasterSurface } from './raster';
+import type { VectorEditOverlay } from './vectorEditOverlay';
+import type { VectorGuideLayer, VectorShapePreview } from './vectorGuides';
+
+import { drawPolylineVertices, SHAPE_PREVIEW_COLOR, SHAPE_PREVIEW_DASH } from './rasterizers/shapeRasterizer';
/** Minimum screen-space grid spacing (px) below which the grid is too dense to draw. */
export const MIN_GRID_SPACING_PX = 8;
@@ -106,6 +110,9 @@ export interface RectShapePreview {
/** Everything the overlay needs to draw a frame. */
export interface OverlayState {
+ vectorEdit?: VectorEditOverlay | null;
+ vectorGuides?: readonly VectorGuideLayer[];
+ vectorShapePreview?: VectorShapePreview | null;
/** Document→CSS-pixel transform. */
view: Mat2d;
/** Backing-store pixels per CSS pixel. */
@@ -417,12 +424,6 @@ const drawTransformFrame = (ctx: Ctx, state: OverlayState): void => {
ctx.restore();
};
-const LASSO_PREVIEW_COLOR = '#38bdf8';
-const LASSO_PREVIEW_DASH: readonly number[] = [4, 4];
-
-/** Screen-space half-size of a placed polygon vertex knob. */
-const LASSO_VERTEX_HALF_PX = 2;
-
/** Dashed lasso preview; polygons add vertices and a first-vertex close-radius cue filled on hover. */
const drawLassoPreview = (ctx: Ctx, state: OverlayState): void => {
const preview = state.lassoPreview;
@@ -434,10 +435,10 @@ const drawLassoPreview = (ctx: Ctx, state: OverlayState): void => {
return;
}
ctx.save();
- ctx.strokeStyle = LASSO_PREVIEW_COLOR;
- ctx.fillStyle = LASSO_PREVIEW_COLOR;
+ ctx.strokeStyle = SHAPE_PREVIEW_COLOR;
+ ctx.fillStyle = SHAPE_PREVIEW_COLOR;
ctx.lineWidth = 1;
- ctx.setLineDash([...LASSO_PREVIEW_DASH]);
+ ctx.setLineDash([...SHAPE_PREVIEW_DASH]);
ctx.beginPath();
outline.forEach((point, index) => {
const p = applyToPoint(state.view, point);
@@ -452,24 +453,7 @@ const drawLassoPreview = (ctx: Ctx, state: OverlayState): void => {
ctx.stroke();
ctx.setLineDash([]);
if (preview.kind === 'polygon') {
- preview.points.forEach((point, index) => {
- const p = applyToPoint(state.view, point);
- if (index === 0 && preview.closeRadiusPx !== null) {
- ctx.beginPath();
- ctx.arc(p.x, p.y, preview.closeRadiusPx, 0, Math.PI * 2);
- if (preview.closeArmed) {
- ctx.fill();
- }
- ctx.stroke();
- } else {
- ctx.fillRect(
- p.x - LASSO_VERTEX_HALF_PX,
- p.y - LASSO_VERTEX_HALF_PX,
- LASSO_VERTEX_HALF_PX * 2,
- LASSO_VERTEX_HALF_PX * 2
- );
- }
- });
+ drawPolylineVertices(ctx, state.view, preview.points, preview.closeRadiusPx, preview.closeArmed);
}
ctx.restore();
};
@@ -480,9 +464,9 @@ const drawRectShapePreview = (ctx: Ctx, state: OverlayState, preview: RectShapeP
}
const screen = transformBounds(state.view, preview.rect);
ctx.save();
- ctx.strokeStyle = LAYER_OUTLINE_COLOR;
+ ctx.strokeStyle = SHAPE_PREVIEW_COLOR;
ctx.lineWidth = 1;
- ctx.setLineDash([...BBOX_DASH]);
+ ctx.setLineDash([...SHAPE_PREVIEW_DASH]);
// The same path the rasterizer commits, so the outline is the shape it makes.
buildParametricShapePath(ctx, preview.kind, screen.x, screen.y, Math.abs(screen.width), Math.abs(screen.height));
ctx.stroke();
@@ -833,7 +817,11 @@ const drawBboxHandles = (ctx: Ctx, frame: BboxFrameGeometry, dpr: number): void
};
/** Clears the backing store, then redraws the overlay in CSS pixels under the state's device-pixel ratio. */
-export const renderOverlay = (target: RasterSurface, state: OverlayState): void => {
+export const renderOverlay = (
+ target: RasterSurface,
+ state: OverlayState,
+ renderVectors?: (ctx: RasterSurface['ctx'], state: OverlayState) => void
+): void => {
const ctx = target.ctx;
const base: Mat2d = { a: state.dpr, b: 0, c: 0, d: state.dpr, e: 0, f: 0 };
@@ -864,6 +852,7 @@ export const renderOverlay = (target: RasterSurface, state: OverlayState): void
drawSamPreview(ctx, state, base);
drawSamGeometry(ctx, state);
+ renderVectors?.(ctx, state);
drawLayerOutline(ctx, state);
if (state.bboxHandles) {
drawBboxHandles(ctx, bboxFrame, state.dpr);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.ts
index f26f6a69de..155040bbb1 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.ts
@@ -5,6 +5,9 @@
import type { CanvasLayerSourceContract, ParametricShapeKind } from '@workbench/canvas-engine/contracts';
import type { RasterSurface } from '@workbench/canvas-engine/render/raster';
+import type { Mat2d, Vec2 } from '@workbench/canvas-engine/types';
+
+import { applyToPoint } from '@workbench/canvas-engine/math/mat2d';
import type { RasterizeDeps, RasterizeResult } from './types';
@@ -138,3 +141,36 @@ export const rasterizeShapeSource = (
return Promise.resolve({ rect: { height, width, x: 0, y: 0 }, surface });
};
+
+export const SHAPE_PREVIEW_COLOR = '#38bdf8';
+export const SHAPE_PREVIEW_DASH: readonly number[] = [4, 4];
+const VERTEX_HALF_PX = 2;
+
+/** Shared Shapes/polyline markers in CSS pixels: vertices and a close target filled while armed. */
+export const drawPolylineVertices = (
+ ctx: RasterSurface['ctx'],
+ view: Mat2d,
+ points: readonly Vec2[],
+ closeRadiusPx: number | null,
+ closeArmed: boolean
+): void => {
+ ctx.save();
+ ctx.setLineDash([]);
+ ctx.strokeStyle = SHAPE_PREVIEW_COLOR;
+ ctx.fillStyle = SHAPE_PREVIEW_COLOR;
+ ctx.lineWidth = 1;
+ points.forEach((point, index) => {
+ const p = applyToPoint(view, point);
+ if (index === 0 && closeRadiusPx !== null) {
+ ctx.beginPath();
+ ctx.arc(p.x, p.y, closeRadiusPx, 0, Math.PI * 2);
+ if (closeArmed) {
+ ctx.fill();
+ }
+ ctx.stroke();
+ } else {
+ ctx.fillRect(p.x - VERTEX_HALF_PX, p.y - VERTEX_HALF_PX, VERTEX_HALF_PX * 2, VERTEX_HALF_PX * 2);
+ }
+ });
+ ctx.restore();
+};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/thumbnail.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/thumbnail.ts
index 3c8fe94a9a..4114b288d6 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/thumbnail.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/thumbnail.ts
@@ -46,6 +46,9 @@ export const resolveLayerThumbnailImageRef = (layer: CanvasLayerContract): Canva
/** Display-only properties that alter a layer thumbnail without changing its raster cache. */
export const getLayerThumbnailDisplayKey = (layer: CanvasLayerContract): string => {
+ if (layer.type === 'vector') {
+ return `vector:${layer.opacity}`;
+ }
if (layer.type === 'raster') {
return `raster:${layer.opacity}:${adjustmentsKey(layer.adjustments)}`;
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/vectorEditOverlay.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/vectorEditOverlay.ts
new file mode 100644
index 0000000000..e85b454ddc
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/vectorEditOverlay.ts
@@ -0,0 +1,86 @@
+import type { Mat2d } from '@workbench/canvas-engine/types';
+import type { VectorEditSession } from '@workbench/canvas-engine/vectorEditState';
+
+import { applyToPoint, multiply } from '@workbench/canvas-engine/math/mat2d';
+import { transformBounds } from '@workbench/canvas-engine/math/rect';
+import { vectorHandleLayout } from '@workbench/canvas-engine/math/vectorHandleLayout';
+
+import type { RasterSurface } from './raster';
+
+export interface VectorEditOverlay {
+ session: VectorEditSession;
+ matrix: Mat2d;
+}
+
+/** Editable anchors/handles use screen-sized hit targets; guide curves are drawn by vectorGuides. */
+export const drawVectorEditOverlay = (
+ ctx: RasterSurface['ctx'],
+ view: Mat2d,
+ overlay: VectorEditOverlay | null
+): void => {
+ if (!overlay) {
+ return;
+ }
+ const { session } = overlay;
+ if (session.pathTransform) {
+ return;
+ }
+ const matrix = multiply(view, overlay.matrix);
+ const selected = new Set(session.selectedPoints.map((ref) => `${ref.pathId}:${ref.pointIndex}`));
+ const active = session.selectedPoints.at(-1);
+ ctx.save();
+ ctx.setLineDash([]);
+ ctx.lineWidth = 1;
+ ctx.strokeStyle = 'rgba(90, 175, 255, 0.75)';
+ for (const ref of session.selectedPoints) {
+ const path = session.paths.find((path) => path.id === ref.pathId);
+ const point = path?.points[ref.pointIndex];
+ if (!path || !point) {
+ continue;
+ }
+ const anchor = applyToPoint(matrix, point.anchor);
+ const handles = vectorHandleLayout(path, ref.pointIndex, matrix);
+ for (const p of [handles.inHandle, handles.outHandle]) {
+ if (!p) {
+ continue;
+ }
+ ctx.beginPath();
+ ctx.moveTo(anchor.x, anchor.y);
+ ctx.lineTo(p.x, p.y);
+ ctx.stroke();
+ ctx.beginPath();
+ ctx.arc(p.x, p.y, 3.5, 0, Math.PI * 2);
+ ctx.fillStyle = '#fff';
+ ctx.fill();
+ ctx.stroke();
+ }
+ }
+ for (const path of session.paths) {
+ path.points.forEach((point, pointIndex) => {
+ const isSelected = selected.has(`${path.id}:${pointIndex}`);
+ const isActive = active?.pathId === path.id && active.pointIndex === pointIndex;
+ const p = applyToPoint(matrix, point.anchor);
+ ctx.beginPath();
+ ctx.arc(p.x, p.y, 4, 0, Math.PI * 2);
+ ctx.lineWidth = 2;
+ ctx.fillStyle = isActive
+ ? 'rgba(90, 175, 255, 1)'
+ : isSelected
+ ? 'rgba(90, 175, 255, 0.55)'
+ : 'rgba(255, 255, 255, 0.95)';
+ ctx.strokeStyle = isActive ? '#3ed684' : isSelected ? 'rgba(255, 255, 255, 0.9)' : 'rgba(90, 175, 255, 1)';
+ ctx.fill();
+ ctx.stroke();
+ });
+ }
+ ctx.globalAlpha = 1;
+ if (session.selectionRect) {
+ const rect = transformBounds(view, session.selectionRect);
+ ctx.fillStyle = 'rgba(90, 175, 255, 0.12)';
+ ctx.strokeStyle = 'rgba(90, 175, 255, 0.9)';
+ ctx.lineWidth = 1;
+ ctx.fillRect(rect.x, rect.y, rect.width, rect.height);
+ ctx.strokeRect(rect.x, rect.y, rect.width, rect.height);
+ }
+ ctx.restore();
+};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/vectorGuides.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/vectorGuides.ts
new file mode 100644
index 0000000000..c4c9f7a25f
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/vectorGuides.ts
@@ -0,0 +1,107 @@
+import type { CanvasBezierPathContract, CanvasBezierPointContract } from '@workbench/canvas-engine/contracts';
+import type { Mat2d, Vec2 } from '@workbench/canvas-engine/types';
+
+import { DEFAULT_VECTOR_GUIDE_COLOR } from '@workbench/canvas-engine/contracts';
+import { applyToPoint, multiply } from '@workbench/canvas-engine/math/mat2d';
+
+import type { RasterSurface } from './raster';
+
+import { drawPolylineVertices, SHAPE_PREVIEW_COLOR, SHAPE_PREVIEW_DASH } from './rasterizers/shapeRasterizer';
+
+export interface VectorGuideLayer {
+ paths: readonly CanvasBezierPathContract[];
+ matrix: Mat2d;
+ opacity: number;
+ guideColor?: string;
+ /** Undefined outside Edit; null means Edit has no active path. */
+ editActivePathId?: string | null;
+}
+
+/** Creation geometry is in document space; committed paths are in layer-local space. */
+export interface VectorShapePreview {
+ layerId: string;
+ points: CanvasBezierPointContract[];
+ isClosed: boolean;
+ vertices: readonly Vec2[] | null;
+ closeRadiusPx: number | null;
+ closeArmed: boolean;
+}
+
+const GUIDE_COLOR = DEFAULT_VECTOR_GUIDE_COLOR;
+
+/** Project controls before stroking so nonuniform layer scaling preserves the 1.5 CSS-px guide. */
+const strokePath = (
+ ctx: RasterSurface['ctx'],
+ points: readonly CanvasBezierPointContract[],
+ isClosed: boolean,
+ matrix: Mat2d
+): void => {
+ const first = points[0];
+ if (!first) {
+ return;
+ }
+ const start = applyToPoint(matrix, first.anchor);
+ ctx.beginPath();
+ ctx.moveTo(start.x, start.y);
+ const segments = isClosed ? points.length : points.length - 1;
+ for (let index = 0; index < segments; index += 1) {
+ const from = points[index]!;
+ const to = points[(index + 1) % points.length]!;
+ const a = applyToPoint(matrix, from.outHandle ?? from.anchor);
+ const b = applyToPoint(matrix, to.inHandle ?? to.anchor);
+ const end = applyToPoint(matrix, to.anchor);
+ ctx.bezierCurveTo(a.x, a.y, b.x, b.y, end.x, end.y);
+ }
+ if (isClosed) {
+ ctx.closePath();
+ }
+ ctx.stroke();
+};
+
+/** Overlay-only: never called by image sampling, raster export or generation composites. */
+export const drawVectorGuides = (
+ ctx: RasterSurface['ctx'],
+ view: Mat2d,
+ layers: readonly VectorGuideLayer[],
+ preview: VectorShapePreview | null
+): void => {
+ if (layers.length === 0 && !preview) {
+ return;
+ }
+ ctx.save();
+ ctx.setLineDash([]);
+ ctx.strokeStyle = GUIDE_COLOR;
+ ctx.lineWidth = 1.5;
+ ctx.lineCap = 'round';
+ ctx.lineJoin = 'round';
+ for (const layer of layers) {
+ ctx.globalAlpha = layer.opacity;
+ const matrix = multiply(view, layer.matrix);
+ const editing = layer.editActivePathId !== undefined;
+ ctx.strokeStyle = layer.guideColor ?? GUIDE_COLOR;
+ ctx.lineWidth = 1.5;
+ for (const path of layer.paths) {
+ if (editing && path.id === layer.editActivePathId) {
+ continue;
+ }
+ strokePath(ctx, path.points, path.isClosed, matrix);
+ }
+ const active = editing ? layer.paths.find((path) => path.id === layer.editActivePathId) : null;
+ if (active) {
+ ctx.globalAlpha = layer.opacity;
+ ctx.lineWidth = 2.25;
+ strokePath(ctx, active.points, active.isClosed, matrix);
+ }
+ }
+ ctx.globalAlpha = 1;
+ if (preview) {
+ ctx.strokeStyle = SHAPE_PREVIEW_COLOR;
+ ctx.lineWidth = 1;
+ ctx.setLineDash([...SHAPE_PREVIEW_DASH]);
+ strokePath(ctx, preview.points, preview.isClosed, view);
+ if (preview.vertices) {
+ drawPolylineVertices(ctx, view, preview.vertices, preview.closeRadiusPx, preview.closeArmed);
+ }
+ }
+ ctx.restore();
+};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.ts
index 8a2453c2c5..1a0227ead8 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.ts
@@ -79,7 +79,7 @@ const predictRefusal = (ctx: ToolContext): CanvasLayerEditRefusal | null => {
if (!leaf || !selected) {
return null;
}
- if (isMaskLayer(selected)) {
+ if (isMaskLayer(selected) || selected.type === 'vector') {
return { layerId: selected.id, layerName: selected.name, status: 'gradient-unsupported' };
}
const status = selected.type === 'raster' && selected.source.type === 'gradient' ? leafEditRefusal(leaf) : 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 3f1a780844..0d4b0737cf 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.ts
@@ -13,7 +13,7 @@ import type { Rect, Vec2 } from '@workbench/canvas-engine/types';
import { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/document/sources';
import { applyToPoint, fromTRS, invert } from '@workbench/canvas-engine/math/mat2d';
-import { isEmpty, union } from '@workbench/canvas-engine/math/rect';
+import { getBezierPathBounds, isEmpty, union } from '@workbench/canvas-engine/math/rect';
type LayerTransform = CanvasLayerBaseContract['transform'];
@@ -26,6 +26,17 @@ export const hittableLayerRect = (
doc: CanvasDocumentContractV3,
liveRect?: Rect
): Rect | null => {
+ if (layer.type === 'vector') {
+ let bounds: Rect | null = null;
+ for (const path of layer.paths) {
+ if (path.points.length < 2) {
+ continue;
+ }
+ const rect = getBezierPathBounds(path.points, path.isClosed);
+ bounds = bounds ? union(bounds, rect) : rect;
+ }
+ return bounds ? { ...bounds, width: Math.max(1, bounds.width), height: Math.max(1, bounds.height) } : null;
+ }
if (!renderableSourceOf(layer)) {
return null;
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts
index 59979f11d4..937e8a5c6b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts
@@ -138,6 +138,10 @@ const resolveTarget = (ctx: ToolContext, tool: PaintToolSpec['id']): PaintTarget
const leaf = doc.selectedLayerId ? lookupDocumentLeaf(doc, doc.selectedLayerId) : null;
const selected = leaf?.layer;
+ if (selected?.type === 'vector') {
+ return null;
+ }
+
if (leaf && selected && selected.type === 'raster' && selected.source.type === 'paint') {
// Locked/hidden paint targets refuse rather than silently creating another layer.
const refusal = leafPaintRefusal(leaf);
@@ -303,7 +307,9 @@ export const createPaintTool = (spec: PaintToolSpec): Tool => {
cursor: (ctx) => {
const doc = ctx.getDocument();
const leaf = doc?.selectedLayerId ? lookupDocumentLeaf(doc, doc.selectedLayerId) : null;
- return !session && predictsRefusal(leaf, spec.id) ? 'not-allowed' : 'crosshair';
+ return !session && (leaf?.layer.type === 'vector' || predictsRefusal(leaf, spec.id))
+ ? 'not-allowed'
+ : 'crosshair';
},
// A press paints the selected leaf in place unless it is refused up front; any other selection gets a new layer.
editsSelectedLayer: (ctx) => {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts
index cd9b97ab7a..0e7642f6f9 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts
@@ -1,5 +1,5 @@
/**
- * Shapes use box drags, polygon clicks or closed freehand. Place on = selected layer draws into a selected paint layer
+ * Vector targets delegate to the v6 guide-creation gestures. Raster Shapes use box drags, polygon clicks or closed freehand. Place on = selected layer draws into a selected paint layer
* or mask (as opaque mask coverage); any other selection, or Place on = new layer, adds a parametric shape layer.
* Shift squares a box and Alt grows it from the press point, both read live on every move and the release, as the
* marquee does; polygon and freehand ignore them. The platform's mod key (⌘ on macOS, where Ctrl-click opens the
@@ -85,7 +85,15 @@ const CUTOUT_CURSOR_SVG = `<svg xmlns='http://www.w3.org/2000/svg' width='24' he
</svg>`;
type Session =
- | { kind: 'drag'; startDoc: Vec2; startScreen: Vec2; moved: boolean; editsSelected: boolean }
+ | {
+ kind: 'drag';
+ startDoc: Vec2;
+ startScreen: Vec2;
+ lastDoc: Vec2;
+ spaceHeld: boolean;
+ moved: boolean;
+ editsSelected: boolean;
+ }
| {
kind: 'polyline';
session: PolylineSession;
@@ -188,8 +196,15 @@ const resolveTarget = (ctx: ToolContext, mode: ShapeMode, loading: 'request' | '
};
/** Creates a fresh shape tool with its own gesture state; `isMacOs` picks the cutout key. */
-export const createShapeTool = ({ isMacOs = IS_MAC_OS }: { isMacOs?: boolean } = {}): Tool => {
+export const createShapeTool = ({
+ isMacOs = IS_MAC_OS,
+ getVectorTool = () => null,
+}: { isMacOs?: boolean; getVectorTool?: () => Tool | null } = {}): Tool => {
let session: Session | null = null;
+ const selectsVector = (ctx: ToolContext): boolean => {
+ const doc = ctx.getDocument();
+ return !!doc?.selectedLayerId && lookupDocumentLeaf(doc, doc.selectedLayerId)?.layer.type === 'vector';
+ };
/** The cutout key on the latest pointer event, which picks the cursor cue. */
let cutoutHeld = false;
const cutoutCursor = `url("data:image/svg+xml,${encodeURIComponent(CUTOUT_CURSOR_SVG)}") 12 12, crosshair`;
@@ -444,6 +459,12 @@ export const createShapeTool = ({ isMacOs = IS_MAC_OS }: { isMacOs?: boolean } =
return {
cursor: (ctx) => {
+ if (selectsVector(ctx)) {
+ return getVectorTool()?.cursor?.(ctx) ?? 'not-allowed';
+ }
+ if (session?.kind === 'drag' && session.spaceHeld) {
+ return 'move';
+ }
if (session?.kind === 'polyline' && session.session.closeArmed) {
return 'pointer';
}
@@ -454,8 +475,22 @@ export const createShapeTool = ({ isMacOs = IS_MAC_OS }: { isMacOs?: boolean } =
return mode === 'cutout' ? cutoutCursor : 'crosshair';
},
id: 'shape',
+ hasSession: () => session !== null || (getVectorTool()?.hasSession?.() ?? false),
+ onDocumentChanged: (ctx) => getVectorTool()?.onDocumentChanged?.(ctx),
+ onModifierKey: (ctx, code, pressed) => {
+ if (selectsVector(ctx)) {
+ return getVectorTool()?.onModifierKey?.(ctx, code, pressed) ?? false;
+ }
+ if (code !== 'Space' || session?.kind !== 'drag') {
+ return false;
+ }
+ session.spaceHeld = pressed;
+ ctx.updateCursor();
+ return true;
+ },
usesAltKey: true,
onDeactivate: (ctx, opts) => {
+ getVectorTool()?.onDeactivate?.(ctx, opts);
// A modifier-hold switch (space → view to pan mid-polygon) keeps the session.
if (!opts?.temporary) {
cutoutHeld = false;
@@ -463,6 +498,9 @@ export const createShapeTool = ({ isMacOs = IS_MAC_OS }: { isMacOs?: boolean } =
}
},
onKeyCommand: (ctx, command) => {
+ if (getVectorTool()?.hasSession?.()) {
+ return getVectorTool()?.onKeyCommand?.(ctx, command) ?? false;
+ }
if (!session) {
return false;
}
@@ -481,11 +519,19 @@ export const createShapeTool = ({ isMacOs = IS_MAC_OS }: { isMacOs?: boolean } =
}
return true;
},
- onPointerCancel: (ctx) => reset(ctx),
+ onPointerCancel: (ctx) => {
+ reset(ctx);
+ getVectorTool()?.onPointerCancel?.(ctx);
+ },
onPointerDown: (ctx, input) => {
if ((input.buttons & PRIMARY_BUTTON) === 0 || !ctx.getDocument()) {
return;
}
+ if (selectsVector(ctx)) {
+ reset(ctx);
+ getVectorTool()?.onPointerDown?.(ctx, input);
+ return;
+ }
noteModifiers(ctx, input.modifiers);
const kind = ctx.stores.shapeOptions.get().kind;
if (session && !sessionFitsKind(session, kind)) {
@@ -507,10 +553,16 @@ export const createShapeTool = ({ isMacOs = IS_MAC_OS }: { isMacOs?: boolean } =
moved: false,
startDoc: input.documentPoint,
startScreen: input.screenPoint,
+ lastDoc: input.documentPoint,
+ spaceHeld: false,
};
noteSelectedLayerEdit(ctx, session, input.modifiers);
},
onPointerMove: (ctx, input, batch) => {
+ if (getVectorTool()?.hasSession?.() || selectsVector(ctx)) {
+ getVectorTool()?.onPointerMove?.(ctx, input, batch);
+ return;
+ }
noteModifiers(ctx, input.modifiers);
if (!session) {
return;
@@ -535,6 +587,13 @@ export const createShapeTool = ({ isMacOs = IS_MAC_OS }: { isMacOs?: boolean } =
ctx.invalidate({ overlay: true });
return;
}
+ if (session.spaceHeld) {
+ session.startDoc = {
+ x: session.startDoc.x + input.documentPoint.x - session.lastDoc.x,
+ y: session.startDoc.y + input.documentPoint.y - session.lastDoc.y,
+ };
+ }
+ session.lastDoc = input.documentPoint;
if (!session.moved) {
const dxs = input.screenPoint.x - session.startScreen.x;
const dys = input.screenPoint.y - session.startScreen.y;
@@ -550,6 +609,10 @@ export const createShapeTool = ({ isMacOs = IS_MAC_OS }: { isMacOs?: boolean } =
}
},
onPointerUp: (ctx, input) => {
+ if (getVectorTool()?.hasSession?.() || selectsVector(ctx)) {
+ getVectorTool()?.onPointerUp?.(ctx, input);
+ return;
+ }
noteModifiers(ctx, input.modifiers);
if (!session) {
return;
@@ -570,6 +633,12 @@ export const createShapeTool = ({ isMacOs = IS_MAC_OS }: { isMacOs?: boolean } =
reset(ctx);
return;
}
+ if (session.spaceHeld) {
+ session.startDoc = {
+ x: session.startDoc.x + input.documentPoint.x - session.lastDoc.x,
+ y: session.startDoc.y + input.documentPoint.y - session.lastDoc.y,
+ };
+ }
commit(ctx, boxShape(ctx, dragRect(session.startDoc, input.documentPoint, constraintsOf(input.modifiers))), mode);
},
};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
index 04dfc3bdae..a74c1c1b68 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
@@ -219,6 +219,8 @@ export interface ToolActivationOptions {
/** A stateless-to-the-engine interaction handler. Implementations may hold private drag state. */
export interface Tool {
readonly id: ToolId;
+ /** A multi-press creation session may remain active between pointer gestures. */
+ hasSession?(): boolean;
/** Called when the tool becomes active. */
onActivate?(ctx: ToolContext, opts?: ToolActivationOptions): void;
/** Called when the tool is deactivated (also on engine dispose). */
@@ -240,6 +242,11 @@ export interface Tool {
* Gesture cancellation stays separate (`onPointerCancel`) and runs first when Escape lands mid-press.
*/
onKeyCommand?(ctx: ToolContext, command: 'apply' | 'cancel'): boolean;
+ /** Owned modifier changes; returning true keeps a modifier from activating a temporary tool. */
+ onModifierKey?(ctx: ToolContext, code: 'Space' | 'Alt' | 'Shift', pressed: boolean): boolean;
+ /** Drop or reconcile an unfinished gesture when its document target changes. Never dispatch from this hook. */
+ onDocumentChanged?(ctx: ToolContext): void;
+
/** Wheel over the canvas; `screenAnchor` is the CSS-pixel cursor position. */
onWheel?(ctx: ToolContext, deltaY: number, screenAnchor: { x: number; y: number }, modifiers: PointerModifiers): void;
/** The CSS cursor to show while this tool is active. */
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/vectorShapeTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/vectorShapeTool.test.ts
new file mode 100644
index 0000000000..aa2f7a5aca
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/vectorShapeTool.test.ts
@@ -0,0 +1,87 @@
+import type { PointerInput } from '@workbench/canvas-engine/types';
+
+import { documentFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
+import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
+import { createVectorLayer } from '@workbench/canvas-engine/document/vectorLayerFactories';
+import { createEngineStores } from '@workbench/canvas-engine/engineStores';
+import { createViewport } from '@workbench/canvas-engine/viewport';
+import { describe, expect, it, vi } from 'vitest';
+
+import type { ToolContext } from './tool';
+
+import { createVectorShapeTool } from './vectorShapeTool';
+
+const pointer = (x: number, y: number, timeStamp = 0): PointerInput => ({
+ buttons: 1,
+ documentPoint: { x, y },
+ screenPoint: { x, y },
+ pressure: 0.5,
+ pointerType: 'mouse',
+ timeStamp,
+ modifiers: { alt: false, ctrl: false, meta: false, shift: false },
+});
+const harness = () => {
+ const layer = createVectorLayer({ id: 'v', name: 'Vector' }),
+ doc = documentFrom([layer], layer.id);
+ const stores = createEngineStores();
+ stores.shapeOptions.set({ ...stores.shapeOptions.get(), target: 'selected', kind: 'rect' });
+ let nextId = 0;
+ const commit = vi.fn<ToolContext['commitStructural']>(() => ({ status: 'committed' }));
+ const ctx = {
+ getDocument: () => doc,
+ stores,
+ viewport: createViewport(),
+ commitStructural: commit,
+ createLayerId: () => `path-${++nextId}`,
+ captureInsertionAnchor: createTestInsertionAnchorCapture('p'),
+ scheduleFrame: (task: () => void) => {
+ task();
+ return () => {};
+ },
+ invalidate: vi.fn(),
+ updateCursor: vi.fn(),
+ reportEditRefusal: vi.fn(),
+ } as unknown as ToolContext;
+ return { tool: createVectorShapeTool(), ctx, commit, stores };
+};
+describe('vector Shapes draft safety', () => {
+ it('keeps a refused shape visible, reports the reason and retries it with Enter', () => {
+ const h = harness();
+ h.commit.mockReturnValueOnce({ status: 'over-budget' });
+ h.tool.onPointerDown!(h.ctx, pointer(10, 10));
+ h.tool.onPointerMove!(h.ctx, pointer(100, 50), [pointer(100, 50)]);
+ h.tool.onPointerUp!(h.ctx, pointer(100, 50));
+ expect(h.tool.hasSession()).toBe(true);
+ expect(h.stores.vectorShapePreview.get()?.points).toHaveLength(4);
+ expect(h.ctx.reportEditRefusal).toHaveBeenCalledWith('over-budget');
+ h.tool.onKeyCommand!(h.ctx, 'apply');
+ expect(h.commit).toHaveBeenCalledTimes(2);
+ expect(h.tool.hasSession()).toBe(false);
+ });
+ it('continues a polyline between presses until Enter and drops canceled geometry without commits', () => {
+ const h = harness();
+ h.stores.shapeOptions.set({ ...h.stores.shapeOptions.get(), kind: 'polygon' });
+ for (const [x, y, time] of [
+ [0, 0, 0],
+ [100, 0, 1000],
+ [100, 100, 2000],
+ ]) {
+ h.tool.onPointerDown!(h.ctx, pointer(x!, y!, time));
+ h.tool.onPointerUp!(h.ctx, pointer(x!, y!, time));
+ expect(h.tool.hasSession()).toBe(true);
+ }
+ expect(h.commit).not.toHaveBeenCalled();
+ h.tool.onKeyCommand!(h.ctx, 'apply');
+ const mutation = h.commit.mock.calls[0]![1];
+ expect(mutation.type).toBe('updateCanvasLayerConfig');
+ if (mutation.type !== 'updateCanvasLayerConfig' || mutation.config.layerType !== 'vector') {
+ throw new Error('Expected vector');
+ }
+ expect(mutation.config.paths?.[0]).toMatchObject({ isClosed: false });
+ expect(mutation.config.paths?.[0]?.points).toHaveLength(3);
+ h.tool.onPointerDown!(h.ctx, pointer(20, 20, 3000));
+ h.tool.onPointerCancel!(h.ctx);
+ expect(h.tool.hasSession()).toBe(false);
+ expect(h.commit).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/vectorShapeTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/vectorShapeTool.ts
new file mode 100644
index 0000000000..419f998a9d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/vectorShapeTool.ts
@@ -0,0 +1,492 @@
+import type {
+ CanvasBezierPointContract,
+ CanvasVectorLayerContract,
+ ParametricShapeKind,
+} from '@workbench/canvas-engine/contracts';
+import type { ShapeToolOptions } from '@workbench/canvas-engine/engineStores';
+import type { Mat2d, PointerInput, Rect, Vec2 } from '@workbench/canvas-engine/types';
+
+import { addedVectorLayerMutations } from '@workbench/canvas-engine/controllers/editSteps';
+import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';
+import { getDocumentIndex } from '@workbench/canvas-engine/document/documentIndex';
+import { leafEditRefusal } from '@workbench/canvas-engine/document/layerEligibility';
+import { createVectorLayer, nextVectorLayerName } from '@workbench/canvas-engine/document/vectorLayerFactories';
+import {
+ anchorsToBezierPoints,
+ fitPolylineToBezierPoints,
+ ovalToBezierPoints,
+ rectToBezierPoints,
+} from '@workbench/canvas-engine/math/bezierPath';
+import { applyToPoint, invert } from '@workbench/canvas-engine/math/mat2d';
+import { polygonShapeVertices } from '@workbench/canvas-engine/math/shapeGeometry';
+import { getStrokePoints } from 'perfect-freehand';
+
+import type { Tool, ToolContext } from './tool';
+
+import { layerMatrix } from './moveHitTest';
+
+type Session = {
+ layer: CanvasVectorLayerContract;
+ toLocal: Mat2d;
+ kind: ShapeToolOptions['kind'];
+ target: ShapeToolOptions['target'];
+ start: Vec2;
+ points: Vec2[];
+ input: PointerInput;
+ lastSample: Vec2;
+ lastPress: { screen: Vec2; time: number };
+ closeArmed: boolean;
+ spaceHeld: boolean;
+ finish?: boolean;
+ pending?: { points: CanvasBezierPointContract[]; isClosed: boolean };
+};
+
+export interface VectorShapeTool extends Tool {
+ hasSession(): boolean;
+}
+
+const distance = (a: Vec2, b: Vec2): number => Math.hypot(a.x - b.x, a.y - b.y);
+const CLOSE_RADIUS_PX = 10;
+const isBoxKind = (kind: ShapeToolOptions['kind']): kind is ParametricShapeKind =>
+ kind !== 'polygon' && kind !== 'freehand';
+
+const boxPoints = (kind: ParametricShapeKind, rect: Rect): CanvasBezierPointContract[] => {
+ if (kind === 'rect') {
+ return rectToBezierPoints(rect);
+ }
+ if (kind === 'ellipse') {
+ return ovalToBezierPoints(rect);
+ }
+ return anchorsToBezierPoints(polygonShapeVertices(kind, rect));
+};
+
+/** v6 box gestures: Shift constrains aspect, Alt draws from center, Space translates the live box. */
+const dragRect = (session: Session): Rect => {
+ let dx = session.input.documentPoint.x - session.start.x;
+ let dy = session.input.documentPoint.y - session.start.y;
+ if (session.input.modifiers.shift) {
+ const side = Math.max(Math.abs(dx), Math.abs(dy));
+ const signX = dx !== 0 ? Math.sign(dx) : dy !== 0 ? Math.sign(dy) : 1;
+ const signY = dy !== 0 ? Math.sign(dy) : signX;
+ dx = side * signX;
+ dy = side * signY;
+ }
+ const fromCenter = session.input.modifiers.alt;
+ const x1 = session.start.x - (fromCenter ? dx : 0);
+ const y1 = session.start.y - (fromCenter ? dy : 0);
+ const x2 = session.start.x + dx;
+ const y2 = session.start.y + dy;
+ return { x: Math.min(x1, x2), y: Math.min(y1, y2), width: Math.abs(x2 - x1), height: Math.abs(y2 - y1) };
+};
+
+export const createVectorShapeTool = (): VectorShapeTool => {
+ let session: Session | null = null;
+ let cancelPreviewFrame: (() => void) | null = null;
+
+ const reset = (ctx: ToolContext): void => {
+ cancelPreviewFrame?.();
+ cancelPreviewFrame = null;
+ session = null;
+ ctx.stores.vectorShapePreview.set(null);
+ ctx.invalidate({ overlay: true });
+ };
+
+ const eligible = (ctx: ToolContext): boolean => {
+ const doc = ctx.getDocument();
+ const leaf = doc?.selectedLayerId ? lookupDocumentLeaf(doc, doc.selectedLayerId) : null;
+ return !!leaf && leaf.layer.type === 'vector' && !leaf.documentHidden && leafEditRefusal(leaf) === null;
+ };
+
+ const isCurrent = (ctx: ToolContext): boolean => {
+ if (!session) {
+ return false;
+ }
+ const doc = ctx.getDocument();
+ const leaf = doc?.selectedLayerId ? lookupDocumentLeaf(doc, doc.selectedLayerId) : null;
+ const options = ctx.stores.shapeOptions.get();
+ if (
+ !leaf ||
+ leaf.layer.type !== 'vector' ||
+ leaf.id !== session.layer.id ||
+ leaf.documentHidden ||
+ leafEditRefusal(leaf) ||
+ leaf.layer.paths !== session.layer.paths ||
+ leaf.layer.transform !== session.layer.transform ||
+ options.kind !== session.kind ||
+ options.target !== session.target
+ ) {
+ reset(ctx);
+ return false;
+ }
+ return true;
+ };
+
+ const snapInput = (input: PointerInput, current: Session): PointerInput => {
+ if (current.kind === 'freehand') {
+ return input;
+ }
+ const local = applyToPoint(current.toLocal, input.documentPoint);
+ const documentPoint = applyToPoint(layerMatrix(current.layer.transform), {
+ x: Math.floor(local.x),
+ y: Math.floor(local.y),
+ });
+ return { ...input, documentPoint };
+ };
+
+ const polygonCursor = (ctx: ToolContext, current: Session): Vec2 => {
+ const point = current.input.documentPoint;
+ const first = current.points[0]!;
+ current.closeArmed =
+ current.points.length >= 3 &&
+ distance(ctx.viewport.documentToScreen(first), current.input.screenPoint) <= CLOSE_RADIUS_PX;
+ if (current.closeArmed) {
+ return first;
+ }
+ if (!current.input.modifiers.shift) {
+ return point;
+ }
+ const last = current.points.at(-1)!;
+ const length = distance(last, point);
+ const angle = (Math.round(Math.atan2(point.y - last.y, point.x - last.x) / (Math.PI / 4)) * Math.PI) / 4;
+ const snapped = { x: last.x + Math.cos(angle) * length, y: last.y + Math.sin(angle) * length };
+ if (current.points.length >= 2) {
+ const threshold = CLOSE_RADIUS_PX / ctx.viewport.getZoom();
+ const dx = Math.abs(snapped.x - first.x);
+ const dy = Math.abs(snapped.y - first.y);
+ if (dx <= threshold && (dy > threshold || dx <= dy)) {
+ snapped.x = first.x;
+ } else if (dy <= threshold) {
+ snapped.y = first.y;
+ }
+ }
+ return snapped;
+ };
+
+ const preview = (ctx: ToolContext): void => {
+ if (!session) {
+ return;
+ }
+ const current = session;
+ let points: CanvasBezierPointContract[];
+ let isClosed = false;
+ if (current.pending) {
+ points = current.pending.points;
+ isClosed = current.pending.isClosed;
+ } else if (isBoxKind(current.kind)) {
+ const rect = dragRect(current);
+ points = rect.width > 0 && rect.height > 0 ? boxPoints(current.kind, rect) : [];
+ isClosed = true;
+ } else if (current.kind === 'polygon') {
+ const cursor = polygonCursor(ctx, current);
+ const anchors =
+ current.closeArmed || distance(cursor, current.points.at(-1)!) === 0
+ ? current.points
+ : [...current.points, cursor];
+ points = anchorsToBezierPoints(anchors);
+ isClosed = current.closeArmed;
+ } else {
+ points = anchorsToBezierPoints(current.points);
+ }
+ ctx.stores.vectorShapePreview.set({
+ layerId: current.layer.id,
+ points,
+ isClosed,
+ vertices: current.kind === 'polygon' ? current.points.slice() : null,
+ closeRadiusPx: current.kind === 'polygon' && current.points.length >= 3 ? CLOSE_RADIUS_PX : null,
+ closeArmed: current.closeArmed,
+ });
+ ctx.invalidate({ overlay: true });
+ ctx.updateCursor();
+ };
+
+ // Build the growing freehand preview once per presented frame, not once per coalesced input event.
+ const requestPreview = (ctx: ToolContext): void => {
+ if (cancelPreviewFrame) {
+ return;
+ }
+ let ran = false;
+ const cancel = ctx.scheduleFrame(() => {
+ ran = true;
+ cancelPreviewFrame = null;
+ preview(ctx);
+ });
+ if (!ran) {
+ cancelPreviewFrame = cancel;
+ }
+ };
+
+ const commit = (ctx: ToolContext, points: CanvasBezierPointContract[], isClosed: boolean): void => {
+ if (!isCurrent(ctx) || !session) {
+ return;
+ }
+ const current = session;
+ const doc = ctx.getDocument()!;
+ if (points.length < (isClosed ? 3 : 2)) {
+ reset(ctx);
+ return;
+ }
+ const toLocal = current.target === 'selected' ? current.toLocal : null;
+ const path = {
+ id: ctx.createLayerId(),
+ name: null,
+ isClosed,
+ points: toLocal
+ ? points.map((point) => ({
+ ...point,
+ anchor: applyToPoint(toLocal, point.anchor),
+ inHandle: point.inHandle ? applyToPoint(toLocal, point.inHandle) : null,
+ outHandle: point.outHandle ? applyToPoint(toLocal, point.outHandle) : null,
+ }))
+ : points,
+ };
+ let result: ReturnType<ToolContext['commitStructural']>;
+ if (current.target === 'new') {
+ const layer = createVectorLayer({
+ id: ctx.createLayerId(),
+ name: nextVectorLayerName(getDocumentIndex(doc).nodes.map((entry) => entry.node.name)),
+ });
+ layer.paths = [path];
+ const mutations = addedVectorLayerMutations(
+ layer,
+ ctx.captureInsertionAnchor('vector', current.layer.id),
+ doc.selectedLayerId
+ );
+ result = ctx.commitStructural('Add vector shape', mutations.forward, mutations.inverse);
+ } else {
+ result = ctx.commitStructural(
+ 'Add vector path',
+ {
+ type: 'updateCanvasLayerConfig',
+ id: current.layer.id,
+ config: { layerType: 'vector', paths: [...current.layer.paths, path] },
+ },
+ {
+ type: 'updateCanvasLayerConfig',
+ id: current.layer.id,
+ config: { layerType: 'vector', paths: current.layer.paths },
+ }
+ );
+ }
+ if (result.status === 'committed') {
+ reset(ctx);
+ return;
+ }
+ const status = result.status;
+ ctx.reportEditRefusal?.(
+ status === 'busy' || status === 'gesture-active' || status === 'over-budget' || status === 'not-ready'
+ ? status
+ : 'not-ready'
+ );
+ // Keep the geometry and let Enter retry; a fresh press explicitly starts another shape.
+ current.pending = { points, isClosed };
+ if (session === current) {
+ requestPreview(ctx);
+ }
+ };
+
+ return {
+ id: 'shape',
+ hasSession: () => session !== null,
+ cursor: (ctx) => {
+ if (!eligible(ctx)) {
+ return 'not-allowed';
+ }
+ if (session?.spaceHeld) {
+ return isBoxKind(session.kind) ? 'move' : 'grabbing';
+ }
+ return session?.closeArmed ? 'pointer' : 'crosshair';
+ },
+ onDocumentChanged: (ctx) => {
+ if (session) {
+ isCurrent(ctx);
+ }
+ },
+ onDeactivate: (ctx, options) => {
+ if (!options?.temporary) {
+ reset(ctx);
+ }
+ },
+ onPointerCancel: reset,
+ onModifierKey: (ctx, code, pressed) => {
+ if (!session) {
+ return code === 'Alt' && eligible(ctx) && isBoxKind(ctx.stores.shapeOptions.get().kind);
+ }
+ if (!isCurrent(ctx) || !session) {
+ return false;
+ }
+ if (code === 'Space') {
+ session.spaceHeld = pressed;
+ session.input = snapInput(
+ {
+ ...session.input,
+ documentPoint: ctx.viewport.screenToDocument(session.input.screenPoint),
+ },
+ session
+ );
+ } else {
+ session.input = {
+ ...session.input,
+ modifiers: { ...session.input.modifiers, [code === 'Alt' ? 'alt' : 'shift']: pressed },
+ };
+ }
+ requestPreview(ctx);
+ return code === 'Space' || (code === 'Alt' && isBoxKind(session.kind));
+ },
+ onKeyCommand: (ctx, command) => {
+ if (!session) {
+ return false;
+ }
+ if (command === 'cancel') {
+ reset(ctx);
+ } else if (isCurrent(ctx) && session?.pending) {
+ commit(ctx, session.pending.points, session.pending.isClosed);
+ } else if (session?.kind === 'polygon') {
+ commit(ctx, anchorsToBezierPoints(session.points), false);
+ }
+ return true;
+ },
+ onPointerDown: (ctx, rawInput) => {
+ if ((rawInput.buttons & 1) === 0 || !eligible(ctx)) {
+ return;
+ }
+ if (session && !isCurrent(ctx)) {
+ return;
+ }
+ if (session?.pending) {
+ reset(ctx);
+ }
+ if (!session) {
+ const doc = ctx.getDocument()!;
+ const layer = lookupDocumentLeaf(doc, doc.selectedLayerId!)!.layer as CanvasVectorLayerContract;
+ const toLocal = invert(layerMatrix(layer.transform));
+ if (!toLocal) {
+ return;
+ }
+ const options = ctx.stores.shapeOptions.get();
+ session = {
+ layer,
+ toLocal,
+ kind: options.kind,
+ target: options.target,
+ start: rawInput.documentPoint,
+ points: [],
+ input: rawInput,
+ lastSample: rawInput.screenPoint,
+ lastPress: { screen: rawInput.screenPoint, time: -Infinity },
+ closeArmed: false,
+ spaceHeld: false,
+ };
+ const input = snapInput(rawInput, session);
+ session.input = input;
+ session.start = input.documentPoint;
+ if (session.kind === 'freehand') {
+ session.points = [input.documentPoint];
+ }
+ }
+ if (session.spaceHeld) {
+ return;
+ }
+ if (session.kind === 'polygon') {
+ session.input = snapInput(rawInput, session);
+ const point = session.points.length > 0 ? polygonCursor(ctx, session) : session.input.documentPoint;
+ if (session.closeArmed) {
+ session.finish = true;
+ requestPreview(ctx);
+ return;
+ }
+ if (
+ rawInput.timeStamp - session.lastPress.time <= 350 &&
+ distance(rawInput.screenPoint, session.lastPress.screen) <= 5
+ ) {
+ session.finish = false;
+ return;
+ }
+ session.points.push(point);
+ session.lastPress = { screen: rawInput.screenPoint, time: rawInput.timeStamp };
+ }
+ requestPreview(ctx);
+ },
+ onPointerMove: (ctx, rawInput, batch) => {
+ if (!isCurrent(ctx) || !session) {
+ return;
+ }
+ const current = session;
+ if (current.pending) {
+ return;
+ }
+ if (current.spaceHeld) {
+ if (isBoxKind(current.kind)) {
+ const input = snapInput(rawInput, current);
+ current.start = {
+ x: current.start.x + input.documentPoint.x - current.input.documentPoint.x,
+ y: current.start.y + input.documentPoint.y - current.input.documentPoint.y,
+ };
+ current.input = input;
+ } else {
+ ctx.viewport.panBy({
+ x: rawInput.screenPoint.x - current.input.screenPoint.x,
+ y: rawInput.screenPoint.y - current.input.screenPoint.y,
+ });
+ current.input = { ...rawInput, documentPoint: ctx.viewport.screenToDocument(rawInput.screenPoint) };
+ ctx.invalidate({ view: true, overlay: true });
+ }
+ } else {
+ current.input = snapInput(rawInput, current);
+ if (current.kind === 'freehand' && (rawInput.buttons & 1) !== 0) {
+ for (const input of batch) {
+ if (distance(input.screenPoint, current.lastSample) < 1) {
+ continue;
+ }
+ const from = current.points.at(-1)!;
+ const steps = Math.max(1, Math.ceil((distance(from, input.documentPoint) * ctx.viewport.getZoom()) / 2));
+ for (let step = 1; step <= steps; step += 1) {
+ const t = step / steps;
+ current.points.push({
+ x: from.x + (input.documentPoint.x - from.x) * t,
+ y: from.y + (input.documentPoint.y - from.y) * t,
+ });
+ }
+ current.lastSample = input.screenPoint;
+ }
+ }
+ }
+ requestPreview(ctx);
+ },
+ onPointerUp: (ctx, rawInput) => {
+ if (!isCurrent(ctx) || !session) {
+ return;
+ }
+ const current = session;
+ if (current.kind === 'polygon') {
+ if (current.finish !== undefined) {
+ commit(ctx, anchorsToBezierPoints(current.points), current.finish);
+ }
+ return;
+ }
+ if (current.kind === 'freehand') {
+ if (current.points.length < 2) {
+ reset(ctx);
+ return;
+ }
+ const zoom = ctx.viewport.getZoom();
+ const stabilized = getStrokePoints(current.points, {
+ size: 1 / zoom,
+ smoothing: 0.5,
+ streamline: 0.35,
+ thinning: 0,
+ simulatePressure: false,
+ last: true,
+ }).map(({ point }) => ({ x: point[0]!, y: point[1]! }));
+ commit(ctx, fitPolylineToBezierPoints(stabilized, Math.max(0.25, 2 / zoom)), false);
+ } else {
+ current.input = snapInput(rawInput, current);
+ const rect = dragRect(current);
+ if (rect.width <= 0 || rect.height <= 0) {
+ reset(ctx);
+ return;
+ }
+ commit(ctx, boxPoints(current.kind, rect), true);
+ }
+ },
+ };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/types.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/types.ts
index 4de906e532..c6c36b4af4 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/types.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/types.ts
@@ -44,6 +44,7 @@ export type ToolId =
| 'lasso'
| 'marquee'
| 'move'
+ | 'spline'
| 'transform'
| 'bbox'
| 'view'
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/vectorDefaults.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/vectorDefaults.ts
new file mode 100644
index 0000000000..c301a6d6bb
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/vectorDefaults.ts
@@ -0,0 +1,4 @@
+// Factories need these defaults without evaluating the runtime contract tables through the public facade.
+export const DEFAULT_VECTOR_GUIDE_COLOR = '#5aafff';
+export const DEFAULT_VECTOR_STROKE_COLOR = '#000000';
+export const DEFAULT_VECTOR_STROKE_WIDTH = 50;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/vectorEditState.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/vectorEditState.ts
new file mode 100644
index 0000000000..7b5f5d81c9
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/vectorEditState.ts
@@ -0,0 +1,20 @@
+import type { CanvasBezierPathContract } from './contracts';
+import type { LayerTransform } from './transform/transformMath';
+import type { Rect } from './types';
+
+export interface VectorPointRef {
+ pathId: string;
+ pointIndex: number;
+}
+
+/** Point-tool selection and in-flight gesture preview; completed edits are persisted immediately. */
+export interface VectorEditSession {
+ layerId: string;
+ paths: CanvasBezierPathContract[];
+ activePathId: string | null;
+ selectedPoints: VectorPointRef[];
+ canSplit: boolean;
+ canJoin: boolean;
+ pathTransform: { pathId: string; rect: Rect; transform: LayerTransform } | null;
+ selectionRect: Rect | null;
+}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/vectorRuntime.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/vectorRuntime.ts
new file mode 100644
index 0000000000..251bc8da1d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/vectorRuntime.ts
@@ -0,0 +1,24 @@
+import type { OverlayState } from './render/overlayRenderer';
+import type { RasterSurface } from './render/raster';
+
+import { VectorEditingController } from './controllers/vectorEditingController';
+import { traceVectorLayer } from './controllers/vectorTraceController';
+import { createVectorLayer, nextVectorLayerName } from './document/vectorLayerFactories';
+import { drawVectorEditOverlay } from './render/vectorEditOverlay';
+import { drawVectorGuides } from './render/vectorGuides';
+import { createVectorShapeTool } from './tools/vectorShapeTool';
+
+/** Per-engine vector state, instantiated only after its implementation has loaded. */
+export const createVectorRuntime = (options: ConstructorParameters<typeof VectorEditingController>[0]) => ({
+ editor: new VectorEditingController(options),
+ shape: createVectorShapeTool(),
+ createLayer: createVectorLayer,
+ nextLayerName: nextVectorLayerName,
+ trace: traceVectorLayer,
+ render: (ctx: RasterSurface['ctx'], state: OverlayState): void => {
+ drawVectorGuides(ctx, state.view, state.vectorGuides ?? [], state.vectorShapePreview ?? null);
+ drawVectorEditOverlay(ctx, state.view, state.vectorEdit ?? null);
+ },
+});
+
+export type VectorRuntime = ReturnType<typeof createVectorRuntime>;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/api.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/api.ts
index 7c5c88ed74..6a16a1863f 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/api.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/api.ts
@@ -57,9 +57,9 @@ export type {
SamSessionErrorCode,
SamSessionSnapshot,
} from './operationTypes';
+export { getCanvasEngine, isBlankCanvasDocument } from './engineRegistry';
export { getCanvasOperations } from './operationAccess';
export { IDLE_CONTROL_DETECTION_STATUS } from './controlDetectionStatusStore';
-export { getCanvasEngine, isBlankCanvasDocument } from './engineRegistry';
export {
recordCanvasMetadata,
resolveCanvasSaveBoardId,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.ts
index 46e68590a9..5e77c1efae 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.ts
@@ -31,7 +31,13 @@ import { describe, expect, it, vi } from 'vitest';
import type { EngineDeps, RegistryTimers } from './engineRegistry';
-import { createEngineRegistry, getCanvasEngine, getOrCreateEngine, isBlankCanvasDocument } from './engineRegistry';
+import {
+ createEngineRegistry,
+ getCanvasEngine,
+ getOrCreateEngine,
+ isBlankCanvasDocument,
+ releaseEngine,
+} from './engineRegistry';
import { TOOL_MEMORY_WRITE_DELAY_MS } from './toolMemory';
const createDeferred = <T>() => {
@@ -153,9 +159,13 @@ describe('createEngineRegistry', () => {
it('disposes the process registry synchronously when its account expires', () => {
accountLifecycle.activate('user-a');
const liveEngines = createLiveCanvasEngines();
+ expect(getCanvasEngine('shared-project-id')).toBeUndefined();
const engine = getOrCreateEngine('shared-project-id', { ...createFakeDeps(), liveEngines });
const dispose = vi.spyOn(engine.lifecycle, 'dispose');
+ expect(getCanvasEngine('shared-project-id')).toBe(engine);
expect(liveEngines.heldAssets('shared-project-id')).toEqual({ images: [], videos: [] });
+ releaseEngine('shared-project-id');
+ expect(getCanvasEngine('shared-project-id')).toBe(engine);
accountLifecycle.invalidate();
@@ -164,6 +174,17 @@ describe('createEngineRegistry', () => {
expect(dispose).toHaveBeenCalledOnce();
});
+ it('does not expose an isolated registry through the default engine lookup', () => {
+ const registry = createEngineRegistry();
+ try {
+ const engine = registry.getOrCreateEngine('isolated-project', createFakeDeps());
+ expect(registry.getEngine('isolated-project')).toBe(engine);
+ expect(getCanvasEngine('isolated-project')).toBeUndefined();
+ } finally {
+ registry.disposeAll();
+ }
+ });
+
it('keeps a released engine for its own Workbench but replaces it for a remounted one', () => {
const { flush, timers } = createFakeTimers();
const registry = createEngineRegistry({ timers });
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.ts
index ec9e4a76d6..e929ac0a42 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.ts
@@ -252,6 +252,6 @@ registerAccountOwnedResource({
export const getOrCreateEngine = defaultRegistry.getOrCreateEngine;
export const releaseEngine = defaultRegistry.releaseEngine;
-/** Non-owning public lookup. Engine construction and lease management stay inside Canvas composition. */
+/** Queries the default registry without constructing an engine or acquiring a lease. */
export const getCanvasEngine = (projectId: string): PublicCanvasEngine | undefined =>
defaultRegistry.getEngine(projectId);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/legacyCanvasMetadata.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/legacyCanvasMetadata.ts
index 4a31e1df5c..0729197cb7 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/legacyCanvasMetadata.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/legacyCanvasMetadata.ts
@@ -1,9 +1,5 @@
import type { AccountScope } from '@platform/state/accountLifecycle';
-import type {
- CanvasDocumentContractV3,
- CanvasLayerContract,
- CanvasLayerSourceContract,
-} from '@workbench/canvas-engine/api';
+import type { CanvasLayerContract, CanvasLayerSourceContract } from '@workbench/canvas-engine/api';
import { galleryImageUrls } from '@features/gallery/utility';
import { createItemId } from '@platform/browser/randomUuid';
@@ -709,7 +705,7 @@ export const convertLegacyCanvasMetadata = async (
}
}
// The current canvas loader below validates this wire projection before anything can commit.
- document.stacks[stack as keyof CanvasDocumentContractV3['stacks']].push(result as CanvasLayerContract);
+ document.stacks[stack].push(result as CanvasLayerContract);
} catch (error) {
assertAccountScopeCurrent(owner);
if (!isCurrent()) {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.test.ts
index 7aceda1c6c..ac66f7c4d4 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.test.ts
@@ -15,6 +15,35 @@ vi.mock('./engineRegistry', () => ({
import { createCanvasEngineResource, createImageResolver } from './useCanvasEngine';
+const resourceEngine = (hasVectors = false) => {
+ let status = 'idle';
+ const listeners = new Map<string, Set<() => void>>();
+ const publish = (key: string) => listeners.get(key)?.forEach((listener) => listener());
+ const setStatus = (value: string) => {
+ status = value;
+ publish('vectorToolsStatus');
+ };
+ const prepare = vi.fn(() => {
+ setStatus('loading');
+ return Promise.resolve(true);
+ });
+ const engine = {
+ projectId: 'project-a',
+ document: { getDocument: () => ({ stacks: { vector: hasVectors ? [{}] : [] } }) },
+ interaction: {
+ get: () => status,
+ subscribe: (key: string, listener: () => void) => {
+ const subscribers = listeners.get(key) ?? new Set<() => void>();
+ listeners.set(key, subscribers);
+ subscribers.add(listener);
+ return () => subscribers.delete(listener);
+ },
+ },
+ layers: { vectorEdit: { prepare } },
+ } as unknown as CanvasEngine;
+ return { engine, prepare, setStatus, listeners };
+};
+
describe('Canvas engine React resource', () => {
beforeEach(() => {
registry.acquire.mockReset();
@@ -22,7 +51,7 @@ describe('Canvas engine React resource', () => {
});
it('acquires only while subscribed and balances one lease across subscribers', () => {
- const engine = { projectId: 'project-a' } as CanvasEngine;
+ const { engine } = resourceEngine();
registry.acquire.mockReturnValue(engine);
const resource = createCanvasEngineResource('project-a', {} as never);
const firstListener = vi.fn();
@@ -47,7 +76,7 @@ describe('Canvas engine React resource', () => {
});
it('reacquires after the last subscriber releases the resource', () => {
- const engine = { projectId: 'project-a' } as CanvasEngine;
+ const { engine } = resourceEngine();
registry.acquire.mockReturnValue(engine);
const resource = createCanvasEngineResource('project-a', {} as never);
@@ -57,6 +86,33 @@ describe('Canvas engine React resource', () => {
expect(registry.acquire).toHaveBeenCalledTimes(2);
expect(registry.release).toHaveBeenCalledTimes(2);
});
+ it('holds a persisted vector document until its tools are ready and removes subscriptions on release', () => {
+ const { engine, prepare, setStatus, listeners } = resourceEngine(true);
+ registry.acquire.mockReturnValue(engine);
+ const resource = createCanvasEngineResource('project-a', {} as never);
+ const changed = vi.fn();
+ const release = resource.subscribe(changed);
+ expect(prepare).toHaveBeenCalledOnce();
+ expect(resource.getSnapshot()).toBeNull();
+ setStatus('ready');
+ expect(resource.getSnapshot()).toBe(engine);
+ expect(changed).toHaveBeenCalled();
+ release();
+ expect([...listeners.values()].every((set) => set.size === 0)).toBe(true);
+ changed.mockClear();
+ setStatus('loading');
+ expect(changed).not.toHaveBeenCalled();
+ });
+
+ it('leaves raster documents usable without requesting vector support', () => {
+ const { engine, prepare } = resourceEngine();
+ registry.acquire.mockReturnValue(engine);
+ const resource = createCanvasEngineResource('project-a', {} as never);
+ const release = resource.subscribe(() => undefined);
+ expect(resource.getSnapshot()).toBe(engine);
+ expect(prepare).not.toHaveBeenCalled();
+ release();
+ });
});
describe('Canvas image resolver', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.ts
index e6b68daa85..e780b0cb56 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.ts
@@ -55,18 +55,37 @@ export const createImageResolver = (): ImageResolver => async (imageName, signal
export const createCanvasEngineResource = (projectId: string, deps: EngineDeps): CanvasEngineResource => {
let engine: CanvasEngine | null = null;
const listeners = new Set<() => void>();
-
+ let unsubscribeVectorState: (() => void) | null = null;
+ let unsubscribeDocument: (() => void) | null = null;
+ const publish = () => {
+ if (
+ engine?.document.getDocument()?.stacks.vector?.length &&
+ engine.interaction.get('vectorToolsStatus') === 'idle'
+ ) {
+ void engine.layers.vectorEdit.prepare();
+ return;
+ }
+ for (const listener of listeners) {
+ listener();
+ }
+ };
return {
- getSnapshot: () => engine,
+ getSnapshot: () => (engine?.interaction.get('vectorToolsStatus') === 'loading' ? null : engine),
subscribe: (listener) => {
listeners.add(listener);
if (listeners.size === 1) {
engine = getOrCreateEngine(projectId, deps);
- listener();
+ unsubscribeVectorState = engine.interaction.subscribe('vectorToolsStatus', publish);
+ unsubscribeDocument = engine.interaction.subscribe('documentEpoch', publish);
+ publish();
}
return () => {
listeners.delete(listener);
if (listeners.size === 0 && engine) {
+ unsubscribeVectorState?.();
+ unsubscribeDocument?.();
+ unsubscribeVectorState = null;
+ unsubscribeDocument = null;
engine = null;
releaseEngine(projectId);
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvasMigration.test.ts b/invokeai/frontend/webv2/src/workbench/canvasMigration.test.ts
index bced404d20..6ac56c54e2 100644
--- a/invokeai/frontend/webv2/src/workbench/canvasMigration.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvasMigration.test.ts
@@ -1,6 +1,6 @@
import type { CanvasStateContractV3 } from '@workbench/canvas-engine/api';
-import { createControlLayer } from '@workbench/canvas-engine/api';
+import { createControlLayer, createVectorLayer } from '@workbench/canvas-engine/api';
import { groupContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
import { describe, expect, it } from 'vitest';
@@ -1295,3 +1295,54 @@ describe('loadCanvasState ingress repair', () => {
expect(loaded.stagingArea).toEqual({ ...state.stagingArea, isVisible: false });
});
});
+
+describe('vector layer appearance persistence', () => {
+ it('round-trips independent layer appearance in the live document and snapshots with schema 7', () => {
+ const first = {
+ ...createVectorLayer({ id: 'a', name: 'A' }),
+ strokeColor: '#123456',
+ strokeWidth: 17,
+ fillColor: '#abcdef',
+ fillEnabled: true,
+ traceTaperEnds: true,
+ traceTaper: 240,
+ };
+ const second = {
+ ...createVectorLayer({ id: 'b', name: 'B' }),
+ strokeColor: '#ff0000',
+ strokeWidth: 3,
+ fillColor: '#00ff00',
+ strokeEnabled: false,
+ };
+ const state = createEmptyCanvasState();
+ const document = { ...state.document, stacks: stacksFrom([first, second]) };
+ const saved = load({ ...state, document, snapshots: [{ id: 'saved', name: 'Saved', createdAt: 'now', document }] });
+ expect(saved.version).toBe(7);
+ expect(saved.document.version).toBe(7);
+ expect(saved.snapshots[0]?.document.version).toBe(7);
+ const reopened = load(JSON.parse(JSON.stringify(saved)));
+ expect(reopened).toEqual(saved);
+ expect(reopened.document.stacks.vector).toEqual([first, second]);
+ expect(reopened.snapshots[0]?.document.stacks.vector).toEqual([first, second]);
+ // A snapshot alone raises the live canvas floor so an older writer cannot drop its appearance.
+ expect(load({ ...state, snapshots: saved.snapshots }).version).toBe(7);
+ expect(writableCanvasSchemaVersion([7], { stacks: stacksFrom([]) })).toBe(7);
+ expect(writableCanvasSchemaVersion([7], { stacks: { ...stacksFrom([]), vector: [] } })).toBe(7);
+ });
+
+ it.each([
+ { strokeColor: undefined },
+ { strokeWidth: undefined },
+ { strokeColor: 'not a color' },
+ { strokeWidth: -3 },
+ { strokeWidth: 601 },
+ { strokeWidth: 1.5 },
+ ])('refuses vector layers with missing or invalid stroke appearance: %j', (appearance) => {
+ const vector = { ...createVectorLayer({ id: 'v', name: 'Vector' }), ...appearance };
+ const state = createEmptyCanvasState();
+ expect(
+ refusal({ ...state, document: { ...state.document, stacks: { ...state.document.stacks, vector: [vector] } } })
+ .status
+ ).toBe('invalid');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvasMigration.ts b/invokeai/frontend/webv2/src/workbench/canvasMigration.ts
index 189b5ce96b..76b1a5a6f3 100644
--- a/invokeai/frontend/webv2/src/workbench/canvasMigration.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvasMigration.ts
@@ -250,6 +250,41 @@ const zLayerBase = z.object({
transform: zTransform,
});
const zCanvasLayer = z.discriminatedUnion('type', [
+ zLayerBase.extend({
+ isHidden: z.boolean().optional(),
+ paths: z.array(
+ z.object({
+ id: z.string(),
+ name: z.string().nullable(),
+ isClosed: z.boolean(),
+ points: z.array(
+ z.object({
+ anchor: zCoordinate,
+ inHandle: zCoordinate.nullable(),
+ outHandle: zCoordinate.nullable(),
+ type: z.enum(['corner', 'smooth', 'symmetric']),
+ })
+ ),
+ })
+ ),
+ type: z.literal('vector'),
+ guideColor: z
+ .string()
+ .regex(/^#[0-9a-f]{6}([0-9a-f]{2})?$/i)
+ .optional()
+ .catch(undefined),
+ fillColor: z
+ .string()
+ .regex(/^#[0-9a-f]{6}([0-9a-f]{2})?$/i)
+ .optional()
+ .catch(undefined),
+ fillEnabled: z.boolean().optional().catch(undefined),
+ strokeColor: z.string().regex(/^#[0-9a-f]{6}([0-9a-f]{2})?$/i),
+ strokeWidth: z.number().int().min(1).max(600),
+ strokeEnabled: z.boolean().optional().catch(undefined),
+ traceTaperEnds: z.boolean().optional().catch(undefined),
+ traceTaper: z.number().int().min(1).max(500).optional().catch(undefined),
+ }),
zLayerBase.extend({
// A pre-stack adjustments OBJECT is dropped rather than failing the document.
adjustments: zAdjustments.optional().catch(undefined),
@@ -447,7 +482,7 @@ const ownSchemaRequirement = (node: Record<string, unknown>): CanvasSchemaVersio
/**
* The newest schema a node or any descendant needs. v4: custom-font typography. v5: a noise or spatial adjustment,
- * enabled or not, which a v4 reader would drop. v6: a control layer carrying any derivation field.
+ * enabled or not, which a v4 reader would drop. v6: control derivation fields.
*/
const nodeSchemaRequirement = (node: unknown): CanvasSchemaVersion => {
if (!isRecord(node)) {
@@ -474,6 +509,9 @@ export const writableCanvasSchemaVersion = (
document: Pick<CanvasDocumentContractV3, 'stacks'>
): CanvasSchemaVersion => {
let version = newestCanvasSchemaVersion(declaredVersions);
+ if (document.stacks.vector !== undefined) {
+ version = Math.max(version, 7) as CanvasSchemaVersion;
+ }
for (const roots of Object.values(document.stacks)) {
for (const root of roots) {
if (version === MAX_SUPPORTED_CANVAS_SCHEMA_VERSION) {
@@ -717,6 +755,9 @@ const parseStacks = (value: unknown, path: string): ParsedStacks => {
}
}
for (const stack of LAYER_STACK_ORDER) {
+ if (stack === 'vector' && value.vector === undefined) {
+ continue;
+ }
const roots = value[stack] === undefined ? [] : value[stack];
if (!Array.isArray(roots)) {
context.diagnostics.push({ message: `${stack} stack is not an array`, path: `${path}.${stack}` });
diff --git a/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.test.ts b/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.test.ts
index 6ecb01d88e..5b809a3222 100644
--- a/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.test.ts
@@ -64,7 +64,7 @@ const getLayer = (
const getPaintSource = (
layer: CanvasLayerContract | undefined
): Extract<CanvasLayerSourceContract, { type: 'paint' }> | null => {
- if (!layer) {
+ if (!layer || layer.type === 'vector') {
return null;
}
if (layer.type === 'raster' || layer.type === 'control') {
diff --git a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts
index 56cf6c492b..80c3156aa7 100644
--- a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts
@@ -322,7 +322,7 @@ const replaceLeaf = (
const stacks = removeNodes(document.stacks, new Set([layer.id]));
return withStacks(
document,
- anchor ? insertNodesAtAnchor(stacks, anchor, [layer]) : { ...stacks, [target]: [layer, ...stacks[target]] }
+ anchor ? insertNodesAtAnchor(stacks, anchor, [layer]) : { ...stacks, [target]: [layer, ...(stacks[target] ?? [])] }
);
};
@@ -473,7 +473,7 @@ const applyMoves = (stacks: CanvasStackForests, moves: readonly CanvasNodeMove[]
};
const next = { ...removed };
for (const stack of Object.keys(next) as CanvasNodeInsertionAnchor['stack'][]) {
- const roots = materialize(lists.get(siblingKey(stack, null)) ?? removed[stack], stack);
+ const roots = materialize(lists.get(siblingKey(stack, null)) ?? removed[stack] ?? [], stack);
if (roots !== removed[stack]) {
next[stack] = [...roots];
}
@@ -631,6 +631,20 @@ const patchLayerConfig = (layer: CanvasNodeContract, config: CanvasLayerConfigPa
if (layer.type !== config.layerType) {
return layer;
}
+ if (layer.type === 'vector' && config.layerType === 'vector') {
+ return {
+ ...layer,
+ ...(Object.hasOwn(config, 'paths') ? { paths: config.paths ?? layer.paths } : {}),
+ ...(Object.hasOwn(config, 'guideColor') ? { guideColor: config.guideColor } : {}),
+ ...(Object.hasOwn(config, 'fillEnabled') ? { fillEnabled: config.fillEnabled } : {}),
+ ...(Object.hasOwn(config, 'strokeEnabled') ? { strokeEnabled: config.strokeEnabled } : {}),
+ ...(Object.hasOwn(config, 'fillColor') ? { fillColor: config.fillColor } : {}),
+ ...(config.strokeColor !== undefined ? { strokeColor: config.strokeColor } : {}),
+ ...(config.strokeWidth !== undefined ? { strokeWidth: config.strokeWidth } : {}),
+ ...(Object.hasOwn(config, 'traceTaperEnds') ? { traceTaperEnds: config.traceTaperEnds } : {}),
+ ...(Object.hasOwn(config, 'traceTaper') ? { traceTaper: config.traceTaper } : {}),
+ };
+ }
if (layer.type === 'group' && config.layerType === 'group') {
return {
...layer,
diff --git a/invokeai/frontend/webv2/src/workbench/canvasSchemaVersion.test.ts b/invokeai/frontend/webv2/src/workbench/canvasSchemaVersion.test.ts
index b6f7c234d1..29a4f59f5c 100644
--- a/invokeai/frontend/webv2/src/workbench/canvasSchemaVersion.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvasSchemaVersion.test.ts
@@ -21,7 +21,15 @@ describe('getProjectCanvasSchemaRequirement', () => {
});
describe('isCanvasSchemaVersionSupported', () => {
- it('opens projects needing schema 3 through 6, including control-layer derivation, and refuses the rest', () => {
- expect([2, 3, 4, 5, 6, 7].map(isCanvasSchemaVersionSupported)).toEqual([false, true, true, true, true, false]);
+ it('opens projects needing schema 3 through 7, including control-layer derivation, and refuses the rest', () => {
+ expect([2, 3, 4, 5, 6, 7, 8].map(isCanvasSchemaVersionSupported)).toEqual([
+ false,
+ true,
+ true,
+ true,
+ true,
+ true,
+ false,
+ ]);
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvasSchemaVersion.ts b/invokeai/frontend/webv2/src/workbench/canvasSchemaVersion.ts
index c9017c6fdb..92f9cb37c8 100644
--- a/invokeai/frontend/webv2/src/workbench/canvasSchemaVersion.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvasSchemaVersion.ts
@@ -5,9 +5,9 @@ export const MIN_SUPPORTED_CANVAS_SCHEMA_VERSION = 3;
* Newest canvas document schema this build can safely read, edit, and write. A document adopts a newer schema only
* when it carries something older builds would drop on load and then lose on save: 4 for custom-font typography, 5
* for noise, clarity, texture or dehaze adjustments, 6 for control-layer derivation fields (`controlType`,
- * `detection`, `original`, `originalTransform`). Older builds refuse the newer schema instead.
+ * `detection`, `original`, `originalTransform`), 7 for vector layers with their geometry and appearance. Older builds refuse the newer schema instead.
*/
-export const MAX_SUPPORTED_CANVAS_SCHEMA_VERSION = 6;
+export const MAX_SUPPORTED_CANVAS_SCHEMA_VERSION = 7;
/** Whether a project whose documents need at least `minimumCanvasSchemaVersion` can be opened here. */
export const isCanvasSchemaVersionSupported = (minimumCanvasSchemaVersion: number): boolean =>
diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts
index f73a5484a5..444956d53c 100644
--- a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts
+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts
@@ -194,6 +194,7 @@ export const firstPartyHotkeyCatalog: HotkeyDefinition[] = [
hotkey('canvas', 'tool.lasso', ['l'], { title: 'Select Lasso Tool' }),
hotkey('canvas', 'tool.marquee', ['m'], { title: 'Select Marquee Tool' }),
hotkey('canvas', 'tool.shape', ['u'], { title: 'Select Shape Tool' }),
+ hotkey('canvas', 'tool.spline', ['s'], { title: 'Select Spline Edit Tool' }),
hotkey('canvas', 'tool.text', ['t'], { title: 'Select Text Tool' }),
hotkey('canvas', 'tool.gradient', ['g'], { title: 'Select Gradient Tool' }),
hotkey('canvas', 'tool.colorPicker', ['i'], { title: 'Select Color Picker' }),
diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/keys.test.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/keys.test.ts
index 4dc2125883..030e54bb6b 100644
--- a/invokeai/frontend/webv2/src/workbench/hotkeys/keys.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/keys.test.ts
@@ -84,7 +84,9 @@ describe('hotkey keys', () => {
acceptsHotkeyPress(withAltGr({ altKey: true, code: 'Enter', ctrlKey: true, key: 'Enter' }), 'alt+mod+enter')
).toBe(true);
expect(acceptsHotkeyPress(withAltGr({ altKey: true, code: 'Digit1', key: '1' }), 'alt+1')).toBe(true);
- expect(isHotkeyPress(withAltGr({ altKey: true, code: 'Digit1', key: '1' }), 'alt+1')).toBe(true);
+ expect(isHotkeyPress(withAltGr({ altKey: true, code: 'Digit1', key: '1' }), 'alt+1')).toBe(
+ navigator.platform !== 'Win32'
+ );
// AltGr+N types ń: not Cmd/Ctrl+Alt+N by position.
expect(isHotkeyPress(withAltGr({ altKey: true, code: 'KeyN', key: 'ń', metaKey: true }), 'meta+alt+n')).toBe(false);
});
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/canvasRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/canvasRecall.ts
index 6d9c6e612c..03a32652a4 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/canvasRecall.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/canvasRecall.ts
@@ -130,7 +130,7 @@ const sourceNames = (layer: CanvasLayerContract): string[] => {
if (layer.source.type === 'paint' && layer.source.bitmap) {
names.push(layer.source.bitmap.imageName);
}
- } else if (layer.mask.bitmap) {
+ } else if ((layer.type === 'inpaint_mask' || layer.type === 'regional_guidance') && layer.mask.bitmap) {
names.push(layer.mask.bitmap.imageName);
}
if (layer.type === 'control' && layer.original) {
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/mediaUsage.ts b/invokeai/frontend/webv2/src/workbench/image-actions/mediaUsage.ts
index 3630430055..98c301f2fe 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/mediaUsage.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/mediaUsage.ts
@@ -28,7 +28,8 @@ export interface MediaUsage {
refs: GalleryItemRef[];
}
-type StackKind = keyof Project['canvas']['document']['stacks'];
+// Vector guides have no raster sources or media references.
+type StackKind = Exclude<keyof Project['canvas']['document']['stacks'], 'vector'>;
/** The canvas layer stacks, each its own surface; a new stack kind fails to compile until it has one. */
const STACK_SURFACES = {
diff --git a/invokeai/frontend/webv2/src/workbench/palette/docsSearchIndex.json b/invokeai/frontend/webv2/src/workbench/palette/docsSearchIndex.json
index 9eac010784..c3c83e738c 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/docsSearchIndex.json
+++ b/invokeai/frontend/webv2/src/workbench/palette/docsSearchIndex.json
@@ -11,7 +11,7 @@
{"s":"start-here/manual","t":"Manual Installation","c":0,"h":[["are-you-in-the-right-place","Are you in the right place?"],["your-setup","Your setup"],["walkthrough","Walkthrough"]]},
{"s":"start-here/system-requirements","t":"Hardware Requirements","c":0,"h":[["hardware","Hardware"],["windowslinux","Windows/Linux"],["python","Python"],["drivers","Drivers"],["intel","Intel"],["nvidia","Nvidia"],["amd","AMD"]]},
{"s":"start-here/upgrading","t":"Upgrading to v7","c":0,"h":[["the-upgrade-is-one-way","The upgrade is one-way"],["backups","Backups"],["which-backup-to-restore","Which backup to restore"],["mysql-and-mariadb","MySQL and MariaDB"],["restore-a-backup","Restore a backup"],["switch-back-to-the-v7-database","Switch back to the v7 database"],["run-v7-alongside-v6","Run v7 alongside v6"]]},
-{"s":"users-guide/canvas/canvas-guide","t":"Canvas guide","d":"A detailed guide to the Canvas — its tools and their options, navigation, the header buttons, the generation frame, selections, transform, filters, the staging area, menus, settings and keyboard shortcuts.","c":1,"h":[["tools","Tools"],["tool-options","Tool options"],["fonts","Fonts"],["navigating-the-canvas","Navigating the canvas"],["the-header","The header"],["the-generation-frame","The generation frame"],["what-the-model-sees","What the model sees"],["frame-size-and-processing-size","Frame size and processing size"],["transforming-layers","Transforming layers"],["filters-and-object-selection","Filters and object selection"],["running-a-workflow-on-a-layer","Running a workflow on a layer"],["the-staging-area","The staging area"],["the-canvas-menu","The canvas menu"],["canvas-settings","Canvas settings"],["saving-and-sharing-a-canvas","Saving and sharing a canvas"],["copying-and-pasting","Copying and pasting"],["keyboard-shortcuts","Keyboard shortcuts"]]},
+{"s":"users-guide/canvas/canvas-guide","t":"Canvas guide","d":"A detailed guide to the Canvas — its tools and their options, navigation, the header buttons, the generation frame, selections, transform, filters, the staging area, menus, settings and keyboard shortcuts.","c":1,"h":[["tools","Tools"],["tool-options","Tool options"],["vector-layers-and-splines","Vector layers and splines"],["fonts","Fonts"],["navigating-the-canvas","Navigating the canvas"],["the-header","The header"],["the-generation-frame","The generation frame"],["what-the-model-sees","What the model sees"],["frame-size-and-processing-size","Frame size and processing size"],["transforming-layers","Transforming layers"],["filters-and-object-selection","Filters and object selection"],["running-a-workflow-on-a-layer","Running a workflow on a layer"],["the-staging-area","The staging area"],["the-canvas-menu","The canvas menu"],["canvas-settings","Canvas settings"],["saving-and-sharing-a-canvas","Saving and sharing a canvas"],["copying-and-pasting","Copying and pasting"],["keyboard-shortcuts","Keyboard shortcuts"]]},
{"s":"users-guide/canvas/introduction","t":"Crafting images with the Canvas","d":"An introduction to the Canvas — layers and masks, sending generations to the Canvas, inpainting, outpainting, regional prompts, control layers, drawing and adding gallery images.","c":1,"h":[["canvas-concepts","Canvas concepts"],["layers","Layers"],["settings-live-in-the-properties-pane","Settings live in the Properties pane"],["the-generation-frame","The generation frame"],["what-invoke-does","What Invoke does"],["sending-generations-to-the-canvas","Sending generations to the Canvas"],["inpainting","Inpainting"],["outpainting","Outpainting"],["regional-prompts-and-reference-images","Regional prompts and reference images"],["control-layers","Control layers"],["drawing-on-a-raster-layer","Drawing on a raster layer"],["adding-a-gallery-image-to-a-layer","Adding a gallery image to a layer"]]},
{"s":"users-guide/canvas/layers-panel","t":"Layers panel guide","d":"A detailed guide to the Canvas Layers panel — the color picker, managing layers, history, the layer menu, and every layer type's settings in the Properties pane.","c":1,"h":[["color","Color"],["layers","Layers"],["the-layer-list","The layer list"],["working-with-layers","Working with layers"],["history","History"],["the-layer-menu","The layer menu"],["properties","Properties"],["raster-layer","Raster layer"],["control-layer","Control layer"],["inpaint-mask","Inpaint mask"],["regional-guidance","Regional guidance"],["regional-reference-image","Regional reference image"],["transform-and-overview","Transform and Overview"],["keyboard-shortcuts","Keyboard shortcuts"]]},
{"s":"users-guide/gallery/gallery-reference","t":"Gallery Reference","d":"Details of the Gallery — the board menu, archiving, downloading and deleting boards, the media menu, Gallery settings and keyboard shortcuts.","c":1,"h":[["managing-boards","Managing boards"],["the-board-menu","The board menu"],["archiving-a-board","Archiving a board"],["downloading-a-board","Downloading a board"],["deleting-a-board","Deleting a board"],["the-media-menu","The media menu"],["gallery-settings","Gallery settings"],["keyboard-shortcuts","Keyboard shortcuts"]]},
diff --git a/invokeai/frontend/webv2/src/workbench/projects/README.md b/invokeai/frontend/webv2/src/workbench/projects/README.md
index 406d745473..fcf52808df 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/README.md
+++ b/invokeai/frontend/webv2/src/workbench/projects/README.md
@@ -99,6 +99,8 @@ Cold-start offline editing not supported. When backend cannot load, unavailable
## Additive canvas values
+The optional `canvas.document.stacks.vector` forest requires Canvas schema 7, even when empty after its last layer is removed. Vector layers retain their Bezier paths and layer-owned appearance in the document and snapshots without image assets. Stroke color and width are required; new layers use black strokes at 50 pixels. A document that has never used vectors omits that forest, preserving its existing compatibility floor. Schema adoption is sticky; older clients refuse schema 7 instead of dropping vector data.
+
New value in a closed canvas set, such as a control layer's adapter kind (`anima_lllite`), is added without raising canvas schema version or project's compatibility floor. Builds that know the value load and save it unchanged; builds that do not refuse the canvas instead of rewriting it, since coercing an unknown kind to a known one would replace the user's adapter on next autosave. In an older build the project is not opened and user sees that it "contains canvas data this version of Invoke cannot read"; saved copy is untouched and exportable, and a build that knows the value opens it as saved. Raise schema version instead when older builds could misread a document without refusing it.
Adjustment stacks are such a case: load drops a stack holding any entry it cannot parse, so an older build would load a document with a new adjustment type minus that layer's whole stack and autosave the loss. A new adjustment type therefore raises the canvas schema for documents that use it. A noise, clarity, texture or dehaze adjustment, enabled or not, on any layer or group at any depth of the live document or a saved snapshot, makes the canvas schema at least 5 (`canvasMigration.ts`, `writableCanvasSchemaVersion`); control-layer derivation fields raise it to 6 (see [Control layer derivation](#control-layer-derivation)). A document with neither keeps its version. Adoption is sticky: removing the last such entry leaves the document at its adopted schema, matching the server's monotonic floor. A build whose maximum is lower refuses the project at the server and the canvas at load as an unsupported version.
diff --git a/invokeai/frontend/webv2/src/workbench/projects/api.test.ts b/invokeai/frontend/webv2/src/workbench/projects/api.test.ts
index 0f47e52597..4e71d0ecc1 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/api.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/api.test.ts
@@ -51,7 +51,7 @@ describe('getProjectWithinSize', () => {
);
await expect(getProjectWithinSize('p-1', 1000)).resolves.toEqual(record);
expect(transport.apiFetch).toHaveBeenCalledWith(
- '/api/v1/projects/p-1?max_canvas_schema_version=6&max_document_schema_version=4',
+ '/api/v1/projects/p-1?max_canvas_schema_version=7&max_document_schema_version=4',
{ signal: undefined }
);
@@ -116,7 +116,7 @@ describe('createProjectSettled', () => {
const post = () => ({
body: JSON.stringify({
...request,
- max_canvas_schema_version: 6,
+ max_canvas_schema_version: 7,
max_document_schema_version: 4,
minimum_canvas_schema_version: 3,
}),
@@ -167,7 +167,7 @@ describe('createProjectSettled', () => {
expect(transport.apiFetchJson).toHaveBeenNthCalledWith(2, '/api/v1/projects/', post());
expect(transport.apiFetchJson).toHaveBeenNthCalledWith(
3,
- '/api/v1/projects/project-1?max_canvas_schema_version=6&max_document_schema_version=4',
+ '/api/v1/projects/project-1?max_canvas_schema_version=7&max_document_schema_version=4',
expect.anything()
);
});
@@ -247,7 +247,7 @@ describe('createProjectSettled', () => {
await expect(createProjectSettled(request, captureAccountScope())).resolves.toMatchObject(project);
expect(transport.apiFetchJson).toHaveBeenNthCalledWith(
3,
- '/api/v1/projects/project-1?max_canvas_schema_version=6&max_document_schema_version=4',
+ '/api/v1/projects/project-1?max_canvas_schema_version=7&max_document_schema_version=4',
expect.anything()
);
@@ -339,7 +339,7 @@ describe('canvas schema compatibility declarations', () => {
await getProject('project/one');
expect(transport.apiFetchJson).toHaveBeenCalledWith(
- '/api/v1/projects/project%2Fone?max_canvas_schema_version=6&max_document_schema_version=4',
+ '/api/v1/projects/project%2Fone?max_canvas_schema_version=7&max_document_schema_version=4',
{ signal: expect.any(AbortSignal) }
);
});
@@ -354,7 +354,7 @@ describe('canvas schema compatibility declarations', () => {
data: {},
minimum_document_schema_version: 4,
name: 'Project',
- max_canvas_schema_version: 6,
+ max_canvas_schema_version: 7,
max_document_schema_version: 4,
minimum_canvas_schema_version: 3,
}),
@@ -379,7 +379,7 @@ describe('canvas schema compatibility declarations', () => {
expected_revision: 4,
minimum_canvas_schema_version: 3,
name: 'Project',
- max_canvas_schema_version: 6,
+ max_canvas_schema_version: 7,
max_document_schema_version: 4,
}),
method: 'PUT',
@@ -590,7 +590,7 @@ describe('project workspaces', () => {
body: JSON.stringify({
data: { layout: {} },
expected_revision: 1,
- max_canvas_schema_version: 6,
+ max_canvas_schema_version: 7,
max_document_schema_version: 4,
}),
method: 'PUT',
@@ -618,7 +618,7 @@ describe('project workspaces', () => {
minimum_document_schema_version: 4,
name: 'Project',
workspace,
- max_canvas_schema_version: 6,
+ max_canvas_schema_version: 7,
max_document_schema_version: 4,
}),
method: 'PUT',
@@ -664,7 +664,7 @@ describe('project workspaces', () => {
minimum_document_schema_version: 4,
name: 'Project',
workspace: { layout: {} },
- max_canvas_schema_version: 6,
+ max_canvas_schema_version: 7,
max_document_schema_version: 4,
minimum_canvas_schema_version: 3,
}),
diff --git a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts
index 5e79148b9c..0c03b23424 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts
@@ -256,6 +256,14 @@ const createService = (
});
beforeEach(() => {
+ // These tests own their persistence API. Unrelated lifecycle reads must not open real HTTP sockets.
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(() => Promise.reject(new TypeError('Network unavailable in persistence unit test')))
+ );
+ onTestFinished(() => {
+ vi.unstubAllGlobals();
+ });
accountLifecycle.activate('durable-sync-test');
vi.mocked(acquireProjectMutationLock).mockReset();
vi.mocked(acquireProjectMutationLock).mockResolvedValue({
diff --git a/invokeai/frontend/webv2/src/workbench/settings/HotkeysSettingsSection.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/settings/HotkeysSettingsSection.browser.test.tsx
index d59c5a0ef0..a7de3d2d1d 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/HotkeysSettingsSection.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/settings/HotkeysSettingsSection.browser.test.tsx
@@ -67,7 +67,8 @@ describe('HotkeysSettingsSection conflicts', () => {
// widget types; a Canvas binding on the same key meets neither.
it('flags a binding that shares its key with a multi-widget shortcut on any of that shortcut’s widgets', async () => {
await patchWorkbenchPreferences({
- customHotkeys: { 'canvas.tool.brush': ['s'], 'gallery.toggleStarredOnly': ['s'] },
+ // Free S within Canvas so this fixture tests only cross-widget overlap with Recall Seed.
+ customHotkeys: { 'canvas.tool.brush': ['s'], 'canvas.tool.spline': [], 'gallery.toggleStarredOnly': ['s'] },
});
await render();
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurfaceContextLayout.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurfaceContextLayout.tsx
index 7269227ffa..5ceb2e46c3 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurfaceContextLayout.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurfaceContextLayout.tsx
@@ -1,5 +1,5 @@
import type { BoxProps } from '@chakra-ui/react';
-import type { MouseEventHandler, ReactNode } from 'react';
+import type { KeyboardEventHandler, MouseEventHandler, ReactNode } from 'react';
import { Box } from '@chakra-ui/react';
@@ -11,14 +11,21 @@ const CANVAS_SURFACE_LAYER_LAYOUT = {
export const CanvasSurfaceContextLayout = ({
children,
onContextMenu,
+ onKeyDown,
surface,
}: {
children: ReactNode;
onContextMenu: MouseEventHandler<HTMLDivElement>;
+ onKeyDown?: KeyboardEventHandler<HTMLDivElement>;
surface: ReactNode;
}) => (
<>
- <Box {...CANVAS_SURFACE_LAYER_LAYOUT} data-canvas-context-menu-owner="" onContextMenu={onContextMenu}>
+ <Box
+ {...CANVAS_SURFACE_LAYER_LAYOUT}
+ data-canvas-context-menu-owner=""
+ onContextMenu={onContextMenu}
+ onKeyDown={onKeyDown}
+ >
{surface}
</Box>
{children}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.browser.test.tsx
index 580b845170..62d9bebbed 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.browser.test.tsx
@@ -21,7 +21,7 @@ import { auditAccessibility } from '@platform/browser/auditAccessibility.testing
import { TINY_PNG_BASE64 } from '@platform/browser/nativeDrag.testing';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { system } from '@theme/system';
-import { createControlLayer } from '@workbench/canvas-engine/api';
+import { createControlLayer, createVectorLayer } from '@workbench/canvas-engine/api';
import { layerContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
import { createDomRasterBackend } from '@workbench/canvas-engine/render/raster';
import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';
@@ -113,7 +113,13 @@ vi.mock('./useCreateFromBbox', () => ({
useCreateFromBbox: () => ({ createFromBbox: () => undefined, isCreating: false }),
}));
vi.mock('./CanvasCreateFromBboxSubmenu', () => ({ CanvasCreateFromBboxSubmenu: () => null }));
-vi.mock('./CanvasGlobalContextMenu', () => ({ CanvasGlobalContextMenu: () => null }));
+vi.mock('./CanvasGlobalContextMenu', () => ({
+ CanvasGlobalContextMenu: () => (
+ <div aria-label="Canvas fallback" role="menu">
+ Canvas actions
+ </div>
+ ),
+}));
vi.mock('./CanvasSaveToGallerySubmenu', () => ({ CanvasSaveToGallerySubmenu: () => null }));
vi.mock('./CanvasSurface', () => ({ CanvasSurface: () => null }));
vi.mock('./MissingFontsDialog', () => ({ MissingFontsDialog: () => null }));
@@ -256,6 +262,148 @@ const renderView = async (
return { commandHandlers, projectId, store };
};
+describe('Canvas spline context menu', () => {
+ const renderSpline = async (selectPath = true) => {
+ const layer = createVectorLayer({ id: 'vector', name: 'Guides' });
+ layer.paths = [
+ {
+ id: 'selected-path',
+ name: null,
+ isClosed: false,
+ points: [
+ { anchor: { x: 300, y: 300 }, inHandle: null, outHandle: null, type: 'corner' },
+ { anchor: { x: 400, y: 300 }, inHandle: null, outHandle: null, type: 'corner' },
+ ],
+ },
+ {
+ id: 'other-path',
+ name: null,
+ isClosed: false,
+ points: [
+ { anchor: { x: 700, y: 450 }, inHandle: null, outHandle: null, type: 'corner' },
+ { anchor: { x: 800, y: 450 }, inHandle: null, outHandle: null, type: 'corner' },
+ ],
+ },
+ ];
+ await renderView('completed', {
+ selectedLayer: layer,
+ staged: false,
+ });
+ await act(async () => {
+ await harness.engine!.layers.vectorEdit.prepare();
+ });
+ await act(() => {
+ harness.engine!.tools.setTool('spline');
+ if (selectPath) {
+ expect(harness.engine!.layers.vectorEdit.targetContextMenu({ x: 350, y: 300 })).toBe(true);
+ }
+ });
+ const owner = host!.querySelector<HTMLDivElement>('[data-canvas-context-menu-owner]')!;
+ owner.tabIndex = -1;
+ owner.focus();
+ return { engine: harness.engine!, owner };
+ };
+
+ it.each(['{Shift>}{F10}{/Shift}', '{ContextMenu}'])(
+ 'opens the active path away from the corner with %s and executes an action with keys',
+ async (keys) => {
+ const { engine, owner } = await renderSpline();
+ await act(() => userEvent.keyboard(keys));
+ await expect.element(page.getByRole('menuitem', { name: 'Trace Path', exact: true })).toBeVisible();
+ expect(engine.interaction.get('vectorEditSession')?.activePathId).toBe('selected-path');
+ await act(() => userEvent.keyboard('{Escape}'));
+ await vi.waitFor(() => expect(document.activeElement).toBe(owner));
+ await act(() => userEvent.keyboard(keys));
+ await expect.element(page.getByRole('menuitem', { name: 'Trace Path', exact: true })).toBeVisible();
+ // Copy Path is immediately before Delete Path; navigate the actual menu without a pointer.
+ await userEvent.keyboard('{End}{ArrowUp}');
+ await expect
+ .element(page.getByRole('menuitem', { name: 'Copy Path', exact: true }))
+ .toHaveAttribute('data-highlighted');
+ await act(() => userEvent.keyboard('{Enter}'));
+ await vi.waitFor(() => expect(engine.interaction.get('vectorEditSession')?.paths).toHaveLength(3));
+ expect(engine.interaction.get('vectorEditSession')?.paths[1]?.points).toEqual(
+ engine.interaction.get('vectorEditSession')?.paths[0]?.points
+ );
+ }
+ );
+
+ it('keeps the active path when a keyboard keydown is followed by a native contextmenu event', async () => {
+ const { engine, owner } = await renderSpline();
+ const bounds = owner.getBoundingClientRect();
+ const key = new KeyboardEvent('keydown', { key: 'ContextMenu', bubbles: true, cancelable: true });
+ await act(() => owner.dispatchEvent(key));
+ expect(key.defaultPrevented).toBe(true);
+ await expect.element(page.getByRole('menuitem', { name: 'Trace Path', exact: true })).toBeVisible();
+
+ // Chromium emits this after the key, with coordinates unrelated to the selected path.
+ const nativeMenu = new PointerEvent('contextmenu', {
+ bubbles: true,
+ cancelable: true,
+ button: -1,
+ pointerType: 'mouse',
+ clientX: bounds.left + 750,
+ clientY: bounds.top + 450,
+ });
+ await act(() => owner.dispatchEvent(nativeMenu));
+
+ expect(nativeMenu.defaultPrevented).toBe(true);
+ expect(engine.interaction.get('vectorEditSession')?.activePathId).toBe('selected-path');
+ await expect.element(page.getByRole('menuitem', { name: 'Trace Path', exact: true })).toBeVisible();
+ });
+
+ it('keeps pointer targeting and native menus in inline editors, without handling other widgets', async () => {
+ const { engine, owner } = await renderSpline();
+ const bounds = owner.getBoundingClientRect();
+ await act(() =>
+ owner.dispatchEvent(
+ new MouseEvent('contextmenu', {
+ bubbles: true,
+ cancelable: true,
+ button: 2,
+ clientX: bounds.left + 750,
+ clientY: bounds.top + 450,
+ })
+ )
+ );
+ await expect.element(page.getByRole('menuitem', { name: 'Trace Path', exact: true })).toBeVisible();
+ expect(engine.interaction.get('vectorEditSession')?.activePathId).toBe('other-path');
+ await act(() => userEvent.keyboard('{Escape}'));
+ await expect.element(page.getByRole('menuitem', { name: 'Trace Path', exact: true })).not.toBeInTheDocument();
+
+ const editor = document.createElement('textarea');
+ owner.append(editor);
+ editor.focus();
+ const key = new KeyboardEvent('keydown', { key: 'F10', shiftKey: true, bubbles: true, cancelable: true });
+ const nativeMenu = new MouseEvent('contextmenu', { bubbles: true, cancelable: true });
+ await act(() => {
+ editor.dispatchEvent(key);
+ editor.dispatchEvent(nativeMenu);
+ });
+ expect(key.defaultPrevented).toBe(false);
+ expect(nativeMenu.defaultPrevented).toBe(false);
+ await expect.element(page.getByRole('menuitem', { name: 'Trace Path', exact: true })).not.toBeInTheDocument();
+
+ const elsewhere = document.createElement('button');
+ elsewhere.textContent = 'Other widget';
+ host!.append(elsewhere);
+ owner.focus();
+ await act(() => userEvent.keyboard('{Shift>}{F10}{/Shift}'));
+ await expect.element(page.getByRole('menuitem', { name: 'Trace Path', exact: true })).toBeVisible();
+ await page.getByRole('button', { name: 'Other widget' }).click();
+ await vi.waitFor(() => expect(document.activeElement).toBe(elsewhere));
+ await act(() => userEvent.keyboard('{Shift>}{F10}{/Shift}'));
+ await expect.element(page.getByRole('menuitem', { name: 'Trace Path', exact: true })).not.toBeInTheDocument();
+ });
+
+ it('uses the Canvas fallback when no path is active, including native keyboard contextmenu events', async () => {
+ const { owner } = await renderSpline(false);
+ await act(() => owner.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, button: 0 })));
+ await expect.element(page.getByRole('menu', { name: 'Canvas fallback' })).toBeVisible();
+ await expect.element(page.getByRole('menuitem', { name: 'Trace Path', exact: true })).not.toBeInTheDocument();
+ });
+});
+
describe('CanvasWidgetView accept and stop', () => {
it('accepts the result, then cancels its batch through the workbench queue command with the accept notice', async () => {
const { store } = await renderView('running');
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.test.tsx
index 36d06bf7f5..35b5427601 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.test.tsx
@@ -40,7 +40,7 @@ vi.mock('@workbench/useCanvasProjectMutationDispatch', () => ({
useCanvasProjectMutationDispatch: () => () => undefined,
}));
vi.mock('@features/queue', () => ({ useQueueItemProgressImage: () => null }));
-vi.mock('./engineStoreHooks', () => ({ useCanvasOperation: () => null }));
+vi.mock('./engineStoreHooks', () => ({ useCanvasOperation: () => null, useVectorEditSession: () => null }));
vi.mock('@workbench/canvas-operations/react', () => ({ useCanvasEngine: () => harness.engine }));
vi.mock('./useCanvasGallerySave', () => ({
useCanvasGallerySave: () => ({ isSaving: false, save: () => undefined }),
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
index 423876c308..4ff7d515d9 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
@@ -1,5 +1,5 @@
import type { WidgetViewProps } from '@workbench/widgetContracts';
-import type { MouseEvent as ReactMouseEvent } from 'react';
+import type { KeyboardEvent as ReactKeyboardEvent, MouseEvent as ReactMouseEvent } from 'react';
import { Box } from '@chakra-ui/react';
import { useDndMonitor, type DragEndEvent } from '@dnd-kit/core';
@@ -29,9 +29,11 @@ import {
useWorkbenchCommands,
useWorkbenchQueries,
} from '@workbench/WorkbenchContext';
-import { lazy, Suspense, useCallback, useEffect, useEffectEvent, useMemo, useState } from 'react';
+import { lazy, Suspense, useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import type { VectorPathMenuTarget } from './VectorPathContextMenu';
+
import { useModelGridSize } from './bboxGrid';
import { CanvasBottomOverlay } from './CanvasBottomOverlay';
import { copyCanvasSelection, decodeImageBlob, readClipboardImage } from './canvasClipboard';
@@ -84,6 +86,10 @@ import { useCreateFromBbox } from './useCreateFromBbox';
import { useStagedResultGallerySave } from './useStagedResultGallerySave';
import { reportLayerOperation, reportPreparedCommit, reportStructuralCommit } from './useStructuralCommit';
+const VectorPathContextMenu = lazy(() =>
+ import('./VectorPathContextMenu').then((module) => ({ default: module.VectorPathContextMenu }))
+);
+
const MissingFontsDialog = lazy(() =>
import('./MissingFontsDialog').then((module) => ({ default: module.MissingFontsDialog }))
);
@@ -132,6 +138,17 @@ export const CanvasWidgetView = ({ runtime, instance }: WidgetViewProps) => {
// Right-click on the canvas surface targets the selected layer (the panel is
// the sole authority; the stack is never hit-tested) and opens either the
// shared per-layer menu or the global menu at the pointer.
+ const [vectorMenuTarget, setVectorMenuTarget] = useState<VectorPathMenuTarget | null>(null);
+ const vectorMenuReturnFocus = useRef<HTMLElement | null>(null);
+ const closeVectorMenu = useCallback(() => {
+ setVectorMenuTarget(null);
+ const focusTarget = vectorMenuReturnFocus.current;
+ vectorMenuReturnFocus.current = null;
+ const focused = focusTarget?.ownerDocument.activeElement;
+ if (focusTarget?.isConnected && (focused === focusTarget.ownerDocument.body || focused?.closest('[role="menu"]'))) {
+ focusTarget.focus({ preventScroll: true });
+ }
+ }, []);
const [contextMenuTarget, setContextMenuTarget] = useState<CanvasContextMenuTarget | null>(null);
const closeContextMenu = useCallback(() => setContextMenuTarget(null), []);
// Feed model grid policy into the model-agnostic engine using primitive selectors for value-stable
@@ -235,27 +252,65 @@ export const CanvasWidgetView = ({ runtime, instance }: WidgetViewProps) => {
},
[canvasCommands, notifications, queries, queryClient, startDroppedFileUpload, t]
);
+ const openSurfaceContextMenu = useCallback(
+ (surface: HTMLDivElement, clientX: number, clientY: number, keyboard: boolean) => {
+ setVectorMenuTarget(null);
+ vectorMenuReturnFocus.current = null;
+ const bounds = surface.getBoundingClientRect();
+ const x = keyboard ? bounds.left + bounds.width / 2 : clientX;
+ const y = keyboard ? bounds.top + bounds.height / 2 : clientY;
+ // Keyboard invocation acts on the current path; only a pointer invocation retargets by geometry.
+ if (keyboard || engine?.layers.vectorEdit.targetContextMenu({ x: x - bounds.left, y: y - bounds.top })) {
+ const edit = engine?.interaction.get('vectorEditSession');
+ if (edit?.activePathId) {
+ const focused = surface.ownerDocument.activeElement;
+ if (keyboard && focused instanceof HTMLElement && surface.contains(focused)) {
+ vectorMenuReturnFocus.current = focused;
+ }
+ setContextMenuTarget(null);
+ setVectorMenuTarget({ x, y, layerId: edit.layerId, pathId: edit.activePathId });
+ return;
+ }
+ }
+ setContextMenuTarget(
+ resolveCanvasContextMenu({
+ clientX: x,
+ clientY: y,
+ isInlineEditor: false,
+ selectedLayerId: engine?.tools.canTargetLayerFromContextMenu() ? canvas.document.selectedLayerId : null,
+ }).target
+ );
+ },
+ [canvas.document.selectedLayerId, engine]
+ );
const { drag: fileDrag, handlers: fileDragHandlers } = useNativeFileDrag({
findZone: findCanvasImageDropDestination,
onDrop: importDroppedFiles,
});
const handleSurfaceContextMenu = useCallback(
(event: ReactMouseEvent<HTMLDivElement>) => {
- // Preserve native menus in inline editors. Canvas context actions target the selected layer without changing
- // selection.
- const resolution = resolveCanvasContextMenu({
- clientX: event.clientX,
- clientY: event.clientY,
- isInlineEditor: event.target instanceof Element && !!event.target.closest(INLINE_EDIT_SELECTOR),
- selectedLayerId: engine?.tools.canTargetLayerFromContextMenu() ? canvas.document.selectedLayerId : null,
- });
- if (!resolution.preventDefault) {
+ if (event.target instanceof Element && event.target.closest(INLINE_EDIT_SELECTOR)) {
return;
}
event.preventDefault();
- setContextMenuTarget(resolution.target);
+ openSurfaceContextMenu(event.currentTarget, event.clientX, event.clientY, event.button <= 0);
},
- [canvas.document.selectedLayerId, engine]
+ [openSurfaceContextMenu]
+ );
+ const handleSurfaceMenuKeyDown = useCallback(
+ (event: ReactKeyboardEvent<HTMLDivElement>) => {
+ if (
+ event.defaultPrevented ||
+ (event.key !== 'ContextMenu' &&
+ !(event.key === 'F10' && event.shiftKey && !event.ctrlKey && !event.altKey && !event.metaKey)) ||
+ (event.target instanceof Element && event.target.closest(INLINE_EDIT_SELECTOR))
+ ) {
+ return;
+ }
+ event.preventDefault();
+ openSurfaceContextMenu(event.currentTarget, 0, 0, true);
+ },
+ [openSurfaceContextMenu]
);
const handleCanvasImageDrop = useCallback(
@@ -581,11 +636,25 @@ export const CanvasWidgetView = ({ runtime, instance }: WidgetViewProps) => {
<MissingFontsDialog key={projectId} engine={engine} groups={fontReferences} />
</Suspense>
) : null}
- <CanvasSurfaceContextLayout surface={canvasSurface} onContextMenu={handleSurfaceContextMenu}>
+ <CanvasSurfaceContextLayout
+ surface={canvasSurface}
+ onContextMenu={handleSurfaceContextMenu}
+ onKeyDown={handleSurfaceMenuKeyDown}
+ >
+ {!engine ? (
+ <Box role="status" position="absolute" inset="0" display="grid" placeItems="center" color="fg.muted">
+ {t('common.loading')}
+ </Box>
+ ) : null}
<CanvasImageDropOverlay fileDrag={fileDrag} isDocumentEditingLocked={isDocumentEditingLocked} />
{engine ? (
<>
<ToolStrip engine={engine} />
+ {vectorMenuTarget ? (
+ <Suspense fallback={null}>
+ <VectorPathContextMenu engine={engine} target={vectorMenuTarget} onClose={closeVectorMenu} />
+ </Suspense>
+ ) : null}
<CanvasFrameSizeReadout engine={engine} />
<ControlLayerCanvasOverlay engine={engine} isFileDragActive={fileDrag !== null} />
<CanvasLayerContextMenu
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsx
index 6e0d20b034..96569a7d59 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsx
@@ -23,6 +23,7 @@ import {
ScanIcon,
SquareDashedMousePointerIcon,
TypeIcon,
+ SplinePointerIcon,
} from 'lucide-react';
import { useCallback, useEffect, useMemo, type ElementType, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
@@ -260,6 +261,13 @@ const ToolStripRoot = ({ engine }: { engine: ToolStripEngine }) => {
toolId="text"
/>
<SelectFamilyButton engine={engine} />
+ <ToolStripButton
+ engine={engine}
+ hotkey={hotkeyFor('canvas.tool.spline')}
+ icon={SplinePointerIcon}
+ label={t('widgets.canvas.tools.spline')}
+ toolId="spline"
+ />
</Toolbar>
</Box>
);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/VectorPathContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/VectorPathContextMenu.tsx
new file mode 100644
index 0000000000..b011060003
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/VectorPathContextMenu.tsx
@@ -0,0 +1,123 @@
+import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';
+
+import { Menu, Portal } from '@chakra-ui/react';
+import { MenuActionItem, MenuContent } from '@platform/ui/Menu';
+import { useNotify } from '@workbench/useNotify';
+import { CopyIcon, PaintBucketIcon, ScanIcon, SquareArrowOutUpRightIcon, Trash2Icon, WavesIcon } from 'lucide-react';
+import { useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useVectorEditSession } from './engineStoreHooks';
+import { vectorTraceErrorKey } from './vectorTraceNotice';
+
+export interface VectorPathMenuTarget {
+ x: number;
+ y: number;
+ layerId: string;
+ pathId: string;
+}
+
+/** Path actions use the point-tool selection and commit through document history. */
+export const VectorPathContextMenu = ({
+ engine,
+ target,
+ onClose,
+}: {
+ engine: Pick<CanvasEngineHandle, 'layers' | 'interaction'>;
+ target: VectorPathMenuTarget | null;
+ onClose(): void;
+}) => {
+ const { t } = useTranslation();
+ const notify = useNotify();
+ const session = useVectorEditSession(engine);
+ const positioning = useMemo(
+ () => ({
+ getAnchorRect: () => ({ x: target?.x ?? 0, y: target?.y ?? 0, width: 1, height: 1 }),
+ placement: 'bottom-start' as const,
+ }),
+ [target?.x, target?.y]
+ );
+ const onOpenChange = useCallback(
+ ({ open }: { open: boolean }) => {
+ if (!open) {
+ onClose();
+ }
+ },
+ [onClose]
+ );
+ if (!target || !session || session.layerId !== target.layerId || session.activePathId !== target.pathId) {
+ return null;
+ }
+ const api = engine.layers.vectorEdit;
+ const label = (key: string) => t(`widgets.layers.vector.${key}`);
+ const run = (action: () => void) => () => {
+ const live = engine.interaction.get('vectorEditSession');
+ if (live && live.layerId === target.layerId && live.activePathId === target.pathId) {
+ action();
+ }
+ onClose();
+ };
+ return (
+ <Menu.Root lazyMount open unmountOnExit positioning={positioning} onOpenChange={onOpenChange}>
+ <Portal>
+ <Menu.Positioner>
+ <MenuContent minW="14rem" py="1">
+ <Menu.ItemGroup>
+ <Menu.ItemGroupLabel>{label('pathTitle')}</Menu.ItemGroupLabel>
+ <MenuActionItem
+ value="transform-path"
+ icon={ScanIcon}
+ label={label('transformPath')}
+ onSelect={run(api.transformPath)}
+ />
+ <MenuActionItem
+ value="trace-path"
+ icon={WavesIcon}
+ label={label('tracePath')}
+ disabled={!session.paths.some((path) => path.id === target.pathId && path.points.length >= 2)}
+ onSelect={run(async () => {
+ const errorKey = vectorTraceErrorKey(
+ await engine.layers.traceVectorLayer(target.layerId, target.pathId)
+ );
+ if (errorKey) {
+ notify.error(label(errorKey));
+ }
+ })}
+ />
+ <MenuActionItem
+ value="fill-path"
+ icon={PaintBucketIcon}
+ label={label('fillPath')}
+ disabled={
+ !session.paths.some((path) => path.id === target.pathId && path.isClosed && path.points.length >= 3)
+ }
+ onSelect={run(async () => {
+ const errorKey = vectorTraceErrorKey(
+ await engine.layers.fillVectorPath(target.layerId, target.pathId)
+ );
+ if (errorKey) {
+ notify.error(label(errorKey));
+ }
+ })}
+ />
+ <MenuActionItem
+ value="extract-path"
+ icon={SquareArrowOutUpRightIcon}
+ label={label('extractPath')}
+ onSelect={run(api.extractPath)}
+ />
+ <MenuActionItem value="copy-path" icon={CopyIcon} label={label('copy')} onSelect={run(api.copyPath)} />
+ <MenuActionItem
+ value="delete-path"
+ icon={Trash2Icon}
+ label={label('deletePath')}
+ tone="danger"
+ onSelect={run(api.deletePath)}
+ />
+ </Menu.ItemGroup>
+ </MenuContent>
+ </Menu.Positioner>
+ </Portal>
+ </Menu.Root>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
index 5c4dee8068..ecac418646 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
@@ -177,6 +177,10 @@ export interface CanvasHotkeyContext extends Omit<CanvasToolCommandContext, 'eng
*/
export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyContext): void => {
const { dispatch, document, engine, t } = ctx;
+ if (commandId === 'canvas.deleteSelected' && engine?.interaction.get('vectorEditSession')) {
+ engine.layers.vectorEdit.deleteSelection();
+ return;
+ }
const { selectedLayerId } = document;
const index = getDocumentIndex(document);
const selected = selectedLayerId ? index.byId.get(selectedLayerId) : undefined;
@@ -213,6 +217,15 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyC
// Arrow-key nudge: engine owns the bounds/lock logic (no-op with no/locked selection).
const nudge = NUDGE_DELTAS[commandId];
if (nudge) {
+ const vectorSession = engine?.interaction.get('vectorEditSession');
+ if (
+ engine &&
+ vectorSession &&
+ (vectorSession.activePathId !== null || vectorSession.selectedPoints.length > 0 || vectorSession.pathTransform)
+ ) {
+ engine.layers.vectorEdit.nudge(nudge.dx, nudge.dy);
+ return;
+ }
const nudged = engine?.layers.nudgeSelectedLayer(nudge.dx, nudge.dy);
// A nudge with nothing eligible selected is an expected no-op; only a broken commit is news.
if (nudged?.status === 'postcondition-failed') {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasToolCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasToolCommands.ts
index 447824de98..120a4b27e1 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasToolCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasToolCommands.ts
@@ -14,7 +14,7 @@ import { captureAccountScope } from '@platform/state/accountLifecycle';
import { createActionToast } from '@platform/ui/toaster';
import { getDocumentNode, mergeDownEligibility } from '@workbench/canvas-engine/api';
import { reportLayerOperation, type LayerOperationRefusal } from '@workbench/widgets/canvas/useStructuralCommit';
-import { CircleIcon, PenLineIcon, PentagonIcon, SquareIcon, StarIcon, TriangleIcon } from 'lucide-react';
+import { CircleIcon, PenLineIcon, VectorPolygonIcon, SquareIcon, StarIcon, TriangleIcon } from 'lucide-react';
/**
* A command refusal the user can fix, shown the way the Canvas shows its edit refusals: an info toast only, never
@@ -146,6 +146,7 @@ export const CANVAS_COMPANION_HOTKEYS = [
['canvas.tool.marquee', 'widgets.canvas.commands.selectMarqueeTool', ['m']],
['canvas.tool.shape', 'widgets.canvas.commands.selectShapeTool', ['u']],
['canvas.tool.text', 'widgets.canvas.commands.selectTextTool', ['t']],
+ ['canvas.tool.spline', 'widgets.canvas.commands.selectSplineTool', ['s']],
['canvas.tool.gradient', 'widgets.canvas.commands.selectGradientTool', ['g']],
// A sticky picker for those who would rather not hold Alt; Alt still picks from tools that do not read it.
['canvas.tool.colorPicker', 'widgets.canvas.commands.selectColorPickerTool', ['i']],
@@ -169,7 +170,7 @@ export const CANVAS_HISTORY_HOTKEYS = [
export const SHAPE_KIND_PRESENTATION: Record<ShapeToolKind, { icon: ElementType; labelKey: string }> = {
ellipse: { icon: CircleIcon, labelKey: 'widgets.canvas.toolOptions.shapeEllipse' },
freehand: { icon: PenLineIcon, labelKey: 'widgets.canvas.toolOptions.shapeFreehand' },
- polygon: { icon: PentagonIcon, labelKey: 'widgets.canvas.toolOptions.shapePolygon' },
+ polygon: { icon: VectorPolygonIcon, labelKey: 'widgets.canvas.toolOptions.shapePolygon' },
rect: { icon: SquareIcon, labelKey: 'widgets.canvas.toolOptions.shapeRect' },
star: { icon: StarIcon, labelKey: 'widgets.canvas.toolOptions.shapeStar' },
triangle: { icon: TriangleIcon, labelKey: 'widgets.canvas.toolOptions.shapeTriangle' },
@@ -308,6 +309,9 @@ export const executeCanvasToolCommand = (commandId: CanvasToolCommandId, ctx: Ca
case 'canvas.tool.text':
engine.tools.setTool('text');
return;
+ case 'canvas.tool.spline':
+ engine.tools.setTool('spline');
+ return;
case 'canvas.tool.gradient':
engine.tools.setTool('gradient');
return;
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts
index 506d518fad..40a2738b36 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts
@@ -42,6 +42,18 @@ const useCanvasInteractionState = <K extends keyof CanvasInteractionState>(
return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
};
+/** Point-tool selection and in-flight geometry preview. Completed edits use document history. */
+export const useVectorEditSession = (
+ engine: CanvasCoreStoreCapability | null
+): CanvasInteractionState['vectorEditSession'] => {
+ const subscribe = useCallback(
+ (listener: () => void) => engine?.interaction.subscribe('vectorEditSession', listener) ?? (() => {}),
+ [engine]
+ );
+ const read = useCallback(() => engine?.interaction.get('vectorEditSession') ?? null, [engine]);
+ return useSyncExternalStore(subscribe, read, read);
+};
+
/**
* Subscribe only to one layer's thumbnail version; null engines return undefined without subscribing for fallback
* rendering.
@@ -266,8 +278,14 @@ export const useBboxOptions = (engine: CanvasCoreStoreCapability): BboxToolOptio
export const useBboxGrid = (engine: CanvasCoreStoreCapability): number => useCanvasInteractionState(engine, 'bboxGrid');
/** The active transform-tool session (layer id + live transform), or `null`. */
-export const useTransformSession = (engine: CanvasCoreStoreCapability): TransformSession | null =>
- useCanvasInteractionState(engine, 'transformSession');
+export const useTransformSession = (engine: CanvasCoreStoreCapability | null): TransformSession | null => {
+ const subscribe = useCallback(
+ (listener: () => void) => engine?.interaction.subscribe('transformSession', listener) ?? (() => undefined),
+ [engine]
+ );
+ const read = useCallback(() => engine?.interaction.get('transformSession') ?? null, [engine]);
+ return useSyncExternalStore(subscribe, read, read);
+};
/** The layer a requested transform waits on until its stroke saves; null when nothing is waiting. */
export const usePendingTransformLayerId = (engine: CanvasCoreStoreCapability): string | null =>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx
index bf41571084..26fb7a8ee9 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx
@@ -39,7 +39,7 @@ const FALLBACK_COLOR = '#000000';
const formatPx = (value: number): string => `${value}px`;
/** Where Place on = Selected layer sends the next shape, given the selection. */
-type SelectedPlacement = 'none' | 'layer' | 'mask' | 'new-layer';
+type SelectedPlacement = 'none' | 'layer' | 'mask' | 'vector' | 'new-layer';
const setShapeOptions = (engine: ToolFormProps['engine'], patch: Partial<ShapeToolOptions>): void => {
engine.interaction.set('shapeOptions', { ...engine.interaction.get('shapeOptions'), ...patch });
@@ -55,6 +55,9 @@ const ShapeToolSettings = ({ engine }: ToolFormProps) => {
if (!layer) {
return 'none';
}
+ if (layer.type === 'vector') {
+ return 'vector';
+ }
if (layer.type === 'inpaint_mask' || layer.type === 'regional_guidance') {
return 'mask';
}
@@ -64,13 +67,17 @@ const ShapeToolSettings = ({ engine }: ToolFormProps) => {
() =>
SHAPE_KIND_ORDER.map((value) => ({
icon: SHAPE_KIND_PRESENTATION[value].icon,
- label: t(SHAPE_KIND_PRESENTATION[value].labelKey),
+ label: t(
+ placement === 'vector' && value === 'polygon'
+ ? 'widgets.canvas.toolOptions.vectorShapePolyline'
+ : SHAPE_KIND_PRESENTATION[value].labelKey
+ ),
value,
})),
- [t]
+ [placement, t]
);
const onKindChange = useCallback((kind: ShapeToolKind) => setShapeOptions(engine, { kind }), [engine]);
- const canPlaceSelected = placement === 'layer' || placement === 'mask';
+ const canPlaceSelected = placement === 'layer' || placement === 'mask' || placement === 'vector';
const targetOptions = useMemo(
() => [
{
@@ -87,6 +94,8 @@ const ShapeToolSettings = ({ engine }: ToolFormProps) => {
[engine]
);
const hintId = useId();
+ const polylineHintId = useId();
+ const showPolylineHint = placement === 'vector' && options.kind === 'polygon';
const hintKey = !canPlaceSelected
? 'widgets.canvas.toolOptions.shapeTargetFallbackHint'
: options.target === 'selected' && placement === 'mask'
@@ -95,6 +104,7 @@ const ShapeToolSettings = ({ engine }: ToolFormProps) => {
return (
<>
<PropertySegmentedRow
+ describedBy={showPolylineHint ? polylineHintId : undefined}
label={t('widgets.properties.rows.kind')}
options={kindOptions}
value={options.kind}
@@ -107,6 +117,11 @@ const ShapeToolSettings = ({ engine }: ToolFormProps) => {
value={canPlaceSelected ? options.target : 'new'}
onValueChange={onTargetChange}
/>
+ {showPolylineHint ? (
+ <Text color="fg.muted" fontSize="xs" id={polylineHintId}>
+ {t('widgets.canvas.toolOptions.vectorPolylineHint')}
+ </Text>
+ ) : null}
{hintKey ? (
<Text color="fg.muted" fontSize="xs" id={hintId}>
{t(hintKey)}
@@ -296,10 +311,22 @@ const ShapeAppearanceControls = ({
);
};
+const useSelectedVectorName = () =>
+ useActiveProjectSelector((project) => {
+ const { document } = project.canvas;
+ const layer = getDocumentLayer(document, document.selectedLayerId);
+ return layer?.type === 'vector' ? layer.name : null;
+ });
+
+const ShapeAppearanceSettings = (props: ToolFormProps) => {
+ const name = useSelectedVectorName();
+ return name !== null ? null : <ShapeDefaultAppearanceSettings {...props} />;
+};
+
export const shapeForm: ToolPropertyForm = {
groups: [
{ body: ShapeToolSettings, id: 'shape', labelKey: 'widgets.properties.groups.shape' },
- { body: ShapeDefaultAppearanceSettings, id: 'shape-appearance', labelKey: 'widgets.properties.groups.appearance' },
+ { body: ShapeAppearanceSettings, id: 'shape-appearance', labelKey: 'widgets.properties.groups.appearance' },
],
id: 'shape',
paintsLeaf: true,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SplineOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SplineOptions.tsx
new file mode 100644
index 0000000000..9745ca5c92
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SplineOptions.tsx
@@ -0,0 +1,139 @@
+import type { ToolFormProps } from '@workbench/widgets/canvas/tool-presentation/toolFormContracts';
+
+import { Box, Grid, Stack, Text } from '@chakra-ui/react';
+import { Button } from '@platform/ui/Button';
+import { SegmentedControl } from '@platform/ui/SegmentedControl';
+import { useVectorEditSession } from '@workbench/widgets/canvas/engineStoreHooks';
+import { PropertyControlRow } from '@workbench/widgets/canvas/tool-presentation/PropertyPrimitives';
+import { useCallback, useMemo, type ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
+
+const ACTION_ROW_CSS = {
+ '& > *': { position: 'relative', minWidth: 0, fontSize: 'xs' },
+ '& > * + *::before': {
+ content: '""',
+ position: 'absolute',
+ insetInlineStart: '-1.5px',
+ top: '50%',
+ transform: 'translateY(-50%)',
+ height: '3.5',
+ width: '1px',
+ bg: 'border.emphasized',
+ pointerEvents: 'none',
+ },
+} as const;
+
+/** Action rows share the Shapes segmented frame without giving commands radio-button semantics. */
+const SplineActionRow = ({
+ children,
+ label,
+ columns = 2,
+}: {
+ children: ReactNode;
+ label: string;
+ columns?: number;
+}) => (
+ <Grid
+ aria-label={label}
+ role="group"
+ borderColor="border.subtle"
+ borderRadius="control"
+ borderWidth="1px"
+ gap="0.5"
+ p="0.5"
+ templateColumns={`repeat(${columns}, minmax(0, 1fr))`}
+ css={ACTION_ROW_CSS}
+ >
+ {children}
+ </Grid>
+);
+
+export const SplineSettings = ({ engine }: ToolFormProps) => {
+ const { t } = useTranslation();
+ const editing = useVectorEditSession(engine);
+ const api = engine.layers.vectorEdit;
+ const label = (key: string) => t(`widgets.layers.vector.${key}`);
+ const pointTypeOptions = useMemo(
+ () =>
+ (['corner', 'smooth', 'symmetric'] as const).map((type) => ({
+ value: type,
+ label: t(`widgets.layers.vector.${type}`),
+ })),
+ [t]
+ );
+ const setPointType = useCallback(
+ (type: string) => api.setPointType(type as 'corner' | 'smooth' | 'symmetric'),
+ [api]
+ );
+ const smoothPath = useCallback(() => api.smooth(false), [api]);
+ const smoothPoints = useCallback(() => api.smooth(true), [api]);
+ const selected = !!editing && editing.selectedPoints.length > 0;
+ const paths = editing?.paths ?? [];
+ const active = paths.find((path) => path.id === editing?.activePathId);
+ const pointTypes = new Set(
+ editing?.selectedPoints.flatMap((ref) => {
+ const point = paths.find((path) => path.id === ref.pathId)?.points[ref.pointIndex];
+ return point ? [point.type] : [];
+ })
+ );
+ return (
+ <Stack gap="3">
+ {!editing ? (
+ <Text color="fg.muted" fontSize="sm">
+ {label('selectVectorLayerHint')}
+ </Text>
+ ) : null}
+ <SegmentedControl
+ ariaLabel={label('pointsTitle')}
+ disabled={!selected}
+ options={pointTypeOptions}
+ value={pointTypes.size === 1 ? ([...pointTypes][0] ?? null) : null}
+ onChange={setPointType}
+ />
+ <SplineActionRow label={label('pointsTitle')}>
+ <Button colorPalette="gray" disabled={!editing?.canSplit} size="sm" variant="ghost" onClick={api.split}>
+ {label('split')}
+ </Button>
+ <Button colorPalette="gray" disabled={!editing?.canJoin} size="sm" variant="ghost" onClick={api.join}>
+ {label('join')}
+ </Button>
+ </SplineActionRow>
+ <Stack
+ borderColor="border.subtle"
+ borderTopWidth="1px"
+ gap="3"
+ mt="2"
+ pt="4"
+ role="group"
+ aria-label={label('pathPropertiesTitle')}
+ >
+ <Text color="fg.muted" fontWeight="600">
+ {label('pathPropertiesTitle')}
+ </Text>
+ <PropertyControlRow label={label('smooth')}>
+ <Box gridColumn="2 / -1" minW="0">
+ <SplineActionRow label={label('smooth')}>
+ <Button colorPalette="gray" disabled={!active} size="sm" variant="ghost" onClick={smoothPath}>
+ {label('pathPropertiesTitle')}
+ </Button>
+ <Button colorPalette="gray" disabled={!selected} size="sm" variant="ghost" onClick={smoothPoints}>
+ {label('pointsTitle')}
+ </Button>
+ </SplineActionRow>
+ </Box>
+ </PropertyControlRow>
+ <SplineActionRow columns={3} label={label('pathPropertiesTitle')}>
+ <Button colorPalette="gray" disabled={!active} size="sm" variant="ghost" onClick={api.copyPath}>
+ {label('copyPathButton')}
+ </Button>
+ <Button colorPalette="gray" disabled={!active} size="sm" variant="ghost" onClick={api.extractPath}>
+ {label('extract')}
+ </Button>
+ <Button colorPalette="gray" disabled={!active} size="sm" variant="ghost" onClick={api.deletePath}>
+ {label('deletePathButton')}
+ </Button>
+ </SplineActionRow>
+ </Stack>
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolAdapters.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolAdapters.test.ts
index 71f407e996..aa8cf93613 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolAdapters.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolAdapters.test.ts
@@ -15,6 +15,7 @@ const TOOL_IDS = Object.keys({
move: true,
sam: true,
shape: true,
+ spline: true,
text: true,
transform: true,
view: true,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolAdapters.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolAdapters.ts
index acc339f227..19b7f43957 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolAdapters.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolAdapters.ts
@@ -1,5 +1,6 @@
import type { ToolId } from '@workbench/canvas-engine/api';
+import { Skeleton } from '@chakra-ui/react';
import { filterOperationForm } from '@workbench/widgets/canvas/tool-options/FilterOptions';
import { bboxForm, moveForm, transformForm } from '@workbench/widgets/canvas/tool-options/geometryForm';
import { gradientForm } from '@workbench/widgets/canvas/tool-options/GradientOptions';
@@ -8,8 +9,20 @@ import { selectObjectOperationForm } from '@workbench/widgets/canvas/tool-option
import { lassoForm, marqueeForm } from '@workbench/widgets/canvas/tool-options/selectionForm';
import { shapeForm } from '@workbench/widgets/canvas/tool-options/ShapeOptions';
import { textForm } from '@workbench/widgets/canvas/tool-options/textForm';
+import { createElement, lazy, Suspense } from 'react';
-import type { CanvasOperationKind, OperationPropertyForm, ToolPropertyForm } from './toolFormContracts';
+import type { CanvasOperationKind, OperationPropertyForm, ToolFormProps, ToolPropertyForm } from './toolFormContracts';
+
+const SplineSettings = lazy(() =>
+ import('@workbench/widgets/canvas/tool-options/SplineOptions').then((module) => ({ default: module.SplineSettings }))
+);
+const splineLoadingRows = createElement(Skeleton, { height: '20' });
+const SplineBody = (props: ToolFormProps) =>
+ createElement(Suspense, { fallback: splineLoadingRows }, createElement(SplineSettings, props));
+const splineForm: ToolPropertyForm = {
+ id: 'spline',
+ groups: [{ body: SplineBody, id: 'spline-points', labelKey: 'widgets.layers.vector.pointsTitle' }],
+};
export const TOOL_PRESENTATION_ADAPTERS: Readonly<Record<ToolId, ToolPropertyForm>> = {
bbox: bboxForm,
@@ -22,6 +35,7 @@ export const TOOL_PRESENTATION_ADAPTERS: Readonly<Record<ToolId, ToolPropertyFor
move: moveForm,
sam: { groups: [], id: 'sam' },
shape: shapeForm,
+ spline: splineForm,
text: textForm,
transform: transformForm,
view: { groups: [], id: 'view' },
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/vectorTraceNotice.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/vectorTraceNotice.ts
new file mode 100644
index 0000000000..7ecc3e8c4e
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/vectorTraceNotice.ts
@@ -0,0 +1,21 @@
+import type { VectorTraceResult } from '@workbench/canvas-engine/api';
+
+/** Maps vector rendering outcomes to the existing Properties and path-menu notices. */
+export const vectorTraceErrorKey = ({ status }: VectorTraceResult): string | null => {
+ if (status === 'committed' || status === 'aborted' || status === 'stale') {
+ return null;
+ }
+ if (status === 'empty') {
+ return 'traceEmpty';
+ }
+ if (status === 'too-complex') {
+ return 'traceTooComplex';
+ }
+ if (status === 'over-budget') {
+ return 'traceOverBudget';
+ }
+ if (status === 'busy' || status === 'gesture-active') {
+ return 'traceBusy';
+ }
+ return 'traceFailed';
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackHeader.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackHeader.tsx
index ac01db61dd..b2c99b14ce 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackHeader.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackHeader.tsx
@@ -21,6 +21,7 @@ const STACK_HINTS: Record<LayerStackKind, FeatureHintId> = {
inpaint_mask: 'layerStackInpaintMask',
raster: 'layerStackRaster',
regional_guidance: 'layerStackRegionalGuidance',
+ vector: 'layerStackVector',
};
interface LayerStackHeaderProps {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx
index 5ce863c2a0..097df66135 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx
@@ -570,7 +570,7 @@ export const LayersTree = ({
const parent = lookupDocumentNodeState(currentDocument, vm.parentId)!;
const grandSiblings =
parent.parentId === null
- ? currentDocument.stacks[parent.stack]
+ ? (currentDocument.stacks[parent.stack] ?? [])
: (getDocumentNode(currentDocument, parent.parentId) as { children: readonly { id: string }[] })
.children;
const beforeId = grandSiblings[parent.siblingIndex + 1]?.id ?? null;
@@ -584,7 +584,7 @@ export const LayersTree = ({
}
const siblings =
vm.parentId === null
- ? currentDocument.stacks[vm.stack]
+ ? (currentDocument.stacks[vm.stack] ?? [])
: (getDocumentNode(currentDocument, vm.parentId) as { children: readonly { id: string; type: string }[] })
.children;
const above = siblings[vm.siblingIndex - 1];
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/VectorLayerSettings.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/VectorLayerSettings.browser.test.tsx
new file mode 100644
index 0000000000..db0b42e4aa
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/VectorLayerSettings.browser.test.tsx
@@ -0,0 +1,143 @@
+import type { CanvasVectorLayerContract } from '@workbench/canvas-engine/contracts';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { system } from '@theme/system';
+import { createVectorLayer } from '@workbench/canvas-engine/api';
+import { documentFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
+import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';
+import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';
+import { createCanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';
+import { createCanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';
+import { createInitialWorkbenchState } from '@workbench/workbenchState';
+import { createWorkbenchStore } from '@workbench/workbenchStore';
+import { createInstance } from 'i18next';
+import { act, useSyncExternalStore } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeAll, expect, it, vi } from 'vitest';
+import { page, userEvent } from 'vitest/browser';
+
+import { VectorLayerSettings } from './VectorLayerSettings';
+
+const i18n = createInstance();
+let root: Root | null = null;
+let host: HTMLDivElement | null = null;
+let engine: ReturnType<typeof createCanvasEngine> | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+beforeAll(async () => {
+ const translation = await fetch('/locales/en.json').then((response) => response.json());
+ await i18n.use(initReactI18next).init({ initAsync: false, lng: 'en', resources: { en: { translation } } });
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ engine?.lifecycle.dispose();
+ host?.remove();
+ root = null;
+ host = null;
+ engine = null;
+});
+
+it('edits and undoes layer appearance independently of another vector layer and the brush', async () => {
+ const a = {
+ ...createVectorLayer({ id: 'a', name: 'A' }),
+ strokeColor: '#ff0000',
+ strokeWidth: 17,
+ fillColor: '#abcdef',
+ fillEnabled: true,
+ };
+ const b = {
+ ...createVectorLayer({ id: 'b', name: 'B' }),
+ strokeColor: '#0000ff',
+ strokeWidth: 3,
+ fillColor: '#00ff00',
+ fillEnabled: true,
+ };
+ const initial = createInitialWorkbenchState();
+ const project = initial.projects[0]!;
+ const store = createWorkbenchStore({
+ ...initial,
+ projects: [{ ...project, canvas: { ...project.canvas, document: documentFrom([a, b], 'a') } }],
+ });
+ engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ imageResolver: () => Promise.resolve(new Blob()),
+ ensureProjectOnServer: () => Promise.resolve(),
+ reportError: () => undefined,
+ mutationPort: createCanvasProjectMutationPort(store, project.id),
+ projectId: project.id,
+ });
+ const liveEngine = engine;
+ const document = () => store.queries.getSnapshot().activeProject.canvas.document;
+ const layer = (id: string) => getDocumentLayer(document(), id) as CanvasVectorLayerContract;
+ const Harness = () => {
+ const doc = useSyncExternalStore(store.subscribe, document);
+ const selected = getDocumentLayer(doc, doc.selectedLayerId!) as CanvasVectorLayerContract;
+ return <VectorLayerSettings key={selected.id} engine={liveEngine} layer={selected} />;
+ };
+ host = globalThis.document.createElement('div');
+ host.style.width = '340px';
+ globalThis.document.body.append(host);
+ root = createRoot(host);
+ await act(() =>
+ root!.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <Harness />
+ </ChakraProvider>
+ </I18nextProvider>
+ )
+ );
+ const brush = liveEngine.interaction.get('brushOptions');
+ const width = page.getByRole('slider', { name: 'Stroke width', exact: true });
+ await expect.element(width).toHaveAttribute('aria-valuenow', '17');
+ await width.element().focus();
+ await act(() => userEvent.keyboard('{ArrowRight}'));
+ expect(layer('a').strokeWidth).toBe(18);
+ expect(layer('b')).toEqual(b);
+ expect(liveEngine.interaction.get('brushOptions')).toEqual(brush);
+ await act(() => liveEngine.history.undo());
+ expect(layer('a').strokeWidth).toBe(17);
+ await act(() => liveEngine.history.redo());
+ expect(layer('a').strokeWidth).toBe(18);
+
+ await act(() => page.getByRole('button', { name: 'Trace color', exact: true }).click());
+ const area = globalThis.document.querySelector<HTMLElement>('[data-scope="color-picker"][data-part="area"]')!;
+ const bounds = area.getBoundingClientRect();
+ const at = {
+ clientX: bounds.left + bounds.width * 0.4,
+ clientY: bounds.top + bounds.height * 0.4,
+ pointerId: 1,
+ button: 0,
+ isPrimary: true,
+ bubbles: true,
+ };
+ await act(() => area.dispatchEvent(new PointerEvent('pointerdown', at)));
+ await vi.waitFor(() => expect(layer('a').strokeColor).not.toBe('#ff0000'));
+ const previewed = layer('a').strokeColor;
+ await act(() => globalThis.document.dispatchEvent(new PointerEvent('pointerup', at)));
+ await act(() => userEvent.keyboard('{Escape}'));
+ expect(layer('a').strokeColor).toBe(previewed);
+ expect(layer('b')).toEqual(b);
+ expect(liveEngine.interaction.get('brushOptions')).toEqual(brush);
+ await act(() => liveEngine.history.undo());
+ expect(layer('a').strokeColor).toBe('#ff0000');
+ await act(() => liveEngine.history.redo());
+ expect(layer('a').strokeColor).toBe(previewed);
+
+ await act(() => page.getByRole('button', { name: 'Fill', exact: true }).click());
+ expect(layer('a').fillEnabled).toBe(false);
+ expect(layer('b').fillEnabled).toBe(true);
+ await act(() => liveEngine.history.undo());
+ expect(layer('a').fillEnabled).toBe(true);
+
+ await act(() => store.commands.canvas.apply(project.id, { type: 'setCanvasSelectedLayer', id: 'b' }));
+ await expect.element(width).toHaveAttribute('aria-valuenow', '3');
+ await act(() => liveEngine.interaction.set('brushOptions', { ...brush, color: '#ff00ff', size: 80 }));
+ expect(layer('a').strokeColor).toBe(previewed);
+ expect(layer('a').strokeWidth).toBe(18);
+ expect(layer('b')).toEqual(b);
+ await act(() => store.commands.canvas.apply(project.id, { type: 'setCanvasSelectedLayer', id: 'a' }));
+ await expect.element(width).toHaveAttribute('aria-valuenow', '18');
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/VectorLayerSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/VectorLayerSettings.tsx
new file mode 100644
index 0000000000..cd71667391
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/VectorLayerSettings.tsx
@@ -0,0 +1,280 @@
+import type { CanvasLayerContract } from '@workbench/canvas-engine/api';
+import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';
+
+import { Stack, Text } from '@chakra-ui/react';
+import { Button, ToggleIconButton } from '@platform/ui/Button';
+import { ColorPicker } from '@platform/ui/ColorPicker';
+import { ScrubberField } from '@platform/ui/ScrubberField';
+import { DEFAULT_VECTOR_GUIDE_COLOR, DEFAULT_VECTOR_STROKE_WIDTH } from '@workbench/canvas-engine/api';
+import { PropertyControlRow, PropertySwitchRow } from '@workbench/widgets/canvas/tool-presentation/PropertyPrimitives';
+import { useColorSampler } from '@workbench/widgets/canvas/useColorSampler';
+import { baselineConfig, useStructuralPreview } from '@workbench/widgets/canvas/useStructuralCommit';
+import { vectorTraceErrorKey } from '@workbench/widgets/canvas/vectorTraceNotice';
+import { PaintBucketIcon, SquareIcon } from 'lucide-react';
+import { useCallback, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+type Engine = Pick<CanvasEngineHandle, 'document' | 'layers' | 'tools'>;
+const TAPER_MARKS = [1, 100, 250, 500];
+const formatPixels = (value: number) => `${value}px`;
+const formatPercent = (value: number) => `${value}%`;
+
+/** Layer appearance lives here; point commands belong to the Spline tool form. */
+export const VectorLayerSettings = ({
+ engine,
+ layer,
+}: {
+ engine: Engine | null;
+ layer: Extract<CanvasLayerContract, { type: 'vector' }>;
+}) => {
+ const { t } = useTranslation();
+ const { preview, commit } = useStructuralPreview(engine);
+ const sampleColor = useColorSampler(engine);
+ const color = layer.guideColor ?? DEFAULT_VECTOR_GUIDE_COLOR;
+ const onChange = useCallback(
+ (guideColor: string) => {
+ preview({ type: 'updateCanvasLayerConfig', id: layer.id, config: { layerType: 'vector', guideColor } });
+ },
+ [preview, layer.id]
+ );
+ const onChangeEnd = useCallback(
+ (guideColor: string) => {
+ const config = { layerType: 'vector', guideColor } as const;
+ commit(t('widgets.layers.vector.guideColor'), (model, baseline) => {
+ if (model.document.selectedLayerId !== layer.id) {
+ return { status: 'unchanged' };
+ }
+ return model.prepare({ id: layer.id, type: 'patch-config', config, before: baselineConfig(baseline, config) });
+ });
+ },
+ [commit, layer.id, t]
+ );
+ const resetGuideColor = useCallback(() => onChangeEnd(DEFAULT_VECTOR_GUIDE_COLOR), [onChangeEnd]);
+ return (
+ <Stack gap="2">
+ <Text color="fg.muted" fontSize="sm">
+ {t('widgets.layers.summary.vectorPaths', { count: layer.paths.length })}
+ </Text>
+ <PropertyControlRow label={t('widgets.layers.vector.guideColor')}>
+ <ColorPicker
+ aria-label={t('widgets.layers.vector.guideColor')}
+ disabled={!engine || layer.isLocked || !layer.isEnabled}
+ value={color}
+ onSampleColor={sampleColor}
+ onValueChange={onChange}
+ onValueChangeEnd={onChangeEnd}
+ />
+ <Button
+ size="xs"
+ variant="outline"
+ disabled={!engine || layer.isLocked || !layer.isEnabled || color === DEFAULT_VECTOR_GUIDE_COLOR}
+ onClick={resetGuideColor}
+ >
+ {t('widgets.layers.vector.reset')}
+ </Button>
+ </PropertyControlRow>
+ {engine ? <VectorTraceSettings key={layer.id} engine={engine} layer={layer} /> : null}
+ </Stack>
+ );
+};
+
+const VectorTraceSettings = ({
+ engine,
+ layer,
+}: {
+ engine: Engine;
+ layer: Extract<CanvasLayerContract, { type: 'vector' }>;
+}) => {
+ const { t } = useTranslation();
+ const sampleColor = useColorSampler(engine);
+ const [failure, setFailure] = useState<string | null>(null);
+ const [running, setRunning] = useState(false);
+ const { preview, commit } = useStructuralPreview(engine);
+ const taperEnds = layer.traceTaperEnds ?? false;
+ const taper = layer.traceTaper ?? 100;
+ const label = (key: string) => t(`widgets.layers.vector.${key}`);
+ const clampTaper = useCallback(
+ (value: number) => Math.round(Math.min(500, Math.max(1, Number.isFinite(value) ? value : taper))),
+ [taper]
+ );
+ const commitSettings = useCallback(
+ (patch: {
+ traceTaperEnds?: boolean;
+ traceTaper?: number;
+ fillColor?: string;
+ strokeColor?: string;
+ strokeWidth?: number;
+ fillEnabled?: boolean;
+ strokeEnabled?: boolean;
+ }) => {
+ const config = { layerType: 'vector', ...patch } as const;
+ commit(t('widgets.layers.vector.traceTitle'), (model, baseline) => {
+ if (model.document.selectedLayerId !== layer.id) {
+ return { status: 'unchanged' };
+ }
+ return model.prepare({ id: layer.id, type: 'patch-config', config, before: baselineConfig(baseline, config) });
+ });
+ },
+ [commit, layer.id, t]
+ );
+ const previewFillColor = useCallback(
+ (fillColor: string) =>
+ preview({ type: 'updateCanvasLayerConfig', id: layer.id, config: { layerType: 'vector', fillColor } }),
+ [preview, layer.id]
+ );
+ const commitFillColor = useCallback((fillColor: string) => commitSettings({ fillColor }), [commitSettings]);
+ const commitFillEnabled = useCallback((fillEnabled: boolean) => commitSettings({ fillEnabled }), [commitSettings]);
+ const commitStrokeEnabled = useCallback(
+ (strokeEnabled: boolean) => commitSettings({ strokeEnabled }),
+ [commitSettings]
+ );
+ const previewStrokeColor = useCallback(
+ (strokeColor: string) =>
+ preview({ type: 'updateCanvasLayerConfig', id: layer.id, config: { layerType: 'vector', strokeColor } }),
+ [preview, layer.id]
+ );
+ const commitStrokeColor = useCallback((strokeColor: string) => commitSettings({ strokeColor }), [commitSettings]);
+ const clampStrokeWidth = useCallback(
+ (value: number) => Math.round(Math.min(600, Math.max(1, Number.isFinite(value) ? value : layer.strokeWidth))),
+ [layer.strokeWidth]
+ );
+ const previewStrokeWidth = useCallback(
+ (value: number) =>
+ preview({
+ type: 'updateCanvasLayerConfig',
+ id: layer.id,
+ config: { layerType: 'vector', strokeWidth: clampStrokeWidth(value) },
+ }),
+ [preview, layer.id, clampStrokeWidth]
+ );
+ const commitStrokeWidth = useCallback(
+ (value: number) => commitSettings({ strokeWidth: clampStrokeWidth(value) }),
+ [commitSettings, clampStrokeWidth]
+ );
+ const commitTaperEnds = useCallback(
+ (traceTaperEnds: boolean) => commitSettings({ traceTaperEnds }),
+ [commitSettings]
+ );
+ const previewTaper = useCallback(
+ (value: number) =>
+ preview({
+ id: layer.id,
+ type: 'updateCanvasLayerConfig',
+ config: { layerType: 'vector', traceTaper: clampTaper(value) },
+ }),
+ [preview, layer.id, clampTaper]
+ );
+ const commitTaper = useCallback(
+ (value: number) => commitSettings({ traceTaper: clampTaper(value) }),
+ [commitSettings, clampTaper]
+ );
+ const trace = useCallback(async () => {
+ if (running) {
+ engine.layers.cancelVectorTrace();
+ return;
+ }
+ setFailure(null);
+ setRunning(true);
+ try {
+ setFailure(vectorTraceErrorKey(await engine.layers.traceFillVectorLayer(layer.id)));
+ } finally {
+ setRunning(false);
+ }
+ }, [running, engine, layer.id]);
+ const onTrace = useCallback(() => {
+ void trace();
+ }, [trace]);
+ const disabled = !layer.isEnabled || layer.isLocked || layer.isHidden === true;
+ return (
+ <Stack borderTopWidth="1px" borderColor="border.subtle" gap="2" mt="2" pt="3">
+ <Text color="fg.muted" fontWeight="600">
+ {t('widgets.properties.groups.appearance')}
+ </Text>
+ <PropertyControlRow label={t('widgets.canvas.toolOptions.shapeFill')}>
+ <ColorPicker
+ aria-label={label('fillColor')}
+ disabled={disabled || !layer.fillEnabled}
+ value={layer.fillColor ?? '#ffffff'}
+ onSampleColor={sampleColor}
+ onValueChange={previewFillColor}
+ onValueChangeEnd={commitFillColor}
+ />
+ <ToggleIconButton
+ checked={layer.fillEnabled ?? false}
+ disabled={disabled}
+ icon={PaintBucketIcon}
+ label={t('widgets.canvas.toolOptions.shapeFill')}
+ onCheckedChange={commitFillEnabled}
+ />
+ </PropertyControlRow>
+ <PropertyControlRow label={t('widgets.canvas.toolOptions.shapeStroke')}>
+ <ColorPicker
+ aria-label={label('traceColor')}
+ disabled={disabled || layer.strokeEnabled === false}
+ value={layer.strokeColor}
+ onSampleColor={sampleColor}
+ onValueChange={previewStrokeColor}
+ onValueChangeEnd={commitStrokeColor}
+ />
+ <ToggleIconButton
+ checked={layer.strokeEnabled ?? true}
+ disabled={disabled}
+ icon={SquareIcon}
+ label={t('widgets.canvas.toolOptions.shapeStroke')}
+ onCheckedChange={commitStrokeEnabled}
+ />
+ </PropertyControlRow>
+ <ScrubberField
+ label={label('strokeWidth')}
+ disabled={disabled || layer.strokeEnabled === false}
+ value={layer.strokeWidth}
+ min={1}
+ max={600}
+ step={1}
+ defaultValue={DEFAULT_VECTOR_STROKE_WIDTH}
+ formatValue={formatPixels}
+ onChange={previewStrokeWidth}
+ onChangeEnd={commitStrokeWidth}
+ />
+ <PropertySwitchRow
+ label={label('taperEnds')}
+ disabled={disabled || layer.strokeEnabled === false}
+ checked={taperEnds}
+ onCheckedChange={commitTaperEnds}
+ />
+ <ScrubberField
+ label={label('taper')}
+ disabled={disabled || layer.strokeEnabled === false || !taperEnds}
+ value={taper}
+ min={1}
+ max={500}
+ step={10}
+ defaultValue={100}
+ marks={TAPER_MARKS}
+ formatValue={formatPercent}
+ onChange={previewTaper}
+ onChangeEnd={commitTaper}
+ />
+ <Button
+ size="sm"
+ disabled={
+ !running &&
+ (disabled ||
+ !layer.paths.some(
+ (path) =>
+ (layer.strokeEnabled !== false && path.points.length >= 2) ||
+ (layer.fillEnabled && path.points.length >= 2)
+ ))
+ }
+ onClick={onTrace}
+ >
+ {running ? t('common.cancel') : label('traceFill')}
+ </Button>
+ {failure ? (
+ <Text color="fg.error" fontSize="sm">
+ {label(failure)}
+ </Text>
+ ) : null}
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/addLayerMenu.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/addLayerMenu.test.ts
index 6e2d3aa7a8..7cb0820c1e 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/addLayerMenu.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/addLayerMenu.test.ts
@@ -22,7 +22,7 @@ describe('ADD_LAYER_MENU', () => {
});
it('lists control + raster under Layers', () => {
- expect(ADD_LAYER_MENU[1]?.items.map((item) => item.id)).toEqual(['control', 'raster', 'group']);
+ expect(ADD_LAYER_MENU[1]?.items.map((item) => item.id)).toEqual(['control', 'raster', 'vector', 'group']);
});
it('gives every item a widgets.layers i18n label key', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/addLayerMenu.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/addLayerMenu.ts
index 18af0440b6..aaec33d780 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/addLayerMenu.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/addLayerMenu.ts
@@ -9,6 +9,7 @@ import { canAddRegionalReferenceImage } from './layerOps';
/** The distinct "add a layer" actions offered across the panel's add surfaces. */
export type AddLayerItemId =
+ | 'vector'
| 'inpaint_mask'
| 'regional_guidance'
| 'regional_reference_image'
@@ -41,6 +42,7 @@ export const ADD_LAYER_MENU: readonly AddLayerMenuGroup[] = [
items: [
{ id: 'control', labelKey: 'widgets.layers.actions.addControlLayer' },
{ id: 'raster', labelKey: 'widgets.layers.actions.addRasterLayer' },
+ { id: 'vector', labelKey: 'widgets.layers.actions.addVectorLayer' },
{ id: 'group', labelKey: 'widgets.layers.actions.newGroup' },
],
titleKey: 'widgets.layers.menuGroups.layers',
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerChildRows.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerChildRows.ts
index ac18ed3788..520a0b59d3 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerChildRows.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerChildRows.ts
@@ -528,7 +528,7 @@ export const layerChildMoveTargets = (
document: CanvasDocumentContractV3,
child: Pick<ProjectedChildRow, 'kind' | 'layerId' | 'itemId' | 'stack'>
): LayerChildMoveTarget[] =>
- preorder(document.stacks[child.stack]).flatMap((node) => {
+ preorder(document.stacks[child.stack] ?? []).flatMap((node) => {
if (node.id === child.layerId) {
return [];
}
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 e36612b52c..49bd98d4bb 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
@@ -6,7 +6,7 @@ import type {
} from '@workbench/canvas-engine/contracts';
import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';
-import { createControlLayer } from '@workbench/canvas-engine/api';
+import { createControlLayer, createVectorLayer } from '@workbench/canvas-engine/api';
import { groupContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
import { CircleDotIcon, CircleIcon } from 'lucide-react';
import { describe, expect, it, vi } from 'vitest';
@@ -53,6 +53,8 @@ const makeLayer = (type: CanvasLayerContract['type']): CanvasLayerContract => {
return createInpaintMaskLayer('Mask', 'mask');
case 'regional_guidance':
return createRegionalGuidanceLayer('Region', 0, 'region');
+ case 'vector':
+ return createVectorLayer({ id: 'vector', name: 'Vector' });
}
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
index 332a36f9a3..5eefa6dca9 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
@@ -268,7 +268,7 @@ export interface LayerContextAction {
export type LayerConfigPatchKind = 'control-transparency-effect' | 'regional-auto-negative';
-const ALL_LAYER_TYPES = ['raster', 'control', 'inpaint_mask', 'regional_guidance'] as const;
+const ALL_LAYER_TYPES = ['raster', 'control', 'inpaint_mask', 'regional_guidance', 'vector'] as const;
type AdjustmentAddItem = {
readonly defaultLabel: string;
readonly icon: LucideIcon;
@@ -441,7 +441,13 @@ const hasReadablePixels = (context: LayerContextActionState): boolean =>
const hasMutablePixels = (context: LayerContextActionState): boolean =>
isLayerMutable(context) && hasReadablePixels(context);
const hasTransformablePixels = (context: LayerContextActionState): boolean =>
- context.layer.isEnabled && hasMutablePixels(context);
+ context.layer.type === 'vector'
+ ? context.layer.isEnabled &&
+ isLayerMutable(context) &&
+ context.hasEngine &&
+ !(layerEntry(context)?.ancestorsEnabled === false) &&
+ context.layer.paths.some((path) => path.points.length >= 2)
+ : context.layer.isEnabled && hasMutablePixels(context);
const hasDocumentContent = (context: LayerContextActionState): boolean => {
const contentRect = getSourceContentRect(context.layer, context.document);
return contentRect.width > 0 && contentRect.height > 0;
@@ -480,7 +486,7 @@ const siblingPosition = (context: LayerContextActionState): { index: number; cou
}
const parent = entry.parentId === null ? null : index.byId.get(entry.parentId)!.node;
const count =
- parent && parent.type === 'group' ? parent.children.length : context.document.stacks[entry.stack].length;
+ parent && parent.type === 'group' ? parent.children.length : (context.document.stacks[entry.stack]?.length ?? 0);
return { count, index: entry.siblingIndex };
};
@@ -620,7 +626,7 @@ export const LAYER_CONTEXT_ACTION_DEFINITIONS: readonly LayerContextActionDefini
labelKey: 'widgets.layers.actions.transform',
order: 10,
section: 'primary',
- supportedLayerTypes: ['raster', 'control', 'inpaint_mask', 'regional_guidance'],
+ supportedLayerTypes: ['raster', 'control', 'vector', 'inpaint_mask', 'regional_guidance'],
},
{
defaultLabel: 'Rename',
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.ts
index 4b21956236..d7e0289be0 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.ts
@@ -28,6 +28,7 @@ export interface LayerContextMenuGroupLayout {
}
type LayerContextMenuLayerLabelKey =
+ | 'widgets.layers.types.vector'
| 'widgets.canvas.import.control'
| 'widgets.canvas.import.inpaintMask'
| 'widgets.canvas.import.raster'
@@ -126,6 +127,8 @@ export const getLayerContextMenuGroupLayout = (
/** Resolves the singular layer labels used by the legacy canvas context menu. */
export const getLayerContextMenuLayerLabelKey = (type: LayerType): LayerContextMenuLayerLabelKey => {
switch (type) {
+ case 'vector':
+ return 'widgets.layers.types.vector';
case 'control':
return 'widgets.canvas.import.control';
case 'inpaint_mask':
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerRowSummary.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerRowSummary.ts
index e884864ded..cc27e1601e 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerRowSummary.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerRowSummary.ts
@@ -5,6 +5,8 @@ import { getControlImageState } from '@workbench/canvasLayerContent';
export const layerRowSummary = (layer: CanvasLayerContract, t: TFunction): string => {
switch (layer.type) {
+ case 'vector':
+ return t('widgets.layers.summary.vectorPaths', { count: layer.paths.length });
case 'raster': {
const parts = [t(`widgets.layers.types.${layer.source.type === 'image' ? 'image' : layer.source.type}`)];
if (layer.blendMode !== 'normal') {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTreeRows.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTreeRows.ts
index 707e4e818b..1f5e33f39d 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTreeRows.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTreeRows.ts
@@ -77,7 +77,7 @@ export const buildLayerStackRows = (
const kept = filtered?.kept ?? null;
const byId = new Map(nodes.map((node) => [node.id, node]));
const setSizeOf = (node: SemanticNode): number =>
- node.parentId === null ? stacks[node.stack].length : (byId.get(node.parentId)?.childCount ?? 0);
+ node.parentId === null ? (stacks[node.stack]?.length ?? 0) : (byId.get(node.parentId)?.childCount ?? 0);
const result = Object.fromEntries(
LAYER_STACKS_TOP_FIRST.map((stack) => [
stack,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTypeIcon.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTypeIcon.ts
index 7ec5a8a593..955a33980f 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTypeIcon.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTypeIcon.ts
@@ -9,6 +9,7 @@ import {
ImagePlusIcon,
MapPinIcon,
SlidersHorizontalIcon,
+ SplineIcon,
SquareDashedBottomIcon,
SquareIcon,
TypeIcon,
@@ -25,6 +26,7 @@ export const LAYER_KIND_ICONS: Readonly<Record<AddLayerItemId, LucideIcon>> = {
group: FolderPlusIcon,
inpaint_mask: SquareDashedBottomIcon,
raster: BrushIcon,
+ vector: SplineIcon,
regional_guidance: MapPinIcon,
regional_reference_image: ImagePlusIcon,
};
@@ -32,6 +34,8 @@ export const LAYER_KIND_ICONS: Readonly<Record<AddLayerItemId, LucideIcon>> = {
/** The small identity glyph between a row's preview and its name. */
export const layerTypeIcon = (layer: CanvasLayerContract): LucideIcon => {
switch (layer.type) {
+ case 'vector':
+ return LAYER_KIND_ICONS.vector;
case 'raster':
switch (layer.source.type) {
case 'image':
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layersPanel.budget.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layersPanel.budget.test.ts
index 806c05c5b2..0178eff1f0 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layersPanel.budget.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layersPanel.budget.test.ts
@@ -47,7 +47,7 @@ describe(`layers panel budgets over ${NODE_COUNT} nodes`, () => {
expect(Object.values(expanded).reduce((total, stack) => total + stack.rows.length, 0)).toBe(NODE_COUNT);
expect(getDocumentModelDiagnostics().nodesCompiled).toBe(NODE_COUNT);
const flat = flattenPanelRows(expanded, [], () => false);
- expect(flat.filter((row) => row.kind === 'header')).toHaveLength(4);
+ expect(flat.filter((row) => row.kind === 'header')).toHaveLength(5);
expect(flat.filter((row) => row.kind === 'node')).toHaveLength(NODE_COUNT);
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerSection.tsx
index a0f01ed788..c623221604 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerSection.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerSection.tsx
@@ -25,12 +25,16 @@ import { RasterLayerFilterSection } from '@workbench/widgets/layers/RasterLayerF
import { ReferenceImageSettings } from '@workbench/widgets/layers/ReferenceImageSettings';
import { RegionalGuidanceSettings } from '@workbench/widgets/layers/RegionalGuidanceSettings';
import { useActiveProjectId, useActiveProjectSelector } from '@workbench/WorkbenchContext';
-import { useCallback } from 'react';
+import { lazy, Suspense, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { GroupSelectedNotice } from './GroupSelectedNotice';
import { PropertiesSection } from './PropertiesSection';
+const VectorLayerSettings = lazy(() =>
+ import('@workbench/widgets/layers/VectorLayerSettings').then((module) => ({ default: module.VectorLayerSettings }))
+);
+
type LayerSectionEngine = Pick<
CanvasEngineHandle,
'document' | 'exports' | 'interaction' | 'layers' | 'lifecycle' | 'projectId' | 'tools'
@@ -158,7 +162,15 @@ const LayerTypeSettings = ({
engine: LayerSectionEngine | null;
layer: CanvasLayerContract;
}) => {
+ const { t } = useTranslation();
+ const loading = useMemo(() => <Text>{t('common.loading')}</Text>, [t]);
switch (layer.type) {
+ case 'vector':
+ return (
+ <Suspense fallback={loading}>
+ <VectorLayerSettings key={layer.id} engine={engine} layer={layer} />
+ </Suspense>
+ );
case 'inpaint_mask':
return <InpaintMaskSettings key={layer.id} engine={engine} layer={layer} />;
case 'regional_guidance':
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.ts
index 2af16a280b..64af72dae4 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.ts
@@ -58,6 +58,26 @@ export const useAddLayer = (): ((id: AddLayerItemId) => void) => {
model.prepare({ aboveId: model.document.selectedLayerId, nodes: [node], type: 'insert' })
);
switch (id) {
+ case 'vector': {
+ if (!engine) {
+ return;
+ }
+ const document = engine.document.getDocument();
+ void engine.layers.vectorEdit
+ .createLayer({
+ id: createLayerId(),
+ })
+ .then((layer) => {
+ if (
+ layer &&
+ engine.lifecycle.getLifecycleState() === 'active' &&
+ engine.document.getDocument() === document
+ ) {
+ add(t('widgets.layers.actions.addVectorLayer'), layer);
+ }
+ });
+ return;
+ }
case 'group': {
// An empty group has no stack of its own: it joins the selected node's stack, else raster.
const groupId = createLayerId();
@@ -119,6 +139,6 @@ export const useAddLayer = (): ((id: AddLayerItemId) => void) => {
}
}
},
- [base, commitPrepared, layerNames, projectId, regionalGuidanceCount, t]
+ [engine, base, commitPrepared, layerNames, projectId, regionalGuidanceCount, t]
);
};
diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mts
index 0c2a70a82c..a100afd909 100644
--- a/invokeai/frontend/webv2/vite.config.mts
+++ b/invokeai/frontend/webv2/vite.config.mts
@@ -259,6 +259,28 @@ const EDITOR_BOOT_SHARED_MODULES = [
// routes) reach it through the same store, while the Launchpad palette does not. Without the group Rolldown splits it
// by importer set, costing the editor boot one request per piece.
const WORKBENCH_RUNTIME_SHARED_MODULES = [
+ // Layer factories are shared with lazy vector creation; keep the adapter helper in the existing boot request.
+ '/workbench/controlAdapters.ts',
+ // The boot document model and lazy vector runtime share these already-eager primitives.
+ '/workbench/canvas-engine/contracts.ts',
+ '/workbench/canvas-engine/document-model/documentModel.ts',
+ '/workbench/canvas-engine/document-model/postconditions.ts',
+ '/workbench/canvas-engine/document-model/semanticLeaf.ts',
+ '/workbench/canvas-engine/document-model/semanticNode.ts',
+ '/workbench/canvas-engine/document/documentIndex.ts',
+ '/workbench/canvas-engine/document/documentTree.ts',
+ '/workbench/canvas-engine/document/insertionAnchors.ts',
+ '/workbench/canvas-engine/document/layerEligibility.ts',
+ '/workbench/canvas-engine/document/layerStacks.ts',
+ '/workbench/canvas-engine/document/selectionRepair.ts',
+ '/workbench/canvas-engine/document/sources.ts',
+ '/workbench/canvas-engine/layerExportGuards.ts',
+ '/workbench/canvas-engine/math/mat2d.ts',
+ '/workbench/canvas-engine/math/rect.ts',
+ '/workbench/canvas-engine/math/snapping.ts',
+ '/workbench/canvas-engine/mutationContracts.ts',
+ '/workbench/canvas-engine/render/rasterizers/textRasterizer.ts',
+ '/workbench/canvas-engine/transform/transformMath.ts',
'/platform/react/draftRegistry.ts',
'/features/generation/core/projectPromptDraft.ts',
'/features/generation/core/prompt/compel.ts',