Skip to content

AI-native design editor. Open-source Figma alternative.

fix: match Figma's transforms, strokes, booleans, sections, and names (#931)

Danila Poyarkov7992516d816f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f64c881dd..54947c8cb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,7 @@
### Breaking changes
- `SkiaRenderer.hitTestFrameTitle` no longer takes the selected IDs: it finds the name of any frame on the page or in a section under a point, selected or not.
+- `SceneNode` from `@open-pencil/scene-graph` has `strokeWeight` and `strokeAlign`, the stroke weight and alignment a layer keeps without strokes, so code that builds `SceneNode` objects itself must include them. `SECTION_DEFAULT_FILL` from `@open-pencil/core/constants` is replaced by `SECTION_DEFAULT_FILLS`, keyed by interface theme.
- `SceneNode.booleanOperation` is a required key whose value may be `undefined`, like every other scene node field, so code that builds `SceneNode` objects itself must include it.
- `useVariables().collections` from `@open-pencil/vue` returns copies of the document's collections instead of the graph's own objects, so components see modes added or renamed in place; change collections through the editor's actions rather than by mutating the returned objects. `addVariable` returns the new variable's ID.
- `useVariablesEditor`, `useVariablesTable`, and `useVariablesDialogState` are removed from `@open-pencil/vue`, together with the `formatModeValue`, `parseVariableValue`, and `shortName` helpers `useVariables()` returned for them, and the package no longer depends on `@tanstack/vue-table`. Build variable editors on `useVariables()` and the editor's variable actions.
@@ -75,6 +76,11 @@
- The desktop app shows an available update in a Software Update window with formatted, scrollable release notes, a link to the full notes, and download progress you can cancel, instead of a system dialog that showed raw Markdown and could grow taller than the screen (#743). On macOS and Linux the update installs first and you choose when to restart; restarting, and on Windows installing, first asks about unsaved documents as Quit does.
- `openpencil eval` prints the value of a script's last expression, as the `eval` tool and app automation already do, so `-c 'figma.currentPage.children.length'` prints the count without a `return`.
- In scripts, children of groups and booleans report `x`, `y`, and `relativeTransform` in their container's space, as in Figma, and a group refits whenever a script moves, resizes, rotates, adds, or removes one of its children; a group left without children is removed. The canvas and the plugin API share the refit.
+- In scripts, layers turn, move, and resize as in Figma: `rotation` turns a layer counterclockwise about its top-left corner, `x` and `y` are that corner in the parent, `resize()` keeps it in place, `relativeTransform` can be set, and `absoluteBoundingBox` covers the turned layer. `appendChild()` and `insertChild()` keep a layer's `x`, `y`, and rotation in its new parent, so it moves with that parent, instead of keeping its place on the canvas. The AI and MCP `create_shape`, `create_slice`, and vector tools likewise place a layer given a `parent_id` at `x` and `y` inside that parent, and `reparent_node` keeps its position inside the new parent.
+- A layer keeps its stroke weight and alignment without strokes, as in Figma: a weight or alignment set before adding a stroke, or kept after removing them, applies to the next stroke, survives `.fig` export and import, and scales with `rescale()`. `strokeWeight` and `strokeAlign` in scripts apply to every stroke rather than the first, and a stroke added from the panel takes the layer's weight and alignment. New strokes align inside, centered on lines and vectors, and outside text.
+- Boolean operations take the size of the shape they produce, as in Figma, from the canvas and from scripts when a renderer is attached, and refit when an operand moves; an empty result keeps its operands' size.
+- New sections look as in Figma: white, or #444444 in the dark theme, with a faint white outline and 2 px corners, 496 px square from scripts. Sections and component sets are drawn with their own corner radius instead of a fixed 5 px.
+- Layers drawn on the canvas and the groups, frames, and components it wraps layers in are numbered as in Figma, one past the highest number used for that name on the page, as in "Rectangle 2" or "Group 10"; scripts keep plain names.
- Group, Frame selection, Create component, and boolean operations match Figma from the canvas and from scripts, through one shared implementation. From the canvas, the new layer takes the topmost selected layer's place in the layer list, Frame selection adds no fill and does not clip, a component wrapped around layers is white and takes a single layer's name, and a boolean is filled like its topmost operand, or its base for Subtract, without strokes. In scripts, `figma.ungroup()` leaves the children in the group's place instead of moving them to the top, booleans are named Union, Subtract, Intersect, or Exclude with the default grey fill, and `figma.createComponentFromNode()` turns a frame or group into a component that keeps its children instead of copying them, and wraps any other layer. Undoing a group or boolean returns each layer to its own place in the layer list.
- Combine as variants matches Figma: the set pads its variants by 20 px and has a dashed purple stroke instead of a grey fill and 40 px of padding, and `figma.combineAsVariants()` in scripts wraps the components exactly with no fill or stroke, as Figma's plugin API does. Both share one implementation.
- New layers start as in Figma, whether drawn or created by a script: frames are white and clip their content, components are white, shapes are #D9D9D9, and lines and vectors get a black 1 px stroke. The Line tool draws a line from the start point to the cursor by its length and angle, as in Figma, instead of an invisible box, and Shift snaps it to 45° steps. A stroke a script adds through the plugin API now gets Figma's 1 px default weight instead of none.
diff --git a/packages/core/src/canvas/boolean.ts b/packages/core/src/canvas/boolean.ts
index d6ba34127..45389bc27 100644
--- a/packages/core/src/canvas/boolean.ts
+++ b/packages/core/src/canvas/boolean.ts
@@ -1,6 +1,6 @@
import type { Canvas, Path, PathBuilder, PathOp } from 'canvaskit-wasm'
-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import type { GroupFitOptions, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { getTextOutlineSupport } from '#core/text/outlines'
@@ -295,6 +295,30 @@ export function makeBooleanOperationPath(
return result
}
+/**
+ * Measures boolean operations for the group refit: the tight box of the combined shape in the
+ * parent's space, which Figma sizes a boolean to, or null for an empty result, which keeps the
+ * operands' box as Figma does.
+ */
+export function booleanResultBounds(
+ r: SkiaRenderer,
+ graph: SceneGraph
+): NonNullable<GroupFitOptions['booleanBounds']> {
+ return (node) => {
+ const path = makeBooleanOperationPath(r, node, graph)
+ if (!path) return null
+ const [left, top, right, bottom] = path.computeTightBounds()
+ path.delete()
+ if (right <= left && bottom <= top) return null
+ return { x: node.x + left, y: node.y + top, width: right - left, height: bottom - top }
+ }
+}
+
+/** Group refit options that size booleans to their result when a renderer can measure it. */
+export function groupFitOptions(r: SkiaRenderer | null, graph: SceneGraph): GroupFitOptions {
+ return r ? { booleanBounds: booleanResultBounds(r, graph) } : {}
+}
+
export function renderBooleanOperation(
r: SkiaRenderer,
canvas: Canvas,
diff --git a/packages/core/src/canvas/scene.ts b/packages/core/src/canvas/scene.ts
index 1471a8b11..9cb6256e0 100644
--- a/packages/core/src/canvas/scene.ts
+++ b/packages/core/src/canvas/scene.ts
@@ -12,7 +12,11 @@ import { computeDescendantVisualBounds } from '@open-pencil/scene-graph/geometry
import Matrix from '@open-pencil/scene-graph/matrix'
import type { Color } from '@open-pencil/scene-graph/primitives'
-import { DROP_HIGHLIGHT_ALPHA, DROP_HIGHLIGHT_STROKE, SECTION_CORNER_RADIUS } from '#core/constants'
+import {
+ COMPONENT_SET_OUTLINE_RADIUS,
+ DROP_HIGHLIGHT_ALPHA,
+ DROP_HIGHLIGHT_STROKE
+} from '#core/constants'
import { createSceneGeometry, nodeOrientationMatrix, projectedNode } from '#core/geometry'
import { transformTextCase } from '#core/text/case'
import { fontManager } from '#core/text/fonts'
@@ -436,7 +440,7 @@ export function renderSection(
node: SceneNode,
graph: SceneGraph
): void {
- const rrect = makeNodeRRect(r, node, SECTION_CORNER_RADIUS)
+ const rrect = makeNodeRRect(r, node, node.cornerRadius)
drawVisibleFills(r, node, graph, () => canvas.drawRRect(rrect, r.fillPaint))
@@ -454,7 +458,7 @@ export function renderComponentSet(
node: SceneNode,
graph: SceneGraph
): void {
- const rrect = makeNodeRRect(r, node, 5)
+ const rrect = makeNodeRRect(r, node, node.cornerRadius)
drawVisibleFills(r, node, graph, () => canvas.drawRRect(rrect, r.fillPaint))
@@ -463,7 +467,16 @@ export function renderComponentSet(
forVisibleStrokes(r, node, graph, (stroke, color) => {
const dashPhase = stroke.dashPattern?.[1] ?? 0
if (stroke.dashPattern && stroke.dashPattern.length > 0) {
- drawDashedRRectWithSolidCorners(r, canvas, node, stroke, color, 5, dashPhase)
+ drawDashedRRectWithSolidCorners(
+ r,
+ canvas,
+ node,
+ stroke,
+ color,
+ // Skia fits a rounded rect's radii to its bounds; the dashed outline must match the fill.
+ Math.min(node.cornerRadius, node.width / 2, node.height / 2),
+ dashPhase
+ )
} else {
drawStyledRRectStroke(r, canvas, rrect, node, stroke, color, dashPhase)
}
@@ -476,7 +489,7 @@ export function renderComponentSet(
r.auxStroke.setPathEffect(
r.ck.PathEffect.MakeDash([r.COMPONENT_SET_DASH / r.zoom, r.COMPONENT_SET_DASH_GAP / r.zoom], 0)
)
- canvas.drawRRect(rrect, r.auxStroke)
+ canvas.drawRRect(makeNodeRRect(r, node, COMPONENT_SET_OUTLINE_RADIUS), r.auxStroke)
r.auxStroke.setPathEffect(null)
}
diff --git a/packages/core/src/constants.ts b/packages/core/src/constants.ts
index 5fb02a005..8d0997c18 100644
--- a/packages/core/src/constants.ts
+++ b/packages/core/src/constants.ts
@@ -74,7 +74,6 @@ export const DEFAULT_FONT_FAMILY = 'Inter'
export const DEFAULT_FONT_SIZE = 14
export const DEFAULT_STROKE_MITER_LIMIT = 4
/** Figma's stroke weight for a node that has not been given one. */
-export const DEFAULT_STROKE_WEIGHT = 1
export const LABEL_FONT_SIZE = 11
export const SIZE_FONT_SIZE = 10
@@ -114,7 +113,6 @@ export const AUTO_LAYOUT_HOVER_BLUE_FILL = { r: 0.28, g: 0.64, b: 1, a: 0.1 } sa
export const AUTO_LAYOUT_HOVER_MAGENTA = { r: 1, g: 0.32, b: 0.68, a: 0.78 } satisfies Color
export const AUTO_LAYOUT_HOVER_MAGENTA_FILL = { r: 1, g: 0.32, b: 0.68, a: 0.1 } satisfies Color
-export const SECTION_CORNER_RADIUS = 5
export const SECTION_TITLE_HEIGHT = 24
export const SECTION_TITLE_PADDING_X = 6
export const SECTION_TITLE_RADIUS = 5
@@ -125,6 +123,8 @@ export const SECTION_HOVER_STROKE_WIDTH = 2
export const COMPONENT_SET_DASH = 6
export const COMPONENT_SET_DASH_GAP = 4
export const COMPONENT_SET_BORDER_WIDTH = 1.5
+/** Corners of the outline the editor draws around a component set with no strokes of its own. */
+export const COMPONENT_SET_OUTLINE_RADIUS = 5
export const COMPONENT_LABEL_FONT_SIZE = 11
export const COMPONENT_LABEL_GAP = 6
export const COMPONENT_LABEL_ICON_SIZE = 10
@@ -523,22 +523,31 @@ export const DEFAULT_FRAME_FILL: Fill = {
visible: true
}
-export const SECTION_DEFAULT_FILL: Fill = {
- type: 'SOLID',
- color: { r: 0.37, g: 0.37, b: 0.37, a: 1 },
- opacity: 1,
- visible: true
+/** The light or dark interface a new section takes its fill from, as in Figma. */
+export type InterfaceTheme = 'light' | 'dark'
+
+/** A new section's fill, which Figma picks from the interface theme it was made in. */
+export const SECTION_DEFAULT_FILLS: Record<InterfaceTheme, Fill> = {
+ light: { type: 'SOLID', color: { r: 1, g: 1, b: 1, a: 1 }, opacity: 1, visible: true },
+ dark: {
+ type: 'SOLID',
+ color: { r: 0x44 / 255, g: 0x44 / 255, b: 0x44 / 255, a: 1 },
+ opacity: 1,
+ visible: true
+ }
}
export const SECTION_DEFAULT_STROKE: Stroke = {
type: 'SOLID',
- color: { r: 0.55, g: 0.55, b: 0.55, a: 1 },
+ color: { r: 1, g: 1, b: 1, a: 1 },
weight: 1,
- opacity: 1,
+ opacity: 0.1,
visible: true,
align: 'INSIDE'
}
+export const SECTION_CORNER_RADIUS = 2
+
export const ZOOM_DIVISOR = 50
export const ZOOM_SCALE_MIN = 0.75
export const ZOOM_SCALE_MAX = 1.25
diff --git a/packages/core/src/editor/shapes.ts b/packages/core/src/editor/shapes.ts
index 594670be7..cf18bdc31 100644
--- a/packages/core/src/editor/shapes.ts
+++ b/packages/core/src/editor/shapes.ts
@@ -5,10 +5,29 @@ import { adoptCoveredLayers } from './shapes/adopt'
import { newLayerDefaults } from './shapes/defaults'
import { createFramePresetActions } from './shapes/frame-presets'
import { createPenActions } from './shapes/pen'
+import { defaultNodeName, nextNumberedName } from './structure/rename'
import type { EditorContext } from './types'
export type { PenDragOptions } from './shapes/pen'
+/** Layers Figma numbers when drawn, as "Rectangle 1"; others keep their type's name. */
+const NUMBERED_WHEN_DRAWN: ReadonlySet<NodeType> = new Set([
+ 'FRAME',
+ 'SECTION',
+ 'RECTANGLE',
+ 'ELLIPSE',
+ 'LINE',
+ 'POLYGON',
+ 'STAR'
+])
+
export function createShapeActions(ctx: EditorContext) {
+ function drawnLayerName(type: NodeType): string {
+ const base = defaultNodeName(type)
+ return NUMBERED_WHEN_DRAWN.has(type)
+ ? nextNumberedName(ctx.graph, ctx.state.currentPageId, base)
+ : base
+ }
+
function createShape(
type: NodeType,
x: number,
@@ -24,12 +43,12 @@ export function createShapeActions(ctx: EditorContext) {
throw new Error('Cannot add a layer to the locked part of an instance')
}
const overrides: Partial<SceneNode> = {
- ...newLayerDefaults(type),
+ ...newLayerDefaults(type, ctx.state.theme),
x,
y,
width: w,
height: h,
- ...(name ? { name } : {})
+ name: name ?? drawnLayerName(type)
}
const node = ctx.graph.createNode(type, pid, overrides)
const id = node.id
diff --git a/packages/core/src/editor/shapes/defaults.ts b/packages/core/src/editor/shapes/defaults.ts
index 77e60c44c..2c82be652 100644
--- a/packages/core/src/editor/shapes/defaults.ts
+++ b/packages/core/src/editor/shapes/defaults.ts
@@ -1,13 +1,15 @@
import type { Fill, NodeType, SceneNode, Stroke } from '@open-pencil/scene-graph'
+import { DEFAULT_STROKE_WEIGHT } from '@open-pencil/scene-graph'
import { copyFills, copyStrokes } from '@open-pencil/scene-graph/copy'
import {
BLACK,
DEFAULT_FRAME_FILL,
DEFAULT_SHAPE_FILL,
- DEFAULT_STROKE_WEIGHT,
- SECTION_DEFAULT_FILL,
- SECTION_DEFAULT_STROKE
+ SECTION_CORNER_RADIUS,
+ SECTION_DEFAULT_FILLS,
+ SECTION_DEFAULT_STROKE,
+ type InterfaceTheme
} from '#core/constants'
const BLACK_FILL: Fill = { type: 'SOLID', color: BLACK, opacity: 1, visible: true }
@@ -16,9 +18,12 @@ const BLACK_STROKE: Stroke = { ...BLACK_FILL, weight: DEFAULT_STROKE_WEIGHT, ali
/**
* What a new layer starts with, as Figma gives it from a drawing tool and from the plugin API:
* frames and components white (frames clipping their content), shapes light grey, lines and
- * vectors a black 1 px stroke, and text black.
+ * vectors a black 1 px stroke, text black, and sections filled for the interface `theme`.
*/
-export function newLayerDefaults(type: NodeType): Partial<SceneNode> {
+export function newLayerDefaults(
+ type: NodeType,
+ theme: InterfaceTheme = 'light'
+): Partial<SceneNode> {
switch (type) {
case 'FRAME':
return { fills: copyFills([DEFAULT_FRAME_FILL]), clipsContent: true }
@@ -26,9 +31,9 @@ export function newLayerDefaults(type: NodeType): Partial<SceneNode> {
return { fills: copyFills([DEFAULT_FRAME_FILL]) }
case 'SECTION':
return {
- fills: copyFills([SECTION_DEFAULT_FILL]),
+ fills: copyFills([SECTION_DEFAULT_FILLS[theme]]),
strokes: copyStrokes([SECTION_DEFAULT_STROKE]),
- cornerRadius: 5
+ cornerRadius: SECTION_CORNER_RADIUS
}
case 'RECTANGLE':
case 'ELLIPSE':
diff --git a/packages/core/src/editor/structure/boolean.ts b/packages/core/src/editor/structure/boolean.ts
index b50e0644d..7d662133f 100644
--- a/packages/core/src/editor/structure/boolean.ts
+++ b/packages/core/src/editor/structure/boolean.ts
@@ -1,7 +1,14 @@
-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import {
+ fitEnclosingGroups,
+ undoGroupFit,
+ type GroupFit,
+ type GroupFitOptions,
+ type SceneGraph,
+ type SceneNode
+} from '@open-pencil/scene-graph'
import { copyFills } from '@open-pencil/scene-graph/copy'
-import { canMakeBooleanSourceNode } from '#core/canvas/boolean'
+import { canMakeBooleanSourceNode, groupFitOptions } from '#core/canvas/boolean'
import { restoreSubtree, snapshotSubtree } from '#core/editor/clipboard/subtree-history'
import { newLayerDefaults } from '#core/editor/shapes/defaults'
import type { EditorContext } from '#core/editor/types'
@@ -14,6 +21,7 @@ export type BooleanOperation = 'UNION' | 'SUBTRACT' | 'INTERSECT' | 'EXCLUDE'
/**
* Wraps sibling layers in a boolean operation named after it, as Figma names one from the canvas
* and from the plugin API. Shared by the editor command and the plugin API; `props` gives the look.
+ * Returns the refit of the boolean and the groups around it too, so undo can reverse it.
*/
export function createBooleanOperation(
graph: SceneGraph,
@@ -21,13 +29,17 @@ export function createBooleanOperation(
parentId: string,
operation: BooleanOperation,
index: number | undefined,
- props: Partial<SceneNode> = {}
-): SceneNode {
- return wrapNodes(graph, 'BOOLEAN_OPERATION', nodes, parentId, index, {
+ props: Partial<SceneNode> = {},
+ fitOptions: GroupFitOptions = {}
+): { node: SceneNode; fit: GroupFit | null } {
+ const node = wrapNodes(graph, 'BOOLEAN_OPERATION', nodes, parentId, index, {
name: operationLabel(operation),
booleanOperation: operation,
...props
})
+ // Figma sizes a boolean to its result, and the groups around it follow.
+ const fit = fitEnclosingGroups(graph, [node.id], fitOptions)
+ return { node, fit }
}
/**
@@ -68,29 +80,37 @@ export function booleanOperationSelected(
index: parent.childIds.indexOf(node.id)
}))
const index = canvasWrapIndex(parent, operands)
- const booleanNode = createBooleanOperation(
+ const { node: booleanNode, fit: createdFit } = createBooleanOperation(
ctx.graph,
operands,
parentId,
operation,
index,
- booleanOperationPaints(operation, operands, 'canvas')
+ booleanOperationPaints(operation, operands, 'canvas'),
+ groupFitOptions(ctx.getRenderer(), ctx.graph)
)
const booleanId = booleanNode.id
+ let fit = createdFit
ctx.setSelectedIds(new Set([booleanId]))
ctx.undo.push({
label: operationLabel(operation),
forward: () => {
const nodes = origPositions.flatMap((pos) => ctx.graph.getNode(pos.id) ?? [])
- createBooleanOperation(ctx.graph, nodes, parentId, operation, index, {
- ...booleanNode,
- childIds: [],
- id: booleanId
- })
+ fit = createBooleanOperation(
+ ctx.graph,
+ nodes,
+ parentId,
+ operation,
+ index,
+ { ...booleanNode, childIds: [], id: booleanId },
+ groupFitOptions(ctx.getRenderer(), ctx.graph)
+ ).fit
ctx.setSelectedIds(new Set([booleanId]))
},
inverse: () => {
+ // The groups around the boolean go back first, so the operands' places mean what they did.
+ if (fit) undoGroupFit(ctx.graph, fit)
for (const { id, subtree } of childSnapshots) {
const root = subtree.get(id)
if (!root) continue
diff --git a/packages/core/src/editor/structure/container-wrap.ts b/packages/core/src/editor/structure/container-wrap.ts
index 64ff13e84..ec28e030e 100644
--- a/packages/core/src/editor/structure/container-wrap.ts
+++ b/packages/core/src/editor/structure/container-wrap.ts
@@ -2,6 +2,7 @@ import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { getAxisAlignedBoundsInParent } from '@open-pencil/scene-graph/coordinate'
import { prepareSlotEdits } from '#core/editor/components/slots'
+import { nextNumberedName } from '#core/editor/structure/rename'
import type { EditorContext } from '#core/editor/types'
export type WrapContainerType =
@@ -19,6 +20,12 @@ const CONTAINER_NAMES: Record<WrapContainerType, string> = {
FRAME: 'Frame'
}
+const NUMBERED_WHEN_WRAPPED: ReadonlySet<WrapContainerType> = new Set([
+ 'GROUP',
+ 'FRAME',
+ 'COMPONENT'
+])
+
/**
* The parent these layers share when a new container may go there, or null when they are not
* siblings or sit in the locked part of an instance.
@@ -93,14 +100,14 @@ export function wrapSelectionInContainer(
.toSorted((a, b) => a.index - b.index)
const index = canvasWrapIndex(parent, selectedNodes)
- const containerNode = wrapNodes(
- ctx.graph,
- containerType,
- selectedNodes,
- parentId,
- index,
- extraProps
- )
+ // Figma numbers a group, frame, or component the canvas wraps layers in, as "Group 1".
+ const name = NUMBERED_WHEN_WRAPPED.has(containerType)
+ ? nextNumberedName(ctx.graph, ctx.state.currentPageId, CONTAINER_NAMES[containerType])
+ : undefined
+ const containerNode = wrapNodes(ctx.graph, containerType, selectedNodes, parentId, index, {
+ ...(name ? { name } : {}),
+ ...extraProps
+ })
const containerId = containerNode.id
ctx.setSelectedIds(new Set([containerId]))
diff --git a/packages/core/src/editor/structure/group-bounds.ts b/packages/core/src/editor/structure/group-bounds.ts
index 145b4c43e..61f6733e3 100644
--- a/packages/core/src/editor/structure/group-bounds.ts
+++ b/packages/core/src/editor/structure/group-bounds.ts
@@ -1,5 +1,6 @@
import { fitEnclosingGroups, redoGroupFit, undoGroupFit } from '@open-pencil/scene-graph'
+import { groupFitOptions } from '#core/canvas/boolean'
import type { EditorContext } from '#core/editor/types'
/**
@@ -7,7 +8,11 @@ import type { EditorContext } from '#core/editor/types'
* itself is shared with the plugin API; see `fitEnclosingGroups` in Scene Graph.
*/
export function fitEnclosingGroupsWithUndo(ctx: EditorContext, parentIds: Iterable<string>) {
- const fit = fitEnclosingGroups(ctx.graph, parentIds)
+ const fit = fitEnclosingGroups(
+ ctx.graph,
+ parentIds,
+ groupFitOptions(ctx.getRenderer(), ctx.graph)
+ )
if (!fit) return
ctx.undo.push({
label: 'Fit groups',
diff --git a/packages/core/src/editor/structure/rename.ts b/packages/core/src/editor/structure/rename.ts
index 0e98dfe57..1de33936d 100644
--- a/packages/core/src/editor/structure/rename.ts
+++ b/packages/core/src/editor/structure/rename.ts
@@ -1,4 +1,6 @@
-import type { NodeType, SceneNode } from '@open-pencil/scene-graph'
+import { escapeRegExp } from 'es-toolkit/string'
+
+import type { NodeType, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
export interface RenameSelectionOptions {
match: string
@@ -16,6 +18,25 @@ export function defaultNodeName(type: NodeType): string {
return words.charAt(0).toUpperCase() + words.slice(1)
}
+/**
+ * The name Figma gives a layer made on the canvas: its base name numbered one past the highest
+ * number any layer on the page already has with it, so "Group 10" follows a "Group 9" anywhere on
+ * the page, whatever that layer is. Scripts get the bare base name instead.
+ */
+export function nextNumberedName(graph: SceneGraph, pageId: string, base: string): string {
+ const pattern = new RegExp(`^${escapeRegExp(base)} (\\d+)$`)
+ let highest = 0
+ const visit = (id: string) => {
+ const node = graph.getNode(id)
+ if (!node) return
+ const number = pattern.exec(node.name)?.[1]
+ if (number) highest = Math.max(highest, Number(number))
+ for (const childId of node.childIds) visit(childId)
+ }
+ for (const childId of graph.getNode(pageId)?.childIds ?? []) visit(childId)
+ return `${base} ${highest + 1}`
+}
+
function numberedReplacement(
replacement: string,
index: number,
diff --git a/packages/core/src/editor/types.ts b/packages/core/src/editor/types.ts
index 2419c8e6e..9abb0bc0c 100644
--- a/packages/core/src/editor/types.ts
+++ b/packages/core/src/editor/types.ts
@@ -17,6 +17,7 @@ import type { GuideOverlayState } from '#core/canvas/guides/types'
import type { DesignIssueOverlay } from '#core/canvas/issues/types'
import type { RulerTheme, SkiaRenderer } from '#core/canvas/renderer'
import type { MeasurementMode, PresenceCursor, RenderOverlays } from '#core/canvas/renderer/types'
+import type { InterfaceTheme } from '#core/constants'
import type { PlayState } from '#core/editor/play/actions'
import type { SnappingPreferences } from '#core/editor/preferences'
import type { RotationPreview } from '#core/geometry'
@@ -46,6 +47,8 @@ export interface EditorSharedState {
/** The layer of the code element around the cursor in a code editor, shown in every pane. */
codeFocusNodeId: string | null
rulerTheme?: RulerTheme
+ /** The interface theme new sections take their fill from; light when unset. */
+ theme?: InterfaceTheme
sceneVersion: number
}
diff --git a/packages/core/src/figma-api/accessor-utils.ts b/packages/core/src/figma-api/accessor-utils.ts
index b2eb5e514..980c34cab 100644
--- a/packages/core/src/figma-api/accessor-utils.ts
+++ b/packages/core/src/figma-api/accessor-utils.ts
@@ -3,9 +3,10 @@ import {
FITTED_CONTAINER_TYPES,
recordInstanceOverride
} from '@open-pencil/scene-graph'
-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import type { GroupFitOptions, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { assertNodeEditable } from '#core/editor/capabilities'
+import type { NodeProxyHost } from '#core/figma-api/proxy'
export interface NodeProxyInternals {
id: symbol
@@ -46,9 +47,20 @@ const GEOMETRY_FIELDS: ReadonlySet<string> = new Set([
])
/** Refits the groups around a node's parent, as Figma does after a script changes it. */
-export function fitGroupsAround(graph: SceneGraph, parentId: string | null | undefined): void {
+export function fitGroupsAround(
+ graph: SceneGraph,
+ parentId: string | null | undefined,
+ options: GroupFitOptions
+): void {
const parent = parentId ? graph.getNode(parentId) : undefined
- if (parent && FITTED_CONTAINER_TYPES.has(parent.type)) fitEnclosingGroups(graph, [parent.id])
+ if (parent && FITTED_CONTAINER_TYPES.has(parent.type)) {
+ fitEnclosingGroups(graph, [parent.id], options)
+ }
+}
+
+/** Refit options of the API a proxy belongs to. */
+export function hostFitOptions(target: ProxyThis, internals: NodeProxyInternals): GroupFitOptions {
+ return (target[internals.api] as NodeProxyHost).groupFitOptions
}
export function updateNode(
@@ -68,6 +80,6 @@ export function updateNode(
g.updateNode(id, applied)
recordInstanceOverride(g, id, Object.keys(applied))
if (Object.keys(applied).some((key) => GEOMETRY_FIELDS.has(key))) {
- fitGroupsAround(g, g.getNode(id)?.parentId)
+ fitGroupsAround(g, g.getNode(id)?.parentId, hostFitOptions(target, internals))
}
}
diff --git a/packages/core/src/figma-api/accessors/basic.ts b/packages/core/src/figma-api/accessors/basic.ts
index 05c092338..602c0a9cb 100644
--- a/packages/core/src/figma-api/accessors/basic.ts
+++ b/packages/core/src/figma-api/accessors/basic.ts
@@ -1,22 +1,23 @@
import {
- getNodeLocalMatrix,
- getParentToContainerMatrix,
+ getAxisAlignedWorldBounds,
getWorldMatrix,
FITTED_CONTAINER_TYPES,
TRANSFORM_FIELDS as NODE_TRANSFORM_FIELDS,
findInstanceAncestor,
+ recordInstanceOverride,
rescaleNodeTree,
slotPropertyId,
type SceneGraph,
type SceneNode
} from '@open-pencil/scene-graph'
-import Matrix from '@open-pencil/scene-graph/matrix'
-import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'
+import type { Mat3 } from '@open-pencil/scene-graph/matrix'
+import type { Rect } from '@open-pencil/scene-graph/primitives'
import { assertNodeEditable } from '#core/editor/capabilities'
import {
fitGroupsAround,
graph,
+ hostFitOptions,
nodeId,
raw,
updateNode,
@@ -25,6 +26,13 @@ import {
} from '#core/figma-api/accessor-utils'
import type { NodeProxyHost } from '#core/figma-api/proxy'
import { computeAbsoluteRenderBounds } from '#core/figma-api/render-bounds'
+import {
+ containerTransform,
+ figmaRotation,
+ setContainerTransform,
+ withFigmaRotation,
+ withOrigin
+} from '#core/figma-api/transform'
import type { FigmaTransform } from '#core/figma-api/types'
const TRANSFORM_FIELDS: ReadonlySet<string> = new Set(NODE_TRANSFORM_FIELDS)
@@ -59,30 +67,21 @@ function inGroup(node: SceneNode, scene: SceneGraph): boolean {
return parent !== undefined && FITTED_CONTAINER_TYPES.has(parent.type)
}
-/** Where Figma's plugin API places a node: in its container's space, looking through groups. */
-function containerPosition(node: SceneNode, scene: SceneGraph): Vector {
- const [x, y] = Matrix.mapPoints(getParentToContainerMatrix(node, scene), [node.x, node.y])
- return { x, y }
-}
-
-function setPosition(
+/**
+ * Moves, turns, or resizes a node as Figma's plugin API does: its transform into its container
+ * keeps whatever `change` leaves of it, so the top-left corner stays put unless moved, and the
+ * groups around it refit.
+ */
+function setTransform(
target: ProxyThis,
internals: NodeProxyInternals,
- axis: 'x' | 'y',
- value: number
+ change: (matrix: Mat3) => Mat3
) {
assertEditable(target, internals)
const scene = graph(target, internals)
const node = raw(target, internals)
- if (!inGroup(node, scene)) {
- scene.updateNode(node.id, { [axis]: value })
- return
- }
- const desired = { ...containerPosition(node, scene), [axis]: value }
- const toParent = Matrix.invert(getParentToContainerMatrix(node, scene)) ?? Matrix.identity()
- const [x, y] = Matrix.mapPoints(toParent, [desired.x, desired.y])
- scene.updateNode(node.id, { x, y })
- fitGroupsAround(scene, node.parentId)
+ setContainerTransform(scene, node, change(containerTransform(node, scene)))
+ fitGroupsAround(scene, node.parentId, hostFitOptions(target, internals))
}
export function installBasicNodeProxyAccessors(
@@ -114,20 +113,21 @@ export function installBasicNodeProxyAccessors(
return !graph(this, internals).getNode(nodeId(this, internals))
}
},
+ // Figma places a node by its top-left corner in its container, wherever rotation takes it.
x: {
get(this: ProxyThis): number {
- return containerPosition(raw(this, internals), graph(this, internals)).x
+ return containerTransform(raw(this, internals), graph(this, internals))[2]
},
set(this: ProxyThis, value: number) {
- setPosition(this, internals, 'x', value)
+ setTransform(this, internals, (matrix) => withOrigin(matrix, value, matrix[5]))
}
},
y: {
get(this: ProxyThis): number {
- return containerPosition(raw(this, internals), graph(this, internals)).y
+ return containerTransform(raw(this, internals), graph(this, internals))[5]
},
set(this: ProxyThis, value: number) {
- setPosition(this, internals, 'y', value)
+ setTransform(this, internals, (matrix) => withOrigin(matrix, matrix[2], value))
}
},
width: {
@@ -147,13 +147,11 @@ export function installBasicNodeProxyAccessors(
if (sourceTransform && preservesRawTransform(node)) {
return Math.atan2(-sourceTransform.m10, sourceTransform.m00) * (180 / Math.PI)
}
- return node.rotation
+ return figmaRotation(containerTransform(node, graph(this, internals)))
},
+ // Figma turns a node counterclockwise about its top-left corner.
set(this: ProxyThis, value: number) {
- assertEditable(this, internals)
- const scene = graph(this, internals)
- scene.updateNode(nodeId(this, internals), { rotation: value })
- fitGroupsAround(scene, raw(this, internals).parentId)
+ setTransform(this, internals, (matrix) => withFigmaRotation(matrix, value))
}
},
relativeTransform: {
@@ -161,11 +159,7 @@ export function installBasicNodeProxyAccessors(
const node = raw(this, internals)
const scene = graph(this, internals)
// Children of groups report a transform into the container, as Figma does.
- if (inGroup(node, scene)) {
- return figmaTransform(
- Matrix.multiply(getParentToContainerMatrix(node, scene), getNodeLocalMatrix(node))
- )
- }
+ if (inGroup(node, scene)) return figmaTransform(containerTransform(node, scene))
const sourceTransform = node.source.fig.rawTransform
if (sourceTransform && preservesRawTransform(node)) {
return figmaTransform([
@@ -177,7 +171,11 @@ export function installBasicNodeProxyAccessors(
sourceTransform.m12
])
}
- return figmaTransform(getNodeLocalMatrix(node))
+ return figmaTransform(containerTransform(node, scene))
+ },
+ set(this: ProxyThis, value: FigmaTransform) {
+ const [[a, b, x], [c, d, y]] = value
+ setTransform(this, internals, () => [a, b, x, c, d, y, 0, 0, 1])
}
},
absoluteTransform: {
@@ -187,7 +185,7 @@ export function installBasicNodeProxyAccessors(
},
absoluteBoundingBox: {
get(this: ProxyThis): Rect {
- return graph(this, internals).getAbsoluteBounds(nodeId(this, internals))
+ return getAxisAlignedWorldBounds(raw(this, internals), graph(this, internals))
}
},
absoluteRenderBounds: {
@@ -198,8 +196,16 @@ export function installBasicNodeProxyAccessors(
})
Object.assign(prototype, {
+ // A resized node keeps its top-left corner, as Figma's does, though it turns about its center.
+ // The groups around it refit once, after the corner is back in place.
resize(this: ProxyThis, width: number, height: number): void {
- updateNode(this, internals, { width, height })
+ assertEditable(this, internals)
+ const scene = graph(this, internals)
+ const node = raw(this, internals)
+ const before = containerTransform(node, scene)
+ scene.updateNode(node.id, { width, height })
+ recordInstanceOverride(scene, node.id, ['width', 'height'])
+ setTransform(this, internals, () => before)
},
resizeWithoutConstraints(this: ProxyThis, width: number, height: number): void {
;(this as { resize(width: number, height: number): void }).resize(width, height)
diff --git a/packages/core/src/figma-api/accessors/strokes.ts b/packages/core/src/figma-api/accessors/strokes.ts
index 345ec570f..9b2852ec0 100644
--- a/packages/core/src/figma-api/accessors/strokes.ts
+++ b/packages/core/src/figma-api/accessors/strokes.ts
@@ -1,6 +1,5 @@
-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import { newStrokeGeometry, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
-import { DEFAULT_STROKE_WEIGHT } from '#core/constants'
import {
nodeId,
raw,
@@ -9,9 +8,9 @@ import {
type ProxyThis
} from '#core/figma-api/accessor-utils'
import {
- setFirstStrokeAlign,
- setFirstStrokeWeight,
- setIndependentStrokeWeight
+ setIndependentStrokeWeight,
+ setStrokeAlign,
+ setStrokeWeight
} from '#core/figma-api/strokes'
type IndependentWeightField =
@@ -40,22 +39,21 @@ export function installStrokeNodeProxyAccessors(
internals: NodeProxyInternals
): void {
Object.defineProperties(prototype, {
+ // Figma keeps stroke weight and alignment on the node, with or without strokes.
strokeWeight: {
get(this: ProxyThis): number {
- // Figma reports its default weight of 1 for a node without strokes.
- return raw(this, internals).strokes[0]?.weight ?? DEFAULT_STROKE_WEIGHT
+ return newStrokeGeometry(raw(this, internals)).weight
},
set(this: ProxyThis, value: number) {
- setFirstStrokeWeight(graph(this, internals), raw(this, internals), value)
+ setStrokeWeight(graph(this, internals), raw(this, internals), value)
}
},
strokeAlign: {
get(this: ProxyThis): string {
- const strokes = raw(this, internals).strokes
- return strokes.length > 0 ? strokes[0].align : 'INSIDE'
+ return newStrokeGeometry(raw(this, internals)).align
},
- set(this: ProxyThis, value: string) {
- setFirstStrokeAlign(graph(this, internals), raw(this, internals), value)
+ set(this: ProxyThis, value: SceneNode['strokeAlign']) {
+ setStrokeAlign(graph(this, internals), raw(this, internals), value)
}
},
dashPattern: {
diff --git a/packages/core/src/figma-api/accessors/visual.ts b/packages/core/src/figma-api/accessors/visual.ts
index 98ca8ddf4..ef303d612 100644
--- a/packages/core/src/figma-api/accessors/visual.ts
+++ b/packages/core/src/figma-api/accessors/visual.ts
@@ -1,8 +1,7 @@
-import type { Fill, SceneNode, Stroke } from '@open-pencil/scene-graph'
+import { newStrokeGeometry, type Fill, type SceneNode, type Stroke } from '@open-pencil/scene-graph'
import { normalizeColor } from '@open-pencil/scene-graph/color'
import { copyFills, copyStrokes } from '@open-pencil/scene-graph/copy'
-import { DEFAULT_STROKE_WEIGHT } from '#core/constants'
import {
raw,
updateNode,
@@ -58,16 +57,30 @@ export function installVisualNodeProxyAccessors(
get(this: ProxyThis): readonly Stroke[] {
return Object.freeze(copyStrokes(raw(this, internals).strokes))
},
- // Figma paints carry no weight; a stroke takes the node's weight, 1 until one is set.
- set(this: ProxyThis, value: readonly (Omit<Stroke, 'weight'> & { weight?: number })[]) {
- const weight = raw(this, internals).strokes[0]?.weight ?? DEFAULT_STROKE_WEIGHT
+ // Figma paints carry no geometry; a stroke takes the node's weight and alignment, which
+ // outlast its strokes.
+ set(
+ this: ProxyThis,
+ value: readonly (Omit<Stroke, 'weight' | 'align'> &
+ Partial<Pick<Stroke, 'weight' | 'align'>>)[]
+ ) {
+ const geometry = newStrokeGeometry(raw(this, internals))
+ const strokes = value.map((stroke) => ({
+ ...stroke,
+ ...paintDefaults(stroke),
+ weight: stroke.weight ?? geometry.weight,
+ align: stroke.align ?? geometry.align,
+ color: normalizeColor(stroke.color)
+ }))
+ const kept = newStrokeGeometry({
+ strokes,
+ strokeWeight: geometry.weight,
+ strokeAlign: geometry.align
+ })
updateNode(this, internals, {
- strokes: value.map((stroke) => ({
- ...stroke,
- ...paintDefaults(stroke),
- weight: stroke.weight ?? weight,
- color: normalizeColor(stroke.color)
- }))
+ strokes,
+ strokeWeight: kept.weight,
+ strokeAlign: kept.align
})
}
},
diff --git a/packages/core/src/figma-api/index.ts b/packages/core/src/figma-api/index.ts
index cd0e202db..549b63895 100644
--- a/packages/core/src/figma-api/index.ts
+++ b/packages/core/src/figma-api/index.ts
@@ -1,6 +1,7 @@
import { fromUint8Array, isValid, toUint8Array } from 'js-base64'
import type {
+ GroupFitOptions,
SceneGraph,
SceneNode as CoreSceneNode,
NodeType,
@@ -15,9 +16,9 @@ import { computeImageHash } from '@open-pencil/scene-graph/images'
import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'
import type { SkiaRenderer } from '#core/canvas'
-import { canMakeBooleanSourceNode } from '#core/canvas/boolean'
+import { canMakeBooleanSourceNode, groupFitOptions } from '#core/canvas/boolean'
import { flattenNodesToVectorProps } from '#core/canvas/flatten'
-import { IS_BROWSER } from '#core/constants'
+import { IS_BROWSER, type InterfaceTheme } from '#core/constants'
import { newLayerDefaults } from '#core/editor/shapes/defaults'
import { booleanOperationPaints, createBooleanOperation } from '#core/editor/structure/boolean'
import { wrapNodes } from '#core/editor/structure/container-wrap'
@@ -87,6 +88,8 @@ export class FigmaAPI implements NodeProxyHost {
private _nodeCache = new Map<string, FigmaNodeProxy>()
private _pageProxies = new WeakSet<FigmaNodeProxy>()
private _renderer: SkiaRenderer | null = null
+ /** The interface theme new sections take their fill from, as in Figma. */
+ theme: InterfaceTheme = 'light'
readonly mixed = MIXED
@@ -100,6 +103,10 @@ export class FigmaAPI implements NodeProxyHost {
this._renderer = renderer
}
+ get groupFitOptions(): GroupFitOptions {
+ return groupFitOptions(this._renderer, this.graph)
+ }
+
get currentPageId(): string {
return this._currentPageId
}
@@ -156,9 +163,10 @@ export class FigmaAPI implements NodeProxyHost {
/** New layers start as the editor's tools make them, which is how Figma's plugin API makes them. */
private _createNode(type: NodeType): FigmaNodeProxy {
- const defaults = newLayerDefaults(type)
- // Figma's plugin API makes a line 100 wide with no height.
+ const defaults = newLayerDefaults(type, this.theme)
+ // Figma's plugin API makes a line 100 wide with no height, and a section 496 square.
if (type === 'LINE') defaults.height = 0
+ if (type === 'SECTION') Object.assign(defaults, { width: 496, height: 496 })
const node = this.graph.createNode(type, this._currentPageId, defaults)
return this.wrapNode(node.id)
}
@@ -353,13 +361,14 @@ export class FigmaAPI implements NodeProxyHost {
if (nodes.length < 2) throw new Error('Need at least 2 nodes for boolean operation')
const parentId = this._nodeId(parent)
const members = nodes.map((node) => this._rawNode(node))
- const group = createBooleanOperation(
+ const { node: group } = createBooleanOperation(
this.graph,
members,
parentId,
operation,
index,
- booleanOperationPaints(operation, members, 'script')
+ booleanOperationPaints(operation, members, 'script'),
+ this.groupFitOptions
)
return this.wrapNode(group.id) as FigmaBooleanOperationNode
}
diff --git a/packages/core/src/figma-api/proxy.ts b/packages/core/src/figma-api/proxy.ts
index 3d3036124..64ee4d28a 100644
--- a/packages/core/src/figma-api/proxy.ts
+++ b/packages/core/src/figma-api/proxy.ts
@@ -1,5 +1,6 @@
import { recordInstanceOverride, slotPropertyId } from '@open-pencil/scene-graph'
import type {
+ GroupFitOptions,
SceneGraph,
SceneNode,
NodeType,
@@ -39,6 +40,7 @@ import * as PluginData from './plugin-data'
import { nodeProxyToJSON } from './serialization'
import { installSlotAccessors, prepareSlotMove, prepareSlotRemoval } from './slots'
import * as TextProxy from './text'
+import { containerTransform, setContainerTransform } from './transform'
import * as Traversal from './traversal'
import type { FigmaTransform } from './types'
@@ -53,6 +55,8 @@ export const INTERNAL_API = Symbol('api')
export interface NodeProxyHost {
wrapNode(id: string): FigmaNodeProxy
readonly currentPageId: string
+ /** How groups and booleans refit; booleans size to their result when a renderer is attached. */
+ readonly groupFitOptions: GroupFitOptions
}
export { MIXED }
@@ -72,7 +76,7 @@ export class FigmaNodeProxy {
declare readonly width: number
declare readonly height: number
declare rotation: number
- declare readonly relativeTransform: FigmaTransform
+ declare relativeTransform: FigmaTransform
declare resize: (width: number, height: number) => void
declare resizeWithoutConstraints: (width: number, height: number) => void
declare rescale: (scale: number) => void
@@ -290,13 +294,21 @@ export class FigmaNodeProxy {
this._reparentAndFit(child[INTERNAL_ID])
}
- /** Moves a child here, keeping its place on the canvas, and refits the groups it left and joined. */
+ /**
+ * Moves a child here as Figma does: it keeps its transform into its container, so its `x`, `y`,
+ * and rotation stay and it moves with its new parent. The groups it left and joined refit.
+ */
private _reparentAndFit(childId: string): void {
const scene = this[INTERNAL_GRAPH]
- const previousParentId = scene.getNode(childId)?.parentId
+ const child = scene.getNode(childId)
+ if (!child) return
+ const previousParentId = child.parentId
+ const transform = containerTransform(child, scene)
scene.reparentNode(childId, this[INTERNAL_ID])
- fitGroupsAround(scene, previousParentId)
- fitGroupsAround(scene, this[INTERNAL_ID])
+ setContainerTransform(scene, child, transform)
+ const options = this[INTERNAL_API].groupFitOptions
+ fitGroupsAround(scene, previousParentId, options)
+ fitGroupsAround(scene, this[INTERNAL_ID], options)
}
insertChild(index: number, child: FigmaNodeProxy): void {
@@ -328,7 +340,7 @@ export class FigmaNodeProxy {
prepareSlotRemoval(this[INTERNAL_GRAPH], this[INTERNAL_ID])
const parentId = this._raw().parentId
this[INTERNAL_GRAPH].deleteNode(this[INTERNAL_ID])
- fitGroupsAround(this[INTERNAL_GRAPH], parentId)
+ fitGroupsAround(this[INTERNAL_GRAPH], parentId, this[INTERNAL_API].groupFitOptions)
}
findAll(callback?: (node: FigmaNodeProxy) => boolean): FigmaNodeProxy[] {
diff --git a/packages/core/src/figma-api/strokes.ts b/packages/core/src/figma-api/strokes.ts
index 28b912505..5d658d2f4 100644
--- a/packages/core/src/figma-api/strokes.ts
+++ b/packages/core/src/figma-api/strokes.ts
@@ -1,21 +1,26 @@
import { recordInstanceOverride } from '@open-pencil/scene-graph'
import type { SceneGraph, SceneNode, Stroke } from '@open-pencil/scene-graph'
-import { copyStrokes } from '@open-pencil/scene-graph/copy'
+import { copyStroke } from '@open-pencil/scene-graph/copy'
-export function setFirstStrokeWeight(graph: SceneGraph, node: SceneNode, weight: number): void {
- if (node.strokes.length === 0) return
- const strokes = copyStrokes(node.strokes)
- strokes[0].weight = weight
- graph.updateNode(node.id, { strokes })
- recordInstanceOverride(graph, node.id, ['strokes'])
+/**
+ * Sets the weight of all of a node's strokes and the weight it keeps with none, as Figma's
+ * node-level `strokeWeight` does; see `SceneNode.strokeWeight`.
+ */
+export function setStrokeWeight(graph: SceneGraph, node: SceneNode, weight: number): void {
+ graph.updateNode(node.id, {
+ strokeWeight: weight,
+ strokes: node.strokes.map((stroke) => ({ ...copyStroke(stroke), weight }))
+ })
+ recordInstanceOverride(graph, node.id, ['strokes', 'strokeWeight'])
}
-export function setFirstStrokeAlign(graph: SceneGraph, node: SceneNode, align: string): void {
- if (node.strokes.length === 0) return
- const strokes = copyStrokes(node.strokes)
- strokes[0].align = align as Stroke['align']
- graph.updateNode(node.id, { strokes })
- recordInstanceOverride(graph, node.id, ['strokes'])
+/** Sets the alignment of all of a node's strokes and the one it keeps with none. */
+export function setStrokeAlign(graph: SceneGraph, node: SceneNode, align: Stroke['align']): void {
+ graph.updateNode(node.id, {
+ strokeAlign: align,
+ strokes: node.strokes.map((stroke) => ({ ...copyStroke(stroke), align }))
+ })
+ recordInstanceOverride(graph, node.id, ['strokes', 'strokeAlign'])
}
export function setIndependentStrokeWeight(
diff --git a/packages/core/src/figma-api/transform.ts b/packages/core/src/figma-api/transform.ts
new file mode 100644
index 000000000..521690c97
--- /dev/null
+++ b/packages/core/src/figma-api/transform.ts
@@ -0,0 +1,47 @@
+import {
+ getNodeLocalMatrix,
+ getParentToContainerMatrix,
+ localTransformFromWorld,
+ type SceneGraph,
+ type SceneNode
+} from '@open-pencil/scene-graph'
+import Matrix, { type Mat3 } from '@open-pencil/scene-graph/matrix'
+
+/**
+ * A node's transform into its container's space, which Figma's plugin API reports as
+ * `relativeTransform` and reads `x`, `y`, and `rotation` from. Groups and booleans set no space of
+ * their own, so the container is the nearest ancestor that is neither.
+ */
+export function containerTransform(node: SceneNode, scene: SceneGraph): Mat3 {
+ return Matrix.multiply(getParentToContainerMatrix(node, scene), getNodeLocalMatrix(node))
+}
+
+/** Places a node so its transform into its container's space is `matrix`; scale and skew drop. */
+export function setContainerTransform(scene: SceneGraph, node: SceneNode, matrix: Mat3): void {
+ const toParent = Matrix.invert(getParentToContainerMatrix(node, scene)) ?? Matrix.identity()
+ const local = localTransformFromWorld(node, Matrix.multiply(toParent, matrix), Matrix.identity())
+ if (local) scene.updateNode(node.id, local)
+}
+
+/** Figma's rotation of a transform: counterclockwise degrees in (-180, 180]. */
+export function figmaRotation(matrix: Mat3): number {
+ const degrees = (Math.atan2(-matrix[3], matrix[0]) * 180) / Math.PI
+ // Figma reports the angle a script set, not its floating-point round trip.
+ const rounded = Math.round(degrees * 1e6) / 1e6
+ return Math.abs(degrees - rounded) < 1e-9 ? rounded + 0 : degrees
+}
+
+/**
+ * `matrix` turned to Figma's rotation `degrees` about its origin, the node's top-left corner, as
+ * Figma's plugin API turns a node; its flip and position stay.
+ */
+export function withFigmaRotation(matrix: Mat3, degrees: number): Mat3 {
+ const turn = Matrix.rotated(((figmaRotation(matrix) - degrees) * Math.PI) / 180)
+ const linear = Matrix.multiply(turn, [matrix[0], matrix[1], 0, matrix[3], matrix[4], 0, 0, 0, 1])
+ return [linear[0], linear[1], matrix[2], linear[3], linear[4], matrix[5], 0, 0, 1]
+}
+
+/** `matrix` moved so its origin is at `x`, `y`. */
+export function withOrigin(matrix: Mat3, x: number, y: number): Mat3 {
+ return [matrix[0], matrix[1], x, matrix[3], matrix[4], y, 0, 0, 1]
+}
diff --git a/packages/core/src/tools/input.ts b/packages/core/src/tools/input.ts
index ff428f144..431fafa28 100644
--- a/packages/core/src/tools/input.ts
+++ b/packages/core/src/tools/input.ts
@@ -14,8 +14,8 @@ export function nodeTraversalInput(depthDescription: string) {
})
}
export const positionInputs = {
- x: toolNumber(v.pipe(v.number(), v.description('X position'))),
- y: toolNumber(v.pipe(v.number(), v.description('Y position')))
+ x: toolNumber(v.pipe(v.number(), v.description('X position in the parent, or on the page'))),
+ y: toolNumber(v.pipe(v.number(), v.description('Y position in the parent, or on the page')))
}
/** Reuse a native number schema for both numeric and numeric-string agent inputs. */
diff --git a/packages/core/tests/editor/components/create-component.test.ts b/packages/core/tests/editor/components/create-component.test.ts
index 4b3e36a7d..e937f4254 100644
--- a/packages/core/tests/editor/components/create-component.test.ts
+++ b/packages/core/tests/editor/components/create-component.test.ts
@@ -35,9 +35,9 @@ describe('createComponentFromSelection', () => {
editor.select([a.id, c.id])
editor.createComponentFromSelection()
const component = created()
- expect(component?.name).toBe('Component')
+ expect(component?.name).toBe('Component 1')
expect(component?.fills.map((fill) => fill.color)).toEqual([WHITE])
- expect(order()).toEqual(['b', 'Component', 'd'])
+ expect(order()).toEqual(['b', 'Component 1', 'd'])
})
test('turns a group into the component in place, keeping its look', () => {
@@ -49,6 +49,6 @@ describe('createComponentFromSelection', () => {
expect(component?.type).toBe('COMPONENT')
expect(component?.fills).toEqual([])
expect(component?.childIds).toEqual([b.id, c.id])
- expect(order()).toEqual(['a', 'Group', 'd'])
+ expect(order()).toEqual(['a', 'Group 1', 'd'])
})
})
diff --git a/packages/core/tests/editor/structure/names.test.ts b/packages/core/tests/editor/structure/names.test.ts
new file mode 100644
index 000000000..626919117
--- /dev/null
+++ b/packages/core/tests/editor/structure/names.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core/editor'
+
+// Recorded in Figma desktop 126: a layer made on the canvas is numbered one past the highest
+// number any layer on the page has with its name, whatever that layer is; booleans are not.
+
+function setup() {
+ const editor = createEditor()
+ const pageId = editor.state.currentPageId
+ const nodes = ['a', 'b', 'c', 'd', 'e', 'f'].map((name, i) =>
+ editor.graph.createNode('RECTANGLE', pageId, { name, x: i * 100, width: 40, height: 40 })
+ )
+ const name = () => editor.graph.getNode([...editor.state.selectedIds][0] ?? '')?.name
+ return { editor, pageId, nodes, name }
+}
+
+describe('canvas layer names', () => {
+ test('drawn layers are numbered per name', () => {
+ const { editor, pageId } = setup()
+ const names = (['RECTANGLE', 'RECTANGLE', 'FRAME', 'ELLIPSE', 'SECTION'] as const).map(
+ (type) => editor.graph.getNode(editor.createShape(type, 0, 0, 10, 10, pageId))?.name
+ )
+ expect(names).toEqual(['Rectangle 1', 'Rectangle 2', 'Frame 1', 'Ellipse 1', 'Section 1'])
+ })
+
+ test('groups, frames, and components count past the highest number on the page', () => {
+ const { editor, pageId, nodes, name } = setup()
+ const [a, b, c, d, e, f] = nodes
+ const frame = editor.graph.createNode('FRAME', pageId, { name: 'Other' })
+ editor.graph.createNode('RECTANGLE', frame.id, { name: 'Group 9' })
+
+ editor.select([a.id, b.id])
+ editor.groupSelected()
+ expect(name()).toBe('Group 10')
+ editor.select([c.id, d.id])
+ editor.frameSelection()
+ expect(name()).toBe('Frame 1')
+ editor.select([e.id, f.id])
+ editor.createComponentFromSelection()
+ expect(name()).toBe('Component 1')
+ })
+
+ test('booleans are named after the operation, without a number', () => {
+ const { editor, nodes, name } = setup()
+ editor.select([nodes[0].id, nodes[1].id])
+ editor.booleanOperationSelected('UNION')
+ expect(name()).toBe('Union')
+ })
+})
diff --git a/packages/core/tests/editor/structure/z-order.test.ts b/packages/core/tests/editor/structure/z-order.test.ts
index 17552309b..3a1c490e6 100644
--- a/packages/core/tests/editor/structure/z-order.test.ts
+++ b/packages/core/tests/editor/structure/z-order.test.ts
@@ -53,12 +53,12 @@ describe('z-order actions', () => {
})
test('grouping takes the topmost layer’s place, and ungrouping and undo keep the stack', () => {
- // Recorded in Figma desktop 126: grouping A and C of A, B, C, D gives B, Group, D.
+ // Recorded in Figma desktop 126: grouping A and C of A, B, C, D gives B, Group 1, D.
const { editor, pageId, nodes } = setupEditor()
editor.select([nodes[2]?.id ?? '', nodes[0]?.id ?? ''])
editor.groupSelected()
- expect(childNames(editor, pageId)).toEqual(['B', 'Group', 'D'])
+ expect(childNames(editor, pageId)).toEqual(['B', 'Group 1', 'D'])
const [groupId] = [...editor.state.selectedIds]
expect(editor.graph.getChildren(groupId ?? '').map((node) => node.name)).toEqual(['A', 'C'])
@@ -66,11 +66,11 @@ describe('z-order actions', () => {
expect(childNames(editor, pageId)).toEqual(['A', 'B', 'C', 'D'])
editor.redoAction()
- expect(childNames(editor, pageId)).toEqual(['B', 'Group', 'D'])
+ expect(childNames(editor, pageId)).toEqual(['B', 'Group 1', 'D'])
editor.ungroupSelected()
expect(childNames(editor, pageId)).toEqual(['B', 'A', 'C', 'D'])
editor.undoAction()
- expect(childNames(editor, pageId)).toEqual(['B', 'Group', 'D'])
+ expect(childNames(editor, pageId)).toEqual(['B', 'Group 1', 'D'])
})
})
diff --git a/packages/core/tests/figma-api/boolean-bounds.test.ts b/packages/core/tests/figma-api/boolean-bounds.test.ts
new file mode 100644
index 000000000..39f27894a
--- /dev/null
+++ b/packages/core/tests/figma-api/boolean-bounds.test.ts
@@ -0,0 +1,125 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test'
+
+import type { Surface } from 'canvaskit-wasm'
+
+import { SkiaRenderer } from '@open-pencil/core/canvas'
+import { createEditor } from '@open-pencil/core/editor'
+import { FigmaAPI, type FigmaNodeProxy } from '@open-pencil/core/figma-api'
+import { initCanvasKit } from '@open-pencil/core/io'
+import { SceneGraph } from '@open-pencil/scene-graph'
+import type { Rect } from '@open-pencil/scene-graph/primitives'
+
+// Recorded with the same script in Figma desktop 126: a boolean operation takes the box of its
+// result, and an empty result keeps its operands' box. Measuring needs a renderer.
+
+type Operation = 'UNION' | 'SUBTRACT' | 'INTERSECT' | 'EXCLUDE'
+
+let renderer: SkiaRenderer
+let surface: Surface
+
+beforeAll(async () => {
+ const ck = await initCanvasKit()
+ const made = ck.MakeSurface(64, 64)
+ if (!made) throw new Error('Could not create CanvasKit surface')
+ surface = made
+ renderer = new SkiaRenderer(ck, surface)
+})
+
+afterAll(() => surface.delete())
+
+const box = (node: Rect) =>
+ [node.x, node.y, node.width, node.height].map((value) => Math.round(value * 1000) / 1000)
+
+function api() {
+ const figma = new FigmaAPI(new SceneGraph())
+ figma.setRenderer(renderer)
+ const square = (x: number, y: number, width = 50, height = 50) => {
+ const rect = figma.createRectangle()
+ rect.x = x
+ rect.y = y
+ rect.resize(width, height)
+ return rect
+ }
+ return { figma, square }
+}
+
+describe('boolean operation bounds', () => {
+ test('from scripts, a boolean takes the box of its result', () => {
+ const { figma, square } = api()
+ const combine = (operation: Operation, ...nodes: FigmaNodeProxy[]) =>
+ figma.booleanOperation(
+ operation,
+ nodes.map((node) => node.id)
+ )
+ expect(box(combine('UNION', square(0, 0), square(20, 20)))).toEqual([0, 0, 70, 70])
+ expect(box(combine('SUBTRACT', square(0, 0), square(20, 20)))).toEqual([0, 0, 50, 50])
+ const intersect = combine('INTERSECT', square(0, 0), square(20, 20))
+ expect(box(intersect)).toEqual([20, 20, 30, 30])
+ // The operands keep their places in the container's space.
+ expect(intersect.children.map((child) => [child.x, child.y])).toEqual([
+ [0, 0],
+ [20, 20]
+ ])
+ expect(box(combine('SUBTRACT', square(0, 0), square(25, -10, 50, 70)))).toEqual([0, 0, 25, 50])
+ expect(box(combine('INTERSECT', square(0, 0), square(100, 0)))).toEqual([0, 0, 150, 50])
+ })
+
+ test('moving an operand refits the boolean to its new result', () => {
+ const { figma, square } = api()
+ const moving = square(20, 20)
+ const intersect = figma.booleanOperation('INTERSECT', [square(0, 0).id, moving.id])
+ moving.x = 40
+ expect(box(intersect)).toEqual([40, 20, 10, 30])
+ })
+
+ test('from the canvas, a boolean takes the box of its result too', () => {
+ const editor = createEditor()
+ // Attaching CanvasKit installs a global text measurer that later tests must not inherit.
+ try {
+ editor.setCanvasKit(renderer.ck, renderer)
+ const pageId = editor.state.currentPageId
+ const a = editor.graph.createNode('RECTANGLE', pageId, { width: 50, height: 50 })
+ const b = editor.graph.createNode('RECTANGLE', pageId, {
+ x: 20,
+ y: 20,
+ width: 50,
+ height: 50
+ })
+ editor.select([a.id, b.id])
+ editor.booleanOperationSelected('INTERSECT')
+ const [booleanId] = [...editor.state.selectedIds]
+ const booleanNode = editor.graph.getNode(booleanId ?? '')
+ expect(booleanNode && box(booleanNode)).toEqual([20, 20, 30, 30])
+ expect(editor.graph.getAbsolutePosition(b.id)).toEqual({ x: 20, y: 20 })
+ } finally {
+ editor.dispose()
+ }
+ })
+
+ test('undo puts back the group a boolean refit', () => {
+ const editor = createEditor()
+ try {
+ editor.setCanvasKit(renderer.ck, renderer)
+ const pageId = editor.state.currentPageId
+ const group = editor.graph.createNode('GROUP', pageId, { width: 200, height: 70 })
+ const a = editor.graph.createNode('RECTANGLE', group.id, { width: 50, height: 50 })
+ const b = editor.graph.createNode('RECTANGLE', group.id, {
+ x: 20,
+ y: 20,
+ width: 50,
+ height: 50
+ })
+ editor.graph.createNode('RECTANGLE', group.id, { x: 150, y: 0, width: 50, height: 50 })
+ const before = [a, b].map((node) => editor.graph.getAbsolutePosition(node.id))
+
+ editor.select([a.id, b.id])
+ editor.booleanOperationSelected('INTERSECT')
+ editor.undo.undo()
+
+ expect(box(group)).toEqual([0, 0, 200, 70])
+ expect([a, b].map((node) => editor.graph.getAbsolutePosition(node.id))).toEqual(before)
+ } finally {
+ editor.dispose()
+ }
+ })
+})
diff --git a/packages/core/tests/figma-api/create-defaults.test.ts b/packages/core/tests/figma-api/create-defaults.test.ts
index 531e1534e..448d927e1 100644
--- a/packages/core/tests/figma-api/create-defaults.test.ts
+++ b/packages/core/tests/figma-api/create-defaults.test.ts
@@ -65,6 +65,18 @@ describe('new layer defaults', () => {
expect(rect.strokeWeight).toBe(1)
})
+ test('sections are 496 square with a faint white outline, filled for the interface theme', () => {
+ const figma = api()
+ const light = figma.createSection()
+ expect([light.width, light.height, light.cornerRadius]).toEqual([496, 496, 2])
+ expect(solid(light.fills)).toEqual([WHITE])
+ expect(solid(light.strokes)).toEqual([WHITE])
+ expect([light.strokes[0]?.opacity, light.strokeAlign]).toEqual([0.1, 'INSIDE'])
+ // Figma fills a section #444444 in its dark theme.
+ figma.theme = 'dark'
+ expect(solid(figma.createSection().fills)).toEqual([[0.27, 0.27, 0.27]])
+ })
+
test('each layer gets its own copy of the default paints', () => {
const editor = createEditor()
try {
diff --git a/packages/core/tests/figma-api/stroke-geometry.test.ts b/packages/core/tests/figma-api/stroke-geometry.test.ts
new file mode 100644
index 000000000..494b8194e
--- /dev/null
+++ b/packages/core/tests/figma-api/stroke-geometry.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, test } from 'bun:test'
+
+import { FigmaAPI } from '@open-pencil/core/figma-api'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+// Recorded with the same script in Figma desktop 126: stroke weight and alignment belong to the
+// node, so they last without strokes and a stroke added later takes them.
+
+const red = [{ type: 'SOLID', color: { r: 1, g: 0, b: 0 } }]
+
+function api() {
+ return new FigmaAPI(new SceneGraph())
+}
+
+describe('plugin API stroke geometry', () => {
+ test('new nodes align strokes inside, centered on lines and vectors, outside text', () => {
+ const figma = api()
+ expect(figma.createRectangle().strokeAlign).toBe('INSIDE')
+ expect(figma.createFrame().strokeAlign).toBe('INSIDE')
+ expect(figma.createLine().strokeAlign).toBe('CENTER')
+ expect(figma.createVector().strokeAlign).toBe('CENTER')
+ expect(figma.createText().strokeAlign).toBe('OUTSIDE')
+ })
+
+ test('weight and alignment set before a stroke are kept and given to it', () => {
+ const figma = api()
+ const rect = figma.createRectangle()
+ rect.strokeWeight = 5
+ expect(rect.strokeWeight).toBe(5)
+ // Scripts pass Figma paints, which carry no geometry.
+ Reflect.set(rect, 'strokes', red)
+ expect([rect.strokeWeight, rect.strokeAlign]).toEqual([5, 'INSIDE'])
+
+ const ellipse = figma.createEllipse()
+ ellipse.strokeAlign = 'OUTSIDE'
+ Reflect.set(ellipse, 'strokes', red)
+ expect([ellipse.strokeAlign, ellipse.strokeWeight]).toEqual(['OUTSIDE', 1])
+ })
+
+ test('the weight applies to every stroke and outlasts them', () => {
+ const rect = api().createRectangle()
+ Reflect.set(rect, 'strokes', [...red, ...red])
+ rect.strokeWeight = 4
+ expect(rect.strokes.map((stroke) => stroke.weight)).toEqual([4, 4])
+ rect.strokes = []
+ expect(rect.strokeWeight).toBe(4)
+ Reflect.set(rect, 'strokes', red)
+ expect(rect.strokeWeight).toBe(4)
+ })
+
+ test('rescale scales the weight a node keeps without strokes', () => {
+ const rect = api().createRectangle()
+ rect.strokeWeight = 3
+ rect.strokeAlign = 'CENTER'
+ rect.rescale(2)
+ expect([rect.strokeWeight, rect.strokeAlign]).toEqual([6, 'CENTER'])
+ })
+})
diff --git a/packages/core/tests/figma-api/transform-parity.test.ts b/packages/core/tests/figma-api/transform-parity.test.ts
new file mode 100644
index 000000000..7a6e22397
--- /dev/null
+++ b/packages/core/tests/figma-api/transform-parity.test.ts
@@ -0,0 +1,119 @@
+import { describe, expect, test } from 'bun:test'
+
+import { FigmaAPI } from '@open-pencil/core/figma-api'
+import { SceneGraph } from '@open-pencil/scene-graph'
+import type { Rect } from '@open-pencil/scene-graph/primitives'
+
+// Recorded with the same script in Figma desktop 126: the plugin API turns a node
+// counterclockwise about its top-left corner, and x and y are that corner in the parent.
+
+const round = (value: number) => Math.round(value * 1000) / 1000
+const rounded = (rows: readonly (readonly number[])[]) => rows.map((row) => row.map(round))
+const box = (rect: Rect) =>
+ [rect.x, rect.y, rect.width, rect.height].map(round)
+
+function rectangle() {
+ const figma = new FigmaAPI(new SceneGraph())
+ const rect = figma.createRectangle()
+ rect.x = 100
+ rect.y = 100
+ rect.resize(100, 50)
+ return { figma, rect }
+}
+
+describe('plugin API rotation', () => {
+ test('turns counterclockwise about the top-left corner', () => {
+ const { rect } = rectangle()
+ rect.rotation = 30
+ expect([rect.x, rect.y, rect.rotation]).toEqual([100, 100, 30])
+ expect(rounded(rect.relativeTransform)).toEqual([
+ [0.866, 0.5, 100],
+ [-0.5, 0.866, 100]
+ ])
+ expect(box(rect.absoluteBoundingBox)).toEqual([100, 50, 111.603, 93.301])
+
+ rect.rotation = -45
+ expect(rounded(rect.relativeTransform)).toEqual([
+ [0.707, -0.707, 100],
+ [0.707, 0.707, 100]
+ ])
+ rect.rotation = 200
+ expect(round(rect.rotation)).toBe(-160)
+ })
+
+ test('a turned node moves and resizes about the same corner', () => {
+ const { rect } = rectangle()
+ rect.rotation = 30
+ rect.x = 0
+ expect([rect.x, rect.y]).toEqual([0, 100])
+ rect.resize(200, 50)
+ expect([round(rect.x), round(rect.y)]).toEqual([0, 100])
+ expect(box(rect.absoluteBoundingBox)).toEqual([0, 0, 198.205, 143.301])
+ })
+
+ test('relativeTransform can be set', () => {
+ const { rect } = rectangle()
+ const [cos, sin] = [Math.cos(Math.PI / 6), Math.sin(Math.PI / 6)]
+ rect.relativeTransform = [
+ [cos, sin, 10],
+ [-sin, cos, 20]
+ ]
+ expect([round(rect.x), round(rect.y), round(rect.rotation)]).toEqual([10, 20, 30])
+ })
+
+ test('a line turns about its start', () => {
+ const figma = new FigmaAPI(new SceneGraph())
+ const line = figma.createLine()
+ line.rotation = 90
+ expect(line.relativeTransform).toEqual([
+ [0, 1, 0],
+ [-1, 0, 0]
+ ])
+ expect(box(line.absoluteBoundingBox)).toEqual([0, -100, 0, 100])
+ })
+})
+
+describe('plugin API appendChild', () => {
+ test('a moved node keeps its x, y, and rotation in its new parent', () => {
+ const figma = new FigmaAPI(new SceneGraph())
+ const frame = figma.createFrame()
+ frame.x = 500
+ frame.y = 40
+ const rect = figma.createRectangle()
+ rect.x = 10
+ rect.y = 20
+ frame.appendChild(rect)
+ expect([rect.x, rect.y]).toEqual([10, 20])
+ expect(rect.absoluteTransform).toEqual([
+ [1, 0, 510],
+ [0, 1, 60]
+ ])
+
+ const turned = figma.createFrame()
+ turned.x = 800
+ turned.resize(200, 200)
+ turned.rotation = 90
+ rect.rotation = 15
+ turned.appendChild(rect)
+ expect([round(rect.x), round(rect.y), round(rect.rotation)]).toEqual([10, 20, 15])
+ expect(rounded(rect.absoluteTransform)).toEqual([
+ [-0.259, 0.966, 820],
+ [-0.966, -0.259, -10]
+ ])
+
+ figma.currentPage.appendChild(rect)
+ expect([round(rect.x), round(rect.y), round(rect.rotation)]).toEqual([10, 20, 15])
+ })
+
+ test('insertChild keeps x and y too', () => {
+ const figma = new FigmaAPI(new SceneGraph())
+ const frame = figma.createFrame()
+ frame.x = 500
+ frame.appendChild(figma.createEllipse())
+ const rect = figma.createRectangle()
+ rect.x = 30
+ rect.y = 40
+ frame.insertChild(0, rect)
+ expect([rect.x, rect.y, frame.children.indexOf(rect)]).toEqual([30, 40, 0])
+ })
+})
diff --git a/packages/core/tests/io/formats/fig/roundtrip/stroke-geometry.test.ts b/packages/core/tests/io/formats/fig/roundtrip/stroke-geometry.test.ts
new file mode 100644
index 000000000..d15d51376
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/roundtrip/stroke-geometry.test.ts
@@ -0,0 +1,32 @@
+import { beforeAll, describe, expect, setDefaultTimeout, test } from 'bun:test'
+
+import { exportFigFile, initCodec, parseFigFile, SceneGraph } from '@open-pencil/core'
+
+import { collectAllNodes } from '#core-tests/helpers/fig/traversal'
+
+setDefaultTimeout(60_000)
+
+describe('roundtrip: stroke geometry without strokes', () => {
+ beforeAll(async () => {
+ await initCodec()
+ })
+
+ test('a weight and alignment kept without strokes survive export and re-import', async () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ graph.createNode('RECTANGLE', page.id, {
+ name: 'Kept',
+ strokes: [],
+ strokeWeight: 5,
+ strokeAlign: 'OUTSIDE'
+ })
+ graph.createNode('RECTANGLE', page.id, { name: 'Default', strokes: [] })
+
+ const bytes = await exportFigFile(graph)
+ const nodes = collectAllNodes(await parseFigFile(bytes.buffer as ArrayBuffer))
+ const kept = nodes.find((node) => node.name === 'Kept')
+ expect([kept?.strokeWeight, kept?.strokeAlign]).toEqual([5, 'OUTSIDE'])
+ const plain = nodes.find((node) => node.name === 'Default')
+ expect([plain?.strokeWeight, plain?.strokeAlign]).toEqual([1, 'INSIDE'])
+ })
+})
diff --git a/packages/fig/src/node-change/convert.ts b/packages/fig/src/node-change/convert.ts
index 30e5737cd..2f3b20418 100644
--- a/packages/fig/src/node-change/convert.ts
+++ b/packages/fig/src/node-change/convert.ts
@@ -2,6 +2,7 @@ import { guidToString } from '@open-pencil/kiwi/fig/guid'
import {
DEFAULT_FONT_FAMILY,
DEFAULT_STROKE_MITER_LIMIT,
+ DEFAULT_STROKE_WEIGHT,
OPEN_PENCIL_PLUGIN_DATA,
styleToWeight
} from '@open-pencil/scene-graph'
@@ -13,7 +14,7 @@ import { importCanvasGuides } from './canvas-guides'
import { convertFigmaDerivedTextGlyphs } from './derived-text/glyphs'
import { convertFontFeatures } from './font/features'
import { convertFontVariations } from './font/variations'
-import { convertEffects, convertFills, convertStrokes } from './paint'
+import { convertEffects, convertFills, convertStrokeAlign, convertStrokes } from './paint'
import { expandPathTextLayoutBox } from './path/text-layout'
import {
extractBoundVariables,
@@ -643,6 +644,8 @@ export function nodeChangeToProps(
vectorAndStrokeProps.strokeJoin,
nc.dashPattern ?? []
),
+ strokeWeight: nc.strokeWeight ?? DEFAULT_STROKE_WEIGHT,
+ strokeAlign: convertStrokeAlign(nc.strokeAlign),
effects: convertEffects(nc.effects),
layoutGrids: convertLayoutGrids(nc.layoutGrids),
guides: importCanvasGuides(nc.guides),
diff --git a/packages/fig/src/node-change/export/node.ts b/packages/fig/src/node-change/export/node.ts
index d11f1b960..b4cb80403 100644
--- a/packages/fig/src/node-change/export/node.ts
+++ b/packages/fig/src/node-change/export/node.ts
@@ -11,6 +11,7 @@ import type {
} from '@open-pencil/scene-graph'
import {
DEFAULT_STROKE_MITER_LIMIT,
+ DEFAULT_STROKE_WEIGHT,
OPEN_PENCIL_PLUGIN_DATA,
withPluginData
} from '@open-pencil/scene-graph'
@@ -920,13 +921,20 @@ export function sceneNodeToKiwiWithContext(
if (node.type === 'GROUP') {
nc.resizeToFit = true
}
- // Only set strokeWeight/strokeAlign when the node has strokes in the scene
- // model. For imported nodes without strokes but with raw strokeWeight data
- // (e.g. text nodes, instance children with scaled strokes), the raw value
- // must be allowed to flow through via applyRawFigmaNodeFields.
+ // With strokes, their geometry is the node's. Without, the node keeps its own weight and
+ // alignment, written when set or when the source file carried them.
if (node.strokes.length > 0) {
nc.strokeWeight = node.strokes[0].weight
nc.strokeAlign = node.strokes[0].align
+ } else {
+ const rawNodeFields = effectiveFigmaRawNodeFields(node)
+ if (node.strokeWeight !== DEFAULT_STROKE_WEIGHT || 'strokeWeight' in rawNodeFields) {
+ nc.strokeWeight = node.strokeWeight
+ }
+ // Kiwi reads a missing alignment as centered.
+ if (node.strokeAlign !== 'CENTER' || 'strokeAlign' in rawNodeFields) {
+ nc.strokeAlign = node.strokeAlign
+ }
}
if (node.locked) nc.locked = true
diff --git a/packages/fig/src/node-change/paint.ts b/packages/fig/src/node-change/paint.ts
index 4a02d00c5..8ca6d28f7 100644
--- a/packages/fig/src/node-change/paint.ts
+++ b/packages/fig/src/node-change/paint.ts
@@ -157,6 +157,11 @@ export function convertFills(paints?: Paint[]): Fill[] {
return paints.map(convertPaint)
}
+/** A Kiwi stroke alignment; Figma leaves out the centered default. */
+export function convertStrokeAlign(align?: string): Stroke['align'] {
+ return align === 'INSIDE' || align === 'OUTSIDE' ? align : 'CENTER'
+}
+
export function convertStrokes(
paints?: Paint[],
weight?: number,
@@ -166,9 +171,7 @@ export function convertStrokes(
dashPattern?: number[]
): Stroke[] {
if (!paints) return []
- let strokeAlign: 'INSIDE' | 'OUTSIDE' | 'CENTER' = 'CENTER'
- if (align === 'INSIDE') strokeAlign = 'INSIDE'
- else if (align === 'OUTSIDE') strokeAlign = 'OUTSIDE'
+ const strokeAlign = convertStrokeAlign(align)
return paints.map((p) => ({
...convertPaint(p),
diff --git a/packages/fig/src/node-change/serialize.ts b/packages/fig/src/node-change/serialize.ts
index 1c2d30c3a..ec284f03b 100644
--- a/packages/fig/src/node-change/serialize.ts
+++ b/packages/fig/src/node-change/serialize.ts
@@ -1,4 +1,5 @@
import {
+ DEFAULT_STROKE_WEIGHT,
normalizeFontFamily,
OPEN_PENCIL_PLUGIN_DATA,
withPluginData
@@ -473,7 +474,6 @@ export function sceneNodeToKiwi(
}
const IDENTITY_TRANSFORM = { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }
-const DEFAULT_STROKE_WEIGHT = 1
export function makeDocumentNodeChange(
guid: GUID,
diff --git a/packages/fig/src/source-metadata.ts b/packages/fig/src/source-metadata.ts
index 1215047f2..643dcb26d 100644
--- a/packages/fig/src/source-metadata.ts
+++ b/packages/fig/src/source-metadata.ts
@@ -49,6 +49,7 @@ const EDITED_RAW_FIELDS: Partial<Record<string, readonly string[]>> = {
...STROKE_GEOMETRY_RAW_FIELDS
],
strokeWeight: ['strokeWeight', ...STROKE_GEOMETRY_RAW_FIELDS],
+ strokeAlign: ['strokeAlign', ...STROKE_GEOMETRY_RAW_FIELDS],
strokeJoin: ['strokeJoin', ...STROKE_GEOMETRY_RAW_FIELDS],
strokeMiterLimit: ['miterLimit', ...STROKE_GEOMETRY_RAW_FIELDS],
strokeCap: [...STROKE_GEOMETRY_RAW_FIELDS],
diff --git a/packages/scene-graph/src/constants.ts b/packages/scene-graph/src/constants.ts
index c7499159b..df2867cbf 100644
--- a/packages/scene-graph/src/constants.ts
+++ b/packages/scene-graph/src/constants.ts
@@ -4,3 +4,4 @@ export const BLACK: Color = { r: 0, g: 0, b: 0, a: 1 }
export const TRANSPARENT: Color = { r: 0, g: 0, b: 0, a: 0 }
export const DEFAULT_FONT_FAMILY = 'Inter'
export const DEFAULT_STROKE_MITER_LIMIT = 4
+export const DEFAULT_STROKE_WEIGHT = 1
diff --git a/packages/scene-graph/src/group-bounds.ts b/packages/scene-graph/src/group-bounds.ts
index c7d4b74be..90aa62a65 100644
--- a/packages/scene-graph/src/group-bounds.ts
+++ b/packages/scene-graph/src/group-bounds.ts
@@ -1,6 +1,7 @@
import { getAxisAlignedBoundsInParent } from './coordinate'
import type { SceneGraph } from './index'
import { FITTED_CONTAINER_TYPES } from './node-defaults'
+import type { Rect } from './primitives'
import type { SceneNode } from './types'
type Placement = Pick<SceneNode, 'x' | 'y' | 'width' | 'height'>
@@ -13,6 +14,14 @@ export interface GroupFit {
removed: Array<{ node: SceneNode; index: number }>
}
+export interface GroupFitOptions {
+ /**
+ * The box of a boolean operation's result in its parent's space, which Figma sizes a boolean to,
+ * or null to fit its operands. Measuring needs path operations, so the renderer supplies it.
+ */
+ booleanBounds?: (node: SceneNode) => Rect | null
+}
+
function placement(node: SceneNode): Placement {
return { x: node.x, y: node.y, width: node.width, height: node.height }
}
@@ -37,9 +46,17 @@ function fittedAncestors(graph: SceneGraph, parentIds: Iterable<string>): SceneN
}
/** Moves the group to its children's bounds, shifting them back so they stay put. */
-function fitGroup(graph: SceneGraph, group: SceneNode, children: SceneNode[], fit: GroupFit) {
+function fitGroup(
+ graph: SceneGraph,
+ group: SceneNode,
+ children: SceneNode[],
+ fit: GroupFit,
+ options: GroupFitOptions
+) {
if (!group.parentId || group.rotation !== 0 || group.flipX || group.flipY) return
- const bounds = getAxisAlignedBoundsInParent(children, group.parentId, graph)
+ const bounds =
+ (group.type === 'BOOLEAN_OPERATION' ? options.booleanBounds?.(group) : null) ??
+ getAxisAlignedBoundsInParent(children, group.parentId, graph)
const dx = bounds.x - group.x
const dy = bounds.y - group.y
if (dx === 0 && dy === 0 && bounds.width === group.width && bounds.height === group.height) {
@@ -74,13 +91,14 @@ function removeEmptyGroup(graph: SceneGraph, group: SceneNode, fit: GroupFit) {
*/
export function fitEnclosingGroups(
graph: SceneGraph,
- parentIds: Iterable<string>
+ parentIds: Iterable<string>,
+ options: GroupFitOptions = {}
): GroupFit | null {
const fit: GroupFit = { before: new Map(), after: new Map(), removed: [] }
for (const group of fittedAncestors(graph, parentIds)) {
const children = graph.getChildren(group.id)
if (children.length === 0) removeEmptyGroup(graph, group, fit)
- else fitGroup(graph, group, children, fit)
+ else fitGroup(graph, group, children, fit, options)
}
return fit.before.size === 0 && fit.removed.length === 0 ? null : fit
}
diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.ts
index ff9f09f91..7f01ae953 100644
--- a/packages/scene-graph/src/index.ts
+++ b/packages/scene-graph/src/index.ts
@@ -23,7 +23,12 @@ export * from './behaviours/kinds'
export * from './behaviours/model'
export * from './behaviours/spec'
export * from './copy'
-export { createDefaultNode, FITTED_CONTAINER_TYPES } from './node-defaults'
+export {
+ createDefaultNode,
+ defaultStrokeAlign,
+ FITTED_CONTAINER_TYPES,
+ newStrokeGeometry
+} from './node-defaults'
export {
copyInstanceComponentProps,
findInstanceAncestor,
diff --git a/packages/scene-graph/src/node-defaults.ts b/packages/scene-graph/src/node-defaults.ts
index b5be01e96..6c4544b56 100644
--- a/packages/scene-graph/src/node-defaults.ts
+++ b/packages/scene-graph/src/node-defaults.ts
@@ -1,4 +1,9 @@
-import { BLACK, DEFAULT_FONT_FAMILY, DEFAULT_STROKE_MITER_LIMIT } from './constants'
+import {
+ BLACK,
+ DEFAULT_FONT_FAMILY,
+ DEFAULT_STROKE_MITER_LIMIT,
+ DEFAULT_STROKE_WEIGHT
+} from './constants'
import { createInstanceOverrideState } from './instance-overrides'
import type { NodeType, SceneNode, SourceMetadata } from './types'
@@ -29,6 +34,23 @@ export function createDefaultSourceMetadata(): SourceMetadata {
*/
type CompleteNodeFields = SceneNode & Record<keyof SceneNode, unknown>
+/** Where Figma aligns a new node's strokes: centered on lines and vectors, outside text, else inside. */
+export function defaultStrokeAlign(type: NodeType): SceneNode['strokeAlign'] {
+ if (type === 'LINE' || type === 'VECTOR') return 'CENTER'
+ return type === 'TEXT' ? 'OUTSIDE' : 'INSIDE'
+}
+
+/**
+ * Weight and alignment a stroke added to `node` takes: its first stroke's, or what the node keeps
+ * with none. Adding a stroke from the panel and from the plugin API both go through here.
+ */
+export function newStrokeGeometry(
+ node: Pick<SceneNode, 'strokes' | 'strokeWeight' | 'strokeAlign'>
+): Pick<SceneNode['strokes'][number], 'weight' | 'align'> {
+ const first = node.strokes.at(0)
+ return { weight: first?.weight ?? node.strokeWeight, align: first?.align ?? node.strokeAlign }
+}
+
export function createDefaultNode(
generateId: () => string,
type: NodeType,
@@ -126,6 +148,8 @@ export function createDefaultNode(
borderBottomWeight: 0,
borderLeftWeight: 0,
independentStrokeWeights: false,
+ strokeWeight: DEFAULT_STROKE_WEIGHT,
+ strokeAlign: defaultStrokeAlign(type),
strokeMiterLimit: DEFAULT_STROKE_MITER_LIMIT,
minWidth: null,
maxWidth: null,
diff --git a/packages/scene-graph/src/scaling/node.ts b/packages/scene-graph/src/scaling/node.ts
index 5b1b66b33..8b49d1cf7 100644
--- a/packages/scene-graph/src/scaling/node.ts
+++ b/packages/scene-graph/src/scaling/node.ts
@@ -127,6 +127,7 @@ export function scaleNodeChanges(
gridTemplateColumns: scaledGridTracks(node.gridTemplateColumns, scale),
gridTemplateRows: scaledGridTracks(node.gridTemplateRows, scale),
strokes: scaledStrokes(node.strokes, scale),
+ strokeWeight: node.strokeWeight * scale,
dashPattern: node.dashPattern.map((value) => value * scale),
borderTopWeight: node.borderTopWeight * scale,
borderRightWeight: node.borderRightWeight * scale,
diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.ts
index a03fd9bfe..beb76f255 100644
--- a/packages/scene-graph/src/types.ts
+++ b/packages/scene-graph/src/types.ts
@@ -520,6 +520,14 @@ export interface SceneNode {
borderLeftWeight: number
independentStrokeWeights: boolean
+ /**
+ * The weight and alignment a node keeps for its strokes, as Figma keeps them on the node: they
+ * last while it has no strokes, and a stroke added to it takes them. Each stroke still carries
+ * its own `weight` and `align`, which win while the node has strokes.
+ */
+ strokeWeight: number
+ strokeAlign: Stroke['align']
+
strokeMiterLimit: number
minWidth: number | null
diff --git a/packages/vue/src/controls/stroke/use.ts b/packages/vue/src/controls/stroke/use.ts
index 1baa8b498..767568cf9 100644
--- a/packages/vue/src/controls/stroke/use.ts
+++ b/packages/vue/src/controls/stroke/use.ts
@@ -1,5 +1,7 @@
import { ref } from 'vue'
+import { newStrokeGeometry, type Stroke } from '@open-pencil/scene-graph'
+
import { useNodeProps } from '#vue/controls/node-props/use'
import {
BORDER_SIDES,
@@ -61,7 +63,11 @@ export function useStrokeControls() {
sideOptions: SIDE_OPTIONS,
borderSides: BORDER_SIDES,
sideMenuOpen,
- defaultStroke: DEFAULT_STROKE,
+ /** A new stroke for the selection: black, with the weight and alignment its first node keeps. */
+ get defaultStroke(): Stroke {
+ const first = nodes.value.at(0)
+ return { ...DEFAULT_STROKE, ...(first ? newStrokeGeometry(first) : {}) }
+ },
updateAlign: updateAlign.bind(null, store),
currentAlign,
currentSides,
diff --git a/src/app/automation/bridge/figma-factory.ts b/src/app/automation/bridge/figma-factory.ts
index d0434fcb9..1de6e7c1d 100644
--- a/src/app/automation/bridge/figma-factory.ts
+++ b/src/app/automation/bridge/figma-factory.ts
@@ -10,6 +10,7 @@ export function makeFigmaFromStore(
): FigmaAPI {
const api = new FigmaAPI(store.graph)
api.setRenderer(store.renderer ?? null)
+ api.theme = store.state.theme ?? 'light'
api.currentPage = api.wrapNode(pageId)
// The user's selection belongs to the page on screen.
api.currentPage.selection =
diff --git a/src/app/shell/theme.ts b/src/app/shell/theme.ts
index 510b6a5fd..21bb40d91 100644
--- a/src/app/shell/theme.ts
+++ b/src/app/shell/theme.ts
@@ -36,6 +36,7 @@ function updateCanvasTheme(): void {
const store = getActiveEditorStoreOrNull()
if (!store) return
store.state.rulerTheme = readRulerTheme() ?? undefined
+ store.state.theme = resolvedAppTheme.value
store.requestRepaint()
}
diff --git a/src/constants.ts b/src/constants.ts
index d3050a171..ef156f727 100644
--- a/src/constants.ts
+++ b/src/constants.ts
@@ -109,8 +109,6 @@ export const PEER_COLORS: Color[] = [
export {
DEFAULT_SHAPE_FILL,
DEFAULT_FRAME_FILL,
- SECTION_DEFAULT_FILL,
- SECTION_DEFAULT_STROKE,
ZOOM_DIVISOR,
ZOOM_SCALE_MIN,
ZOOM_SCALE_MAX
diff --git a/tests/e2e/clipboard/copy-paste.spec.ts b/tests/e2e/clipboard/copy-paste.spec.ts
index a4624a0ff..3461e4504 100644
--- a/tests/e2e/clipboard/copy-paste.spec.ts
+++ b/tests/e2e/clipboard/copy-paste.spec.ts
@@ -42,7 +42,7 @@ test('pasted node is offset from original', async () => {
expect(nodes).toHaveLength(1)
const pasted = nodes[0]
- expect(pasted.name).toBe('Rectangle')
+ expect(pasted.name).toBe('Rectangle 1')
})
test('⌘D duplicates in place', async () => {
diff --git a/tests/e2e/clipboard/paste-into-container.spec.ts b/tests/e2e/clipboard/paste-into-container.spec.ts
index fcf5ba8b7..49bc2d0a7 100644
--- a/tests/e2e/clipboard/paste-into-container.spec.ts
+++ b/tests/e2e/clipboard/paste-into-container.spec.ts
@@ -76,7 +76,7 @@ test('paste into selected frame places node as child', async () => {
const store = window.openPencil?.getStore?.()
if (!store) throw new Error('OpenPencil store not initialized')
const rect = [...store.graph.nodes.values()].find(
- (n) => n.name === 'Rectangle' && n.type === 'RECTANGLE'
+ (n) => n.name === 'Rectangle 1' && n.type === 'RECTANGLE'
)
if (!rect) throw new Error('Rectangle not found')
store.select([rect.id])
@@ -92,7 +92,7 @@ test('paste into selected frame places node as child', async () => {
await editor.canvas.waitForRender()
const children = await getNodeChildren(frameId)
- const pastedChild = children.find((c) => c.name === 'Rectangle')
+ const pastedChild = children.find((c) => c.name === 'Rectangle 1')
expect(pastedChild).toBeDefined()
expect(pastedChild?.parentId).toBe(frameId)
})
@@ -110,7 +110,7 @@ test('paste with child selected places node as sibling in parent frame', async (
const store = window.openPencil?.getStore?.()
if (!store) throw new Error('OpenPencil store not initialized')
const rect = [...store.graph.nodes.values()].find(
- (n) => n.name === 'Rectangle' && n.type === 'RECTANGLE'
+ (n) => n.name === 'Rectangle 1' && n.type === 'RECTANGLE'
)
if (!rect) throw new Error('Rectangle not found')
store.select([rect.id])
diff --git a/tests/e2e/clipboard/tauri-plugin-routing.spec.ts b/tests/e2e/clipboard/tauri-plugin-routing.spec.ts
index 4319a6cd3..6157b7872 100644
--- a/tests/e2e/clipboard/tauri-plugin-routing.spec.ts
+++ b/tests/e2e/clipboard/tauri-plugin-routing.spec.ts
@@ -72,7 +72,7 @@ test('Tauri copy writes selected design HTML without requiring ClipboardEvent.cl
await dispatchClipboardEvent(page, 'copy')
- await expect.poll(() => clipboard.snapshot()).toMatchObject({ text: 'Rectangle' })
+ await expect.poll(() => clipboard.snapshot()).toMatchObject({ text: 'Rectangle 1' })
const snapshot = clipboard.snapshot()
expect(snapshot.html).toContain('(figma)')
expect(snapshot.writes.some((entry) => entry.cmd === 'plugin:clipboard-manager|write_html')).toBe(
@@ -86,7 +86,7 @@ test('Tauri paste restores copied design data from plugin clipboard text', async
const { canvas, clipboard } = await createTauriEditorPage(page)
await canvas.drawRect(160, 160, 96, 72)
await dispatchClipboardEvent(page, 'copy')
- await expect.poll(() => clipboard.snapshot()).toMatchObject({ text: 'Rectangle' })
+ await expect.poll(() => clipboard.snapshot()).toMatchObject({ text: 'Rectangle 1' })
expect(await pageChildren(page)).toHaveLength(1)
await canvas.deleteSelection()
@@ -96,7 +96,7 @@ test('Tauri paste restores copied design data from plugin clipboard text', async
await canvas.waitForRender()
const children = await pageChildren(page)
- expect(children).toEqual([{ name: 'Rectangle', type: 'RECTANGLE' }])
+ expect(children).toEqual([{ name: 'Rectangle 1', type: 'RECTANGLE' }])
expect(await selectedCount(page)).toBe(1)
await expect(page.getByText('Clipboard access is blocked in this browser context')).toHaveCount(0)
canvas.assertNoErrors()
@@ -112,7 +112,7 @@ test('Tauri cut writes design data and deletes the selection', async ({ page })
await expect.poll(() => pageChildren(page)).toEqual([])
const snapshot = clipboard.snapshot()
expect(snapshot.html).toContain('(figma)')
- expect(snapshot.text).toBe('Rectangle')
+ expect(snapshot.text).toBe('Rectangle 1')
await expect(page.getByText('Clipboard access is blocked in this browser context')).toHaveCount(0)
canvas.assertNoErrors()
})
@@ -125,7 +125,7 @@ test('Tauri cut keeps the selection when the clipboard write fails', async ({ pa
await dispatchClipboardEvent(page, 'cut')
await canvas.waitForRender()
- await expect.poll(() => pageChildren(page)).toEqual([{ name: 'Rectangle', type: 'RECTANGLE' }])
+ await expect.poll(() => pageChildren(page)).toEqual([{ name: 'Rectangle 1', type: 'RECTANGLE' }])
expect(await selectedCount(page)).toBe(1)
const snapshot = clipboard.snapshot()
expect(snapshot.html).toBe('')
@@ -198,7 +198,7 @@ test('Tauri context-menu copy uses plugin clipboard fallback instead of blocked
await page.mouse.click(box.x + 190, box.y + 190, { button: 'right' })
await page.getByTestId('context-copy').click()
- await expect.poll(() => clipboard.snapshot()).toMatchObject({ text: 'Rectangle' })
+ await expect.poll(() => clipboard.snapshot()).toMatchObject({ text: 'Rectangle 1' })
await expect(page.getByText('Clipboard access is blocked in this browser context')).toHaveCount(0)
canvas.assertNoErrors()
})
diff --git a/tests/e2e/editor/duplicate-undo.spec.ts b/tests/e2e/editor/duplicate-undo.spec.ts
index 127a640bd..2ce790863 100644
--- a/tests/e2e/editor/duplicate-undo.spec.ts
+++ b/tests/e2e/editor/duplicate-undo.spec.ts
@@ -33,16 +33,16 @@ test('undo after option-drag duplicate removes the copy', async () => {
await editor.canvas.altDrag(180, 165, 340, 165)
await expect.poll(rectangleCount).toBe(2)
- await expect.poll(layerItems).toEqual(['Rectangle', 'Rectangle'])
+ await expect.poll(layerItems).toEqual(['Rectangle 1', 'Rectangle 1'])
await editor.canvas.undo()
await expect.poll(rectangleCount).toBe(1)
- await expect.poll(layerItems).toEqual(['Rectangle'])
+ await expect.poll(layerItems).toEqual(['Rectangle 1'])
await expect.poll(historyState).toMatchObject({ canRedo: true, redoLabel: 'Duplicate' })
await editor.page.waitForTimeout(1500)
await expect.poll(rectangleCount).toBe(1)
- await expect.poll(layerItems).toEqual(['Rectangle'])
+ await expect.poll(layerItems).toEqual(['Rectangle 1'])
await expect.poll(historyState).toMatchObject({ canRedo: true, redoLabel: 'Duplicate' })
await editor.page.keyboard.down('Meta')
@@ -52,12 +52,12 @@ test('undo after option-drag duplicate removes the copy', async () => {
await editor.page.keyboard.up('Meta')
await editor.canvas.waitForRender()
await expect.poll(rectangleCount).toBe(2)
- await expect.poll(layerItems).toEqual(['Rectangle', 'Rectangle'])
+ await expect.poll(layerItems).toEqual(['Rectangle 1', 'Rectangle 1'])
await expect.poll(historyState).toMatchObject({ canUndo: true, undoLabel: 'Duplicate' })
await editor.page.waitForTimeout(1500)
await expect.poll(rectangleCount).toBe(2)
- await expect.poll(layerItems).toEqual(['Rectangle', 'Rectangle'])
+ await expect.poll(layerItems).toEqual(['Rectangle 1', 'Rectangle 1'])
await expect.poll(historyState).toMatchObject({ canUndo: true, undoLabel: 'Duplicate' })
editor.canvas.assertNoErrors()
})
diff --git a/tests/e2e/layers/panel.spec.ts b/tests/e2e/layers/panel.spec.ts
index 81389edf8..6de4fb4e8 100644
--- a/tests/e2e/layers/panel.spec.ts
+++ b/tests/e2e/layers/panel.spec.ts
@@ -53,6 +53,8 @@ async function getSelectedCount(): Promise<number> {
})
}
+const NUMBERED_GROUP = /^Group \d+$/
+
test('demo layers visible in panel', async () => {
const names = await getLayerNames()
expect(names).toContain('Announcement system')
@@ -105,13 +107,13 @@ test('creating a shape updates layers', async () => {
const before = await getLayerNames()
await editor.canvas.drawRect(600, 500, 50, 50)
const names = await getLayerNames()
- expect(names).toContain('Rectangle')
+ expect(names).toContain('Rectangle 1')
expect(names.length).toBe(before.length + 1)
await editor.canvas.undo()
const after = await getLayerNames()
expect(after.length).toBe(before.length)
- expect(after).not.toContain('Rectangle')
+ expect(after).not.toContain('Rectangle 1')
})
test('Shift+A wraps selection in auto-layout frame', async () => {
@@ -152,12 +154,13 @@ test('grouping updates layers', async () => {
await editor.page.keyboard.press('Meta+g')
await editor.canvas.waitForRender()
+ // The canvas numbers a group past the highest "Group" number on the page, as Figma does.
const tree = await getSceneTree()
- const group = tree.children.find((c) => c.name === 'Group' && c.type === 'GROUP')
+ const group = tree.children.find((c) => NUMBERED_GROUP.test(c.name) && c.type === 'GROUP')
expect(group).toBeTruthy()
const names = await getLayerNames()
- expect(names).toContain('Group')
+ expect(names.some((name) => NUMBERED_GROUP.test(name))).toBe(true)
editor.canvas.assertNoErrors()
})
@@ -167,8 +170,8 @@ test('ungrouping updates layers', async () => {
await editor.canvas.waitForRender()
const names = await getLayerNames()
- expect(names).not.toContain('Group')
- expect(names).toContain('Rectangle')
+ expect(names.some((name) => NUMBERED_GROUP.test(name))).toBe(false)
+ expect(names.some((name) => /^Rectangle \d+$/.test(name))).toBe(true)
editor.canvas.assertNoErrors()
})
@@ -210,11 +213,16 @@ test('clicking outside rename input commits', async () => {
editor.canvas.assertNoErrors()
})
-test('clearing a layer name falls back to the default node name', async () => {
+test('clearing a layer name keeps the name it had', async () => {
await editor.canvas.drawRect(980, 600, 50, 50)
await editor.canvas.waitForRender()
- const row = layerRows().filter({ hasText: 'Rectangle' }).last()
+ const drawn = await editor.page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ const id = store ? [...store.state.selectedIds][0] : undefined
+ return id ? (store?.graph.getNode(id)?.name ?? '') : ''
+ })
+ const row = layerRows().filter({ hasText: drawn }).last()
const countBefore = await layerRows().count()
await row.dblclick()
@@ -230,7 +238,8 @@ test('clearing a layer name falls back to the default node name', async () => {
expect(countAfter).toBe(countBefore)
const names = await getLayerNames()
- expect(names.filter((name) => name === 'Rectangle').length).toBeGreaterThan(0)
+ expect(drawn).toMatch(/^Rectangle \d+$/)
+ expect(names).toContain(drawn)
editor.canvas.assertNoErrors()
})
diff --git a/tests/e2e/stroke-picker/gradient.spec.ts b/tests/e2e/stroke-picker/gradient.spec.ts
index da3f24799..fb97b5c20 100644
--- a/tests/e2e/stroke-picker/gradient.spec.ts
+++ b/tests/e2e/stroke-picker/gradient.spec.ts
@@ -36,7 +36,7 @@ test('a stroke can be made a gradient and taken back to solid', async ({ page })
expect(gradient?.type).toBe('GRADIENT_LINEAR')
expect(gradient?.gradientStops?.length).toBeGreaterThan(1)
// The stroke keeps its geometry across the paint change.
- expect(gradient).toMatchObject({ weight: 1, align: 'CENTER' })
+ expect(gradient).toMatchObject({ weight: 1, align: 'INSIDE' })
await page.getByTestId('fill-picker-tab-solid').click()
await canvas.waitForRender()
@@ -44,6 +44,6 @@ test('a stroke can be made a gradient and taken back to solid', async ({ page })
// Switching back keeps the stops, as it does for a fill, so the gradient returns on re-pick.
const solid = await selectedStroke(page)
expect(solid?.type).toBe('SOLID')
- expect(solid).toMatchObject({ weight: 1, align: 'CENTER' })
+ expect(solid).toMatchObject({ weight: 1, align: 'INSIDE' })
canvas.assertNoErrors()
})
diff --git a/tests/engine/figma/api/absolute/position.test.ts b/tests/engine/figma/api/absolute/position.test.ts
index e83dd2795..e6a984c95 100644
--- a/tests/engine/figma/api/absolute/position.test.ts
+++ b/tests/engine/figma/api/absolute/position.test.ts
@@ -15,13 +15,14 @@ describe('absolute position', () => {
child.resize(50, 30)
child.rotation = 90
+ // Recorded in Figma desktop 126: a node turns counterclockwise about its top-left corner.
expect(child.relativeTransform).toEqual([
- [0, -1, 50],
- [1, 0, 10]
+ [0, 1, 10],
+ [-1, 0, 20]
])
expect(child.absoluteTransform).toEqual([
- [0, -1, 150],
- [1, 0, 210]
+ [0, 1, 110],
+ [-1, 0, 220]
])
})
@@ -49,8 +50,9 @@ describe('absolute position', () => {
}
})
+ // Recorded in Figma desktop 126: x and y are the transform's translation, flipped or not.
expect(node.x).toBe(5)
- expect(node.y).toBe(8)
+ expect(node.y).toBe(16)
expect(node.rotation).toBe(-0)
expect(node.relativeTransform).toEqual([
[1, 0, 5],