Skip to content

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

fix: Figma parity follow-ups for instances, guides, layer type, paste, and selection (#1101)

Danila Poyarkov004e1ac6c205
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 18a26a47a..8ce5788bd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,14 +10,21 @@
### Added
- Text keeps a case, a link, text and fill styles, and variable bindings for any range of its characters, as in Figma: the canvas draws each range in its own case, `.fig` files and the Figma clipboard keep them, apart from font weight bindings, HTML, Tailwind, and JSX exports write links as `<a href>` and cases as `text-transform` and HTML import reads them back, Design JSX `<Span>` takes `textCase` and `href`, and the Typography section's text case changes the selected characters while text is edited. Scripts read and set them with `getRangeTextCase`, `setRangeTextCase`, `getRangeHyperlink`, `setRangeHyperlink`, `getRangeTextStyleId`, `setRangeTextStyleIdAsync`, `getRangeFillStyleId`, `setRangeFillStyleIdAsync`, `getRangeBoundVariable`, `setRangeBoundVariable`, and the text's `hyperlink`.
+- Switch a frame to a group and back from the layer type menu in the properties panel header, as in Figma. A frame becomes a group that keeps its layers, effects, and opacity and fits them; a group becomes a frame of its bounds that clips.
+- Edit the layout guides of several frames at once: the panel lists them while the frames' guides match and edits every frame in one undo step, and while they differ offers Add, which gives each frame one new guide. A new guide is Figma's 10 px grid.
- Official builds send one anonymous ping a day, with the app version, operating system, architecture, desktop or web, and whether usage stats are shared, and no ID; turn it off in Settings → Privacy or with `OPENPENCIL_TELEMETRY=0` or `DO_NOT_TRACK=1` in the desktop app's environment. Usage stats (launches, file formats opened and exported, and which AI provider answered) are sent only after you agree in a one-time prompt after the welcome screen. The [privacy page](https://openpencil.dev/overview/privacy) lists every field.
### Changed
-- **Settings…** (<kbd>⌘</kbd><kbd>,</kbd>) is in the **OpenPencil** menu on macOS and at the end of the **File** menu elsewhere, instead of under **View → Preferences**.
+- The Layout guide section follows Figma: each guide is a row with a summary such as "5 columns" or "Grid 10px" that switches between grid, columns, and rows, and its settings open from the row's icon with Count, Type, Width or Height, Margin or Offset, Gutter, and Color fields. The section now sits after Selection colors.
- A selected layer resizes and rotates where Figma's does: every edge resizes along its whole length within 7.5 px outside it and up to a tenth of the side inside it, corners within 7.5 px, and the area outside a corner within 16 px rotates; a frame's name takes a press before rotation but not before resizing. Layers under 24 px keep these zones outside them, and a layer under 10 px on both sides has none, taking presses within 16 px across its centre instead. A selection draws Figma's four corner handles, without the edge midpoints, and none on such a small layer.
- Pasted layers keep how they were turned and flipped on the canvas, as in Figma, so a layer copied out of a rotated frame stays at its angle in an upright one, and paste to replace keeps the copied layer's angle too. Layers copied out of a frame or section keep their offset from its box on the canvas, and move into the frame only when they start past its far edge, or, for top-level layers, miss it: then layers that fit are centred on that axis, and larger ones go to the frame's top-left, or are centred if top-level. Layers overlapping an edge stay where they are, and layers copied from different places are placed each from its own.
+- A click up to 3.5 screen pixels outside a shape selects it, as in Figma, so hairlines and small dots are easy to pick; a frame's edge stays exact.
+- A click on a section's empty area selects the section, while a drag there still selects the layers inside it, and a right-click over the empty area of a frame with layers, or of a section, selects it for the menu. A selection under 10 screen pixels both ways shows no size label, as it shows no handles.
+- With nothing selected, a layer copied out of a frame or section pastes back into it, where it was on the canvas, or onto the page in the middle of the view when that place is out of view, as in Figma.
+- In scripts, `setProperties` switches an instance's variant, alongside its other properties, and fails without changing anything when no variant has the values, with Figma's messages; `resize` places a frame's layers by their constraints while `resizeWithoutConstraints` leaves them, and an instance's layers follow their constraints either way.
+- **Settings…** (<kbd>⌘</kbd><kbd>,</kbd>) is in the **OpenPencil** menu on macOS and at the end of the **File** menu elsewhere, instead of under **View → Preferences**.
- The demo at `/demo` is a tour of one player card in eight chapters stacked on one canvas, each showing one thing with a numbered card that says what to try and draws the piece of the app to click: preview, the artwork slot, the controls' behaviours, the theme's modes, shader fills, the Code tab, Lint on a card with planted issues, and sharing and opening your own files. It opens on the first chapter with the rest below it and follows the app's light or dark theme. The welcome dialog on first launch offers it next to AI setup, and File > Open the Tour opens it any time.
### Fixed
@@ -36,6 +43,10 @@
- Lines of text that mix font sizes or line heights are spaced as in Figma: each line is as tall as the tallest line height on it, with its largest font centred in it, instead of stacking the tallest parts of every style on it, which put lines after a large word or a taller line height up to 10 px off.
- A line height in pixels shorter than the font, such as 24 px on 24 px text, opens from `.fig` files as set instead of as the font's own height.
- Text with an empty line, or ending in one, saved to `.fig` or copied to Figma shows there, where Figma showed it blank.
+- Instances keep following their component after being resized: resizing one by a handle no longer makes the sizes of the layers its constraints move into overrides. A component edit no longer gives a copy the component's size where it sizes itself to its own content, such as a badge's count set by an instance property, or an auto layout frame hugging the layers the instance shows, and setting a text property measures the new characters, so the badge fits them at once.
+- `openpencil eval -o` saves a script's edits laid out, though the script never read them back; `@open-pencil/core/figma-api` exports `flushPendingLayout` for hosts that save scripts' results.
+- Saving keeps a fill, stroke, effect, or text style that an instance has cleared, which reopened with the component's style.
+- Layout guides added in the panel or a script save to `.fig` files, where saving failed on them, and a guide read from a file shows as columns or rows in the panel and saves the count edited there. Columns and rows with an Auto count draw as many as fit the frame and read Auto in the panel. Scripts read and set `layoutGrids` in Figma's shape.
- The properties panel shows the shared styles layers use in opened `.fig` files, where it listed them as missing styles.
- Styles made in OpenPencil, by importing design tokens or by pasting layers from another document, are saved in `.fig` files as styles, and layers reopen with them. Saving wrote their references empty, so reopening dropped the styles, and saving into an opened file made them layers of the page in Figma.
- Layers and text that use a library style keep it in Figma after OpenPencil saves them, where Figma showed them with no style.
diff --git a/packages/cli/src/commands/eval.ts b/packages/cli/src/commands/eval.ts
index fc6ca3dc8..da56b20e6 100644
--- a/packages/cli/src/commands/eval.ts
+++ b/packages/cli/src/commands/eval.ts
@@ -1,6 +1,6 @@
import { defineCommand } from 'citty'
-import { FigmaAPI } from '@open-pencil/core/figma-api'
+import { FigmaAPI, flushPendingLayout } from '@open-pencil/core/figma-api'
import { compileScript } from '@open-pencil/core/tools'
import { isAppMode, requireFile, rpc } from '#cli/app/client'
@@ -86,6 +86,8 @@ export default defineCommand({
if (args.write || args.output) {
const outPath = args.output ? args.output : file
+ // A script's edits that nothing read yet are laid out before saving, as Figma saves them.
+ flushPendingLayout(graph)
await writeFigDocument(graph, outPath)
if (!args.quiet) {
console.error(`Written to ${outPath}`)
diff --git a/packages/cli/tests/commands/eval.test.ts b/packages/cli/tests/commands/eval.test.ts
new file mode 100644
index 000000000..1ef4ecb41
--- /dev/null
+++ b/packages/cli/tests/commands/eval.test.ts
@@ -0,0 +1,63 @@
+import { describe, expect, setDefaultTimeout, test } from 'bun:test'
+import { mkdtemp } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+
+import { CLI_ENTRY, FIXTURES } from '#cli-tests/helpers/paths'
+import * as v from 'valibot'
+
+setDefaultTimeout(60_000)
+
+async function cli(args: string[], stdin?: string) {
+ const proc = Bun.spawn([process.execPath, CLI_ENTRY, ...args], {
+ stdout: 'pipe',
+ stderr: 'pipe',
+ stdin: stdin ? Buffer.from(stdin) : undefined
+ })
+ const [stdout, stderr] = await Promise.all([
+ new Response(proc.stdout).text(),
+ new Response(proc.stderr).text()
+ ])
+ return { stdout: stdout.trim(), stderr: stderr.trim(), exitCode: await proc.exited }
+}
+
+describe('eval CLI', () => {
+ test('saves a script’s edits laid out, though the script never read them back', async () => {
+ const out = join(await mkdtemp(join(tmpdir(), 'open-pencil-eval-')), 'badge.fig')
+ // A hugging badge whose label a property shortens: its saved width fits the new label.
+ const script = `
+ const badge = figma.createComponent()
+ badge.name = 'Badge'
+ badge.layoutMode = 'HORIZONTAL'
+ badge.paddingLeft = badge.paddingRight = 10
+ badge.primaryAxisSizingMode = 'AUTO'
+ badge.counterAxisSizingMode = 'AUTO'
+ const label = figma.createText()
+ label.characters = 'Placeholder'
+ badge.appendChild(label)
+ const prop = badge.addComponentProperty('Label', 'TEXT', 'Placeholder')
+ label.componentPropertyReferences = { characters: prop }
+ const instance = badge.createInstance()
+ instance.name = 'Short'
+ instance.setProperties({ [prop]: '2' })
+ `
+ const written = await cli(
+ ['eval', join(FIXTURES, 'gold-preview.fig'), '--stdin', '-o', out, '-q'],
+ script
+ )
+ expect(written.exitCode).toBe(0)
+ const read = await cli([
+ 'eval',
+ out,
+ '--json',
+ '--code',
+ `
+ const short = figma.currentPage.findOne((n) => n.name === 'Short')
+ const badge = figma.currentPage.findOne((n) => n.type === 'COMPONENT' && n.name === 'Badge')
+ return [short.width < badge.width, short.children[0].width < badge.children[0].width]
+ `
+ ])
+ const parsed = v.safeParse(v.pipe(v.string(), v.parseJson(), v.array(v.boolean())), read.stdout)
+ expect(parsed.success && parsed.output).toEqual([true, true])
+ })
+})
diff --git a/packages/core/src/canvas/labels/selection.ts b/packages/core/src/canvas/labels/selection.ts
index 55920e181..f226146d1 100644
--- a/packages/core/src/canvas/labels/selection.ts
+++ b/packages/core/src/canvas/labels/selection.ts
@@ -11,7 +11,7 @@ import {
SIZE_PILL_RADIUS,
SIZE_PILL_TEXT_OFFSET_Y
} from '#core/constants'
-import { createSceneGeometry } from '#core/geometry'
+import { createSceneGeometry, hasTransformHandles } from '#core/geometry'
import { measureGlyphWidth } from './paragraph-cache'
import { frameLabelPlacement, labelScreenMatrix } from './transform'
@@ -129,6 +129,11 @@ export function drawSelectionLabels(
activeOverlays
)
if (nodes.length === 0) return
+ // A selection too small on screen for handles has no size label either, as in Figma.
+ const [only] = nodes
+ const width = nodes.length === 1 ? only.width : maxX - minX
+ const height = nodes.length === 1 ? only.height : maxY - minY
+ if (!hasTransformHandles(width * r.zoom, height * r.zoom)) return
if (nodes.length === 1) {
drawSingleSelectionSize(r, canvas, graph, nodes[0], activeOverlays, sizeFont)
diff --git a/packages/core/src/canvas/layout-grids.ts b/packages/core/src/canvas/layout-grids.ts
index c90253c69..eba4510f3 100644
--- a/packages/core/src/canvas/layout-grids.ts
+++ b/packages/core/src/canvas/layout-grids.ts
@@ -2,7 +2,7 @@ import type { Canvas } from 'canvaskit-wasm'
import { readEffectiveFigmaRawField } from '@open-pencil/fig'
import type { SceneNode } from '@open-pencil/scene-graph'
-import { layoutGuideSections } from '@open-pencil/scene-graph/layout'
+import { layoutGridCount, layoutGuideSections } from '@open-pencil/scene-graph/layout'
import type { Color } from '@open-pencil/scene-graph/primitives'
import { SELECTION_COLOR } from '#core/constants'
@@ -17,7 +17,7 @@ type RawLayoutGrid = SceneNode['layoutGrids'][number] & {
type?: string
alignment?: string
numSections?: number
- count?: number
+ count?: number | null
offset?: number
sectionSize?: number
gutterSize?: number
@@ -58,10 +58,11 @@ function rawGridAlignment(grid: RawLayoutGrid): GridGeometry['alignment'] {
function gridGeometry(grid: RawLayoutGrid): GridGeometry | null {
if (grid.visible === false) return null
- const count = grid.count ?? grid.numSections ?? 1
+ // An Auto count stays as it is: the sections drawn are as many as fit.
+ const count = layoutGridCount(grid)
const sectionSize = grid.sectionSize ?? 0
const alignment = rawGridAlignment(grid)
- if (!Number.isFinite(count) || count <= 0) return null
+ if (count <= 0) return null
if (rawGridPattern(grid) === 'GRID' && sectionSize <= 0) return null
if (alignment !== 'STRETCH' && sectionSize <= 0) return null
return {
diff --git a/packages/core/src/constants.ts b/packages/core/src/constants.ts
index 72768180a..005f5c159 100644
--- a/packages/core/src/constants.ts
+++ b/packages/core/src/constants.ts
@@ -566,6 +566,8 @@ export const ZOOM_SCALE_MAX = 1.25
export const PEN_CLOSE_THRESHOLD = 8
export const ROTATION_SNAP_DEGREES = 15
export const HANDLE_HIT_RADIUS = 6
+/** How far outside a shape, in screen pixels, a click still selects it (Figma desktop 126). */
+export const LAYER_HIT_PAD = 3.5
export const ROTATION_HANDLE_DISTANCE = 24
export const DEFAULT_TEXT_WIDTH = 200
export const DEFAULT_TEXT_HEIGHT = 24
diff --git a/packages/core/src/editor/bridges/structure.ts b/packages/core/src/editor/bridges/structure.ts
index 762901703..e3f2aed24 100644
--- a/packages/core/src/editor/bridges/structure.ts
+++ b/packages/core/src/editor/bridges/structure.ts
@@ -14,6 +14,11 @@ export function createStructureBridge(structure: StructureActions, selection: Se
flattenSelected: () => structure.flattenSelected(selection.getSelectedNodes()),
outlineTextSelected: () => structure.outlineTextSelected(selection.getSelectedNodes()),
outlineStrokeSelected: () => structure.outlineStrokeSelected(selection.getSelectedNodes()),
- ungroupSelected: () => structure.ungroupSelected(selection.getSelectedNode())
+ ungroupSelected: () => structure.ungroupSelected(selection.getSelectedNode()),
+ /** Switches a frame or group to the other type in place, as Figma's layer type menu does. */
+ convertLayerType: (nodeId: string, type: 'FRAME' | 'GROUP') =>
+ type === 'GROUP'
+ ? structure.convertFrameToGroup(nodeId)
+ : structure.convertGroupToFrame(nodeId)
}
}
diff --git a/packages/core/src/editor/clipboard.ts b/packages/core/src/editor/clipboard.ts
index 7a0f509a0..397ed06d0 100644
--- a/packages/core/src/editor/clipboard.ts
+++ b/packages/core/src/editor/clipboard.ts
@@ -16,7 +16,11 @@ import { createClipboardFontActions } from './clipboard/fonts'
import { deleteIds, recreateSnapshots, restoreDeletedEntries } from './clipboard/history'
import type { PasteHistoryOperation } from './clipboard/paste/replace'
import { replaceTargetsWithCreated, selectedReplacementTargets } from './clipboard/paste/replace'
-import { pastedComponentIds, resolvePasteTarget } from './clipboard/paste/target'
+import {
+ pastedComponentIds,
+ requestedPasteTarget,
+ resolvePasteTarget
+} from './clipboard/paste/target'
import {
clipboardPlacement,
createClipboardPlacementActions,
@@ -246,7 +250,12 @@ export function createClipboardActions(ctx: EditorContext) {
return node.id
}
- const requestedTarget = replacementTargets[0]?.parentId ?? resolvePasteTarget(ctx)
+ const { requestedTarget, returningTo } = requestedPasteTarget(
+ ctx,
+ placement.sources.map((source) => source?.id ?? null),
+ replacementTargets[0]?.parentId ?? null,
+ !!cursorPos
+ )
const pasteTarget = cycleSafeParent(
ctx.graph,
requestedTarget,
@@ -289,6 +298,7 @@ export function createClipboardActions(ctx: EditorContext) {
}
if (cursorPos) placementActions.centerNodesAtCanvasPoint(created, cursorPos)
+ else if (returningTo === pasteTarget) placementActions.placeReturned(created)
else placementActions.placePasted(created, placement, pasteTarget, requestedTarget)
computeAllLayouts(ctx.graph, ctx.state.currentPageId)
ctx.setSelectedIds(new Set(created))
diff --git a/packages/core/src/editor/clipboard/paste/target.ts b/packages/core/src/editor/clipboard/paste/target.ts
index d7e547547..5d8d72d3a 100644
--- a/packages/core/src/editor/clipboard/paste/target.ts
+++ b/packages/core/src/editor/clipboard/paste/target.ts
@@ -22,6 +22,39 @@ function pasteTargetCandidate(ctx: Pick<EditorContext, 'graph' | 'state'>): stri
return node.parentId ?? ctx.state.currentPageId
}
+/**
+ * Where a paste with nothing selected goes, as Figma pastes it: back into the frame or section
+ * the layers were copied out of, while it still exists on this page and takes layers. Null for
+ * top-level layers, layers from several places, or a parent that is gone.
+ */
+export function sourcePasteTarget(
+ ctx: Pick<EditorContext, 'graph' | 'state'>,
+ sourceIds: readonly (string | null)[]
+): string | null {
+ const [id, ...rest] = sourceIds
+ if (!id || rest.some((other) => other !== id)) return null
+ if (ctx.state.selectedIds.size > 0 || ctx.state.enteredContainerId) return null
+ if (!ctx.graph.getNode(id) || ctx.graph.pageOf(id) !== ctx.state.currentPageId) return null
+ return acceptingParent(ctx, id) === id ? id : null
+}
+
+/**
+ * Where a paste goes before cycles are checked: a replaced layer's parent, the frame a paste with
+ * nothing selected came from (`returningTo`), or the selection's paste target.
+ */
+export function requestedPasteTarget(
+ ctx: Pick<EditorContext, 'graph' | 'state'>,
+ sourceIds: readonly (string | null)[],
+ replacedParentId: string | null,
+ atCursor: boolean
+): { requestedTarget: string; returningTo: string | null } {
+ const returningTo = replacedParentId || atCursor ? null : sourcePasteTarget(ctx, sourceIds)
+ return {
+ requestedTarget: replacedParentId ?? returningTo ?? resolvePasteTarget(ctx),
+ returningTo
+ }
+}
+
type PastedTree = SceneNode & { children?: PastedTree[] }
/** The document's components that pasted instances point at; copied components are new ones. */
diff --git a/packages/core/src/editor/clipboard/placement.ts b/packages/core/src/editor/clipboard/placement.ts
index f8d5153cf..9c3fd1e50 100644
--- a/packages/core/src/editor/clipboard/placement.ts
+++ b/packages/core/src/editor/clipboard/placement.ts
@@ -257,6 +257,21 @@ export function createClipboardPlacementActions(ctx: EditorContext) {
}
}
+ /**
+ * Places layers pasted back into the frame they were copied out of: where they were on the
+ * canvas, as Figma keeps them even after the frame moved. Out of view, they go onto the page in
+ * the middle of the view instead.
+ */
+ function placeReturned(nodeIds: string[]) {
+ const view = viewportRect()
+ if (!view || overlaps(canvasBounds(ctx.graph, nodesOf(nodeIds)), view)) return
+ for (const id of nodeIds) ctx.graph.reparentNode(id, ctx.state.currentPageId)
+ centerNodesAtCanvasPoint(nodeIds, {
+ x: view.x + view.width / 2,
+ y: view.y + view.height / 2
+ })
+ }
+
/** Centers layers on a canvas point, through their parents' rotation and flips. */
function centerNodesAtCanvasPoint(nodeIds: string[], point: Vector) {
const items = nodesOf(nodeIds)
@@ -275,6 +290,7 @@ export function createClipboardPlacementActions(ctx: EditorContext) {
duplicatePosition,
keepCanvasTransforms,
placeForeignPaste,
- placePasted
+ placePasted,
+ placeReturned
}
}
diff --git a/packages/core/src/editor/components/properties.ts b/packages/core/src/editor/components/properties.ts
index 985d88964..a1af6fece 100644
--- a/packages/core/src/editor/components/properties.ts
+++ b/packages/core/src/editor/components/properties.ts
@@ -14,6 +14,7 @@ import type {
import { assertNodeEditable } from '#core/editor/capabilities'
import type { EditorContext } from '#core/editor/types'
+import { textAutoResizeChanges } from '#core/layout/text-auto-resize'
function definitionsForInstance(
ctx: Pick<EditorContext, 'graph'>,
@@ -32,6 +33,21 @@ function targetValue(target: ComponentPropertyTarget | null): string {
if (target.field === 'VISIBLE') return String(target.node.visible)
return target.source.componentId ?? target.node.componentId ?? ''
}
+/** Measures text a property gave new characters, when it sizes itself to them, as Figma does. */
+export function measurePropertyText(
+ ctx: Pick<EditorContext, 'graph'>,
+ instanceId: string,
+ definition: ComponentPropertyDefinition
+): void {
+ const instance = ctx.graph.getNode(instanceId)
+ if (definition.type !== 'TEXT' || !instance) return
+ for (const target of findComponentPropertyTargets(ctx.graph, instance, definition.id)) {
+ if (target.field !== 'TEXT') continue
+ const changes = textAutoResizeChanges(target.node, { text: target.node.text })
+ if (Object.keys(changes).length > 0) ctx.graph.updateNode(target.node.id, changes)
+ }
+}
+
function applyPropertyValue(
ctx: Pick<EditorContext, 'graph'>,
instanceId: string,
@@ -39,6 +55,7 @@ function applyPropertyValue(
value: string
): boolean {
const result = applyComponentPropertyValue(ctx.graph, instanceId, definition, value)
+ measurePropertyText(ctx, instanceId, definition)
return definition.type !== 'INSTANCE_SWAP' || result !== null
}
@@ -126,10 +143,12 @@ export function createComponentPropertyActions(
)
if (!applyPropertyValue(ctx, instanceId, definition, value)) return
+ ctx.runLayoutForNode(instanceId)
ctx.undo.push({
label: `Change ${definition.name}`,
forward: () => {
applyPropertyValue(ctx, instanceId, definition, value)
+ ctx.runLayoutForNode(instanceId)
ctx.requestRender()
},
inverse: () => {
@@ -143,6 +162,8 @@ export function createComponentPropertyActions(
restoredTargets.forEach((target, index) =>
restoreTarget(live, target, previousValues[index] ?? '')
)
+ measurePropertyText(ctx, instanceId, definition)
+ ctx.runLayoutForNode(instanceId)
}
ctx.requestRender()
}
diff --git a/packages/core/src/editor/selection/hit-test.ts b/packages/core/src/editor/selection/hit-test.ts
index 4681f30fc..fb7447b21 100644
--- a/packages/core/src/editor/selection/hit-test.ts
+++ b/packages/core/src/editor/selection/hit-test.ts
@@ -1,5 +1,6 @@
import type { SceneNode } from '@open-pencil/scene-graph'
+import { LAYER_HIT_PAD } from '#core/constants'
import type { EditorContext } from '#core/editor/types'
export function createSelectionHitTestActions(
@@ -10,24 +11,22 @@ export function createSelectionHitTestActions(
function hitTestAtPoint(cx: number, cy: number, deep = false): SceneNode | null {
const renderer = ctx.getRenderer()
if (!renderer) return null
+ const pad = LAYER_HIT_PAD / ctx.state.zoom
const scopeId = ctx.state.enteredContainerId
- if (scopeId) {
- const scopeNode = ctx.graph.getNode(scopeId)
- if (!scopeNode) {
- ctx.state.enteredContainerId = null
- } else {
- return deep
- ? ctx.graph.hitTestDeep(cx, cy, scopeId)
- : ctx.graph.hitTestSelectable(cx, cy, scopeId, ctx.state.selectedIds)
- }
- }
+ if (scopeId && !ctx.graph.getNode(scopeId)) ctx.state.enteredContainerId = null
+ const scope = ctx.state.enteredContainerId ?? ctx.state.currentPageId
return deep
- ? ctx.graph.hitTestDeep(cx, cy, ctx.state.currentPageId)
- : ctx.graph.hitTestSelectable(cx, cy, ctx.state.currentPageId, ctx.state.selectedIds)
+ ? ctx.graph.hitTestDeep(cx, cy, scope, pad)
+ : ctx.graph.hitTestSelectable(cx, cy, scope, ctx.state.selectedIds, pad)
}
+ /**
+ * Selects what a right-click is over, as Figma does: the layer a click would select, or else the
+ * frame or section whose empty area is under the point, which a click leaves for a marquee.
+ */
function selectAtPoint(cx: number, cy: number) {
- const hit = hitTestAtPoint(cx, cy)
+ const scopeId = ctx.state.enteredContainerId ?? ctx.state.currentPageId
+ const hit = hitTestAtPoint(cx, cy) ?? ctx.graph.hitTestOpenContainer(cx, cy, scopeId)
if (hit) {
if (!ctx.state.selectedIds.has(hit.id)) select([hit.id])
} else {
diff --git a/packages/core/src/editor/structure.ts b/packages/core/src/editor/structure.ts
index c07a91f52..0331ce958 100644
--- a/packages/core/src/editor/structure.ts
+++ b/packages/core/src/editor/structure.ts
@@ -1,5 +1,14 @@
-import { createsComponentCycle, type SceneNode } from '@open-pencil/scene-graph'
+import { pick } from 'es-toolkit/object'
+import {
+ createsComponentCycle,
+ fitEnclosingGroups,
+ redoGroupFit,
+ undoGroupFit,
+ type SceneNode
+} from '@open-pencil/scene-graph'
+
+import { groupFitOptions } from '#core/canvas/boolean'
import { acceptingParent, acceptsChildren, prepareSlotEdits } from '#core/editor/components/slots'
import { fitEnclosingGroupsWithUndo } from '#core/editor/structure/group-bounds'
@@ -23,6 +32,25 @@ import { createStructureReorderActions } from './structure/reorder'
import { createStructureStateActions } from './structure/state'
import type { EditorContext } from './types'
+/** What a frame has and a group does not, restored when the change to a group is undone. */
+const FRAME_ONLY_FIELDS = [
+ 'type',
+ 'fills',
+ 'strokes',
+ 'cornerRadius',
+ 'topLeftRadius',
+ 'topRightRadius',
+ 'bottomRightRadius',
+ 'bottomLeftRadius',
+ 'independentCorners',
+ 'layoutMode',
+ 'clipsContent',
+ 'layoutGrids',
+ 'fillStyleId',
+ 'strokeStyleId',
+ 'gridStyleId'
+] as const
+
export function createStructureActions(ctx: EditorContext) {
const reorderActions = createStructureReorderActions(ctx)
const stateActions = createStructureStateActions(ctx)
@@ -79,20 +107,71 @@ export function createStructureActions(ctx: EditorContext) {
}
/**
- * Turns a group into a frame in place. The layer keeps its id, children, bounds and look: a
- * group has no fill and does not clip, and the frame starts the same way.
+ * Turns a group into a frame in place, as Figma's layer type menu does. The layer keeps its id,
+ * children, bounds and look: a group has no fill, and the frame clips to the bounds its
+ * children already fill.
*/
function convertGroupToFrame(nodeId: string) {
if (ctx.graph.getNode(nodeId)?.type !== 'GROUP') return
- const apply = (type: 'GROUP' | 'FRAME') => {
- ctx.graph.updateNode(nodeId, { type })
+ const apply = (changes: Partial<SceneNode>) => {
+ ctx.graph.updateNode(nodeId, changes)
ctx.runLayoutForNode(nodeId)
}
- apply('FRAME')
+ const before = { type: 'GROUP' as const, clipsContent: ctx.graph.getNode(nodeId)?.clipsContent }
+ const after = { type: 'FRAME' as const, clipsContent: true }
+ apply(after)
ctx.undo.push({
label: 'Convert to frame',
- forward: () => apply('FRAME'),
- inverse: () => apply('GROUP')
+ forward: () => apply(after),
+ inverse: () => apply(before)
+ })
+ }
+
+ /**
+ * Turns a frame into a group in place, as Figma's layer type menu does: the layer keeps its id,
+ * children, effects and opacity, drops what a group cannot have (fill, stroke, corners, auto
+ * layout, guides), and fits its children, so one the frame clipped now widens it.
+ */
+ function convertFrameToGroup(nodeId: string) {
+ const frame = ctx.graph.getNode(nodeId)
+ if (frame?.type !== 'FRAME' || frame.childIds.length === 0) return
+ const before = structuredClone(pick(frame, FRAME_ONLY_FIELDS))
+ const after: Partial<SceneNode> = {
+ type: 'GROUP',
+ fills: [],
+ strokes: [],
+ cornerRadius: 0,
+ topLeftRadius: 0,
+ topRightRadius: 0,
+ bottomRightRadius: 0,
+ bottomLeftRadius: 0,
+ independentCorners: false,
+ layoutMode: 'NONE',
+ clipsContent: false,
+ layoutGrids: [],
+ fillStyleId: null,
+ strokeStyleId: null,
+ gridStyleId: null
+ }
+ ctx.graph.updateNode(nodeId, after)
+ const fit = fitEnclosingGroups(
+ ctx.graph,
+ [nodeId],
+ groupFitOptions(ctx.getRenderer(), ctx.graph)
+ )
+ ctx.runLayoutForNode(nodeId)
+ ctx.undo.push({
+ label: 'Convert to group',
+ forward: () => {
+ ctx.graph.updateNode(nodeId, after)
+ if (fit) redoGroupFit(ctx.graph, fit)
+ ctx.runLayoutForNode(nodeId)
+ },
+ inverse: () => {
+ if (fit) undoGroupFit(ctx.graph, fit)
+ ctx.graph.updateNode(nodeId, structuredClone(before))
+ ctx.runLayoutForNode(nodeId)
+ }
})
}
@@ -174,6 +253,7 @@ export function createStructureActions(ctx: EditorContext) {
wrapInAutoLayout,
groupSelected,
frameSelection,
+ convertFrameToGroup,
convertGroupToFrame,
booleanOperationSelected,
ungroupSelected,
diff --git a/packages/core/src/figma-api/accessors/basic.ts b/packages/core/src/figma-api/accessors/basic.ts
index 28b177f38..445d8d6a6 100644
--- a/packages/core/src/figma-api/accessors/basic.ts
+++ b/packages/core/src/figma-api/accessors/basic.ts
@@ -13,6 +13,11 @@ import {
} from '@open-pencil/scene-graph'
import type { Mat3 } from '@open-pencil/scene-graph/matrix'
import type { Rect } from '@open-pencil/scene-graph/primitives'
+import {
+ computeConstrainedResizeChanges,
+ createResizeSnapshot,
+ type ResizeSnapshot
+} from '@open-pencil/scene-graph/resize'
import { assertNodeEditable } from '#core/editor/capabilities'
import {
@@ -234,32 +239,10 @@ export function installBasicNodeProxyAccessors(
// 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 {
- assertEditable(this, internals)
- const scene = graph(this, internals)
- const node = raw(this, internals)
- const before = containerTransform(node, scene)
- // Text given a size stops sizing itself to its content, as in Figma.
- const fixesText =
- node.type === 'TEXT' &&
- (node.textAutoResize === 'WIDTH_AND_HEIGHT' || node.textAutoResize === 'HEIGHT')
- // A locked ratio does not hold here; it takes the new size, as in Figma.
- const recaptured = recapturedAspectRatio(node, width, height)
- scene.updateNode(node.id, {
- width,
- height,
- ...recaptured,
- ...(fixesText ? { textAutoResize: 'NONE' as const } : {})
- })
- recordInstanceOverride(scene, node.id, [
- 'width',
- 'height',
- ...Object.keys(recaptured),
- ...(fixesText ? ['textAutoResize'] : [])
- ])
- setTransform(this, internals, () => before)
+ resizeNode(this, internals, width, height, true)
},
resizeWithoutConstraints(this: ProxyThis, width: number, height: number): void {
- ;(this as { resize(width: number, height: number): void }).resize(width, height)
+ resizeNode(this, internals, width, height, false)
},
rescale(this: ProxyThis, scale: number): void {
assertEditable(this, internals)
@@ -272,4 +255,57 @@ export function installBasicNodeProxyAccessors(
})
}
+/** Every layer below a node, which a resize may place by its constraints. */
+function descendants(scene: SceneGraph, node: SceneNode): SceneNode[] {
+ return scene.getChildren(node.id).flatMap((child) => [child, ...descendants(scene, child)])
+}
+
+/**
+ * Resizes a node keeping its top-left corner, as Figma's does, though it turns about its center.
+ * `resize` places the layers inside by their constraints, as Figma's does, without making their
+ * sizes overrides; `resizeWithoutConstraints` leaves them be, except in an instance. The groups around the node refit
+ * once, after the corner is back in place.
+ */
+function resizeNode(
+ target: ProxyThis,
+ internals: NodeProxyInternals,
+ width: number,
+ height: number,
+ constrained: boolean
+): void {
+ assertEditable(target, internals)
+ const scene = graph(target, internals)
+ const node = raw(target, internals)
+ const before = containerTransform(node, scene)
+ const size = { width: node.width, height: node.height }
+ // An instance's layers follow its constraints however it is resized, as in Figma.
+ const placed =
+ constrained || node.type === 'INSTANCE'
+ ? new Map(descendants(scene, node).map((child) => [child.id, createResizeSnapshot(child)]))
+ : new Map<string, ResizeSnapshot>()
+ // Text given a size stops sizing itself to its content, as in Figma.
+ const fixesText =
+ node.type === 'TEXT' &&
+ (node.textAutoResize === 'WIDTH_AND_HEIGHT' || node.textAutoResize === 'HEIGHT')
+ // A locked ratio does not hold here; it takes the new size, as in Figma.
+ const recaptured = recapturedAspectRatio(node, width, height)
+ scene.updateNode(node.id, {
+ width,
+ height,
+ ...recaptured,
+ ...(fixesText ? { textAutoResize: 'NONE' as const } : {})
+ })
+ if (placed.size > 0 && size.width > 0 && size.height > 0) {
+ const changes = computeConstrainedResizeChanges(scene, node.id, size, { width, height }, placed)
+ for (const [id, change] of changes) scene.updateNode(id, change)
+ }
+ recordInstanceOverride(scene, node.id, [
+ 'width',
+ 'height',
+ ...Object.keys(recaptured),
+ ...(fixesText ? ['textAutoResize'] : [])
+ ])
+ setTransform(target, internals, () => before)
+}
+
export type { NodeProxyHost }
diff --git a/packages/core/src/figma-api/accessors/layout.ts b/packages/core/src/figma-api/accessors/layout.ts
index 466e0fd2e..71d839abc 100644
--- a/packages/core/src/figma-api/accessors/layout.ts
+++ b/packages/core/src/figma-api/accessors/layout.ts
@@ -4,12 +4,18 @@ import {
layoutSizingError,
layoutSizingUpdates,
lockedAspectRatioTarget,
+ type LayoutGrid,
type LayoutMode,
type LayoutSizing,
type LayoutSizingAxis,
type SceneNode,
type Vector
} from '@open-pencil/scene-graph'
+import {
+ AUTO_LAYOUT_GRID_COUNT,
+ isAutoGridCount,
+ layoutGridCount
+} from '@open-pencil/scene-graph/layout'
import {
prepareFollowedFieldEdit,
@@ -21,12 +27,47 @@ import {
type ProxyThis
} from '#core/figma-api/accessor-utils'
+/** A guide in Figma's plugin shape, whether it was set that way or read from a file. */
+function figmaLayoutGrid(grid: LayoutGrid): Readonly<LayoutGrid> {
+ const visible = grid.visible ?? true
+ const color = { ...(grid.color ?? { r: 1, g: 0, b: 0, a: 0.1 }) }
+ if (grid.pattern === 'GRID')
+ return Object.freeze({ pattern: 'GRID', sectionSize: grid.sectionSize ?? 10, visible, color })
+ const rows = grid.pattern === 'ROWS' || (grid.pattern !== 'COLUMNS' && grid.axis === 'Y')
+ const alignment = grid.alignment ?? grid.type ?? 'STRETCH'
+ return Object.freeze({
+ pattern: rows ? 'ROWS' : 'COLUMNS',
+ alignment,
+ gutterSize: grid.gutterSize ?? 0,
+ count: layoutGridCount(grid) === AUTO_LAYOUT_GRID_COUNT ? null : layoutGridCount(grid),
+ // A stretched guide's sections fill the frame, so Figma reports no section size for it.
+ ...(alignment === 'STRETCH' ? {} : { sectionSize: grid.sectionSize ?? 0 }),
+ offset: grid.offset ?? 0,
+ visible,
+ color
+ })
+}
+
export function installLayoutNodeProxyAccessors(
prototype: object,
internals: NodeProxyInternals
): void {
Object.defineProperties(prototype, {
layoutMode: simpleAccessor(internals, 'layoutMode'),
+ // Figma's grids, as a frame's Layout guide section shows them.
+ layoutGrids: {
+ get(this: ProxyThis): readonly LayoutGrid[] {
+ return Object.freeze(raw(this, internals).layoutGrids.map(figmaLayoutGrid))
+ },
+ set(this: ProxyThis, value: readonly LayoutGrid[]) {
+ if (!Array.isArray(value)) throw new TypeError('layoutGrids must be an array')
+ // An Auto count is stored as the archive stores it, so it survives copies and saves.
+ const grids = structuredClone([...value]).map((grid) =>
+ isAutoGridCount(grid.count) ? { ...grid, count: AUTO_LAYOUT_GRID_COUNT } : grid
+ )
+ updateNode(this, internals, { layoutGrids: grids })
+ }
+ },
layoutDirection: {
get(this: ProxyThis): string {
const node = raw(this, internals)
diff --git a/packages/core/src/figma-api/components.ts b/packages/core/src/figma-api/components.ts
index 409ad81a4..ca66a5888 100644
--- a/packages/core/src/figma-api/components.ts
+++ b/packages/core/src/figma-api/components.ts
@@ -13,12 +13,22 @@ import {
removeComponentProperty,
createComponentPropertyId,
exposedInstances,
- instanceExposureIssue
+ instanceExposureIssue,
+ resolveComponentPropertyValue
} from '@open-pencil/scene-graph'
import { cloneNodeProps } from '@open-pencil/scene-graph/copy'
import { becomesComponent, componentWrapProps } from '#core/editor/components/create'
+import {
+ measurePropertyText,
+ reapplyInstanceComponentProperties
+} from '#core/editor/components/properties'
import { applyVariantProperties, variantSetProps } from '#core/editor/components/variant-set'
+import {
+ findExactVariant,
+ getComponentSet,
+ variantValues
+} from '#core/editor/components/variants/model'
import { wrapNodes } from '#core/editor/structure/container-wrap'
import type { NodeProxyInternals, ProxyThis } from './accessor-utils'
@@ -310,6 +320,34 @@ function propertyReferenceName(field: ComponentPropertyReferenceField): string {
if (field === 'SLOT_CONTENT') return 'slotContentId'
return field === 'TEXT' ? 'characters' : 'visible'
}
+interface PropertyValue {
+ definition: ComponentPropertyDefinition
+ value: string | boolean
+}
+
+/**
+ * Switches an instance to the variant with the given values, the rest kept, as Figma's
+ * `setProperties` does; a combination no variant has fails without changing anything.
+ */
+function switchVariant(scene: SceneGraph, instance: SceneNode, values: PropertyValue[]): void {
+ const component = instance.componentId ? scene.getNode(instance.componentId) : undefined
+ const setId = component?.parentId
+ const target =
+ component && setId && getComponentSet(scene, setId)
+ ? findExactVariant(scene, setId, {
+ ...variantValues(scene, setId, component),
+ ...Object.fromEntries(
+ values.map(({ definition, value }) => [definition.name, String(value)])
+ )
+ })
+ : undefined
+ if (!target)
+ throw new Error('in setProperties: Unable to find a variant with those property values')
+ if (target.id === instance.componentId) return
+ scene.swapInstanceComponent(instance.id, target.id)
+ reapplyInstanceComponentProperties({ graph: scene }, instance.id)
+}
+
function applyProperty(
target: ProxyThis,
internals: NodeProxyInternals,
@@ -317,16 +355,10 @@ function applyProperty(
definition: ComponentPropertyDefinition,
value: string | boolean
): void {
- if (definition.type === 'VARIANT') {
- throw new Error('setProperties() cannot set VARIANT properties through the adapter')
- }
- const result = applyComponentPropertyValue(
- graph(target, internals),
- node.id,
- definition,
- String(value)
- )
+ const scene = graph(target, internals)
+ const result = applyComponentPropertyValue(scene, node.id, definition, String(value))
if (!result) throw new Error(`Unable to apply component property: ${propertyName(definition)}`)
+ measurePropertyText({ graph: scene }, node.id, definition)
}
export function installComponentPropertyAccessors(
prototype: object,
@@ -420,10 +452,29 @@ export function installComponentPropertyAccessors(
const node = raw(this, internals)
if (node.type !== 'INSTANCE')
throw new Error('setProperties() can only be called on instances')
- for (const [name, value] of Object.entries(properties)) {
+ // Figma checks every name and the variant they make before changing anything.
+ const values = Object.entries(properties).map(([name, value]) => {
const definition = findDefinition(this, internals, name)
- if (!definition) throw new Error(`Unknown component property: ${name}`)
- applyProperty(this, internals, node, definition, value)
+ if (!definition)
+ throw new Error(
+ `in setProperties: Could not find a component property with name: '${name}'`
+ )
+ return { definition, value }
+ })
+ const scene = graph(this, internals)
+ const unresolved = values.find(
+ ({ definition, value }) =>
+ definition.type === 'INSTANCE_SWAP' &&
+ !resolveComponentPropertyValue(scene, String(value))
+ )
+ if (unresolved)
+ throw new Error(
+ `Unable to apply component property: ${propertyName(unresolved.definition)}`
+ )
+ const variant = values.filter(({ definition }) => definition.type === 'VARIANT')
+ if (variant.length > 0) switchVariant(scene, node, variant)
+ for (const { definition, value } of values) {
+ if (definition.type !== 'VARIANT') applyProperty(this, internals, node, definition, value)
}
}
},
diff --git a/packages/core/src/figma-api/index.ts b/packages/core/src/figma-api/index.ts
index b052d04f2..009fcc07a 100644
--- a/packages/core/src/figma-api/index.ts
+++ b/packages/core/src/figma-api/index.ts
@@ -63,6 +63,7 @@ const noop = () => undefined
export { FigmaNodeProxy } from './proxy'
export { getPageBackgrounds, setPageBackgrounds } from './page-backgrounds'
+export { flushPendingLayout } from './pending-layout'
export type { FigmaEffect } from './effects'
export type { ExportImageOptions } from './types'
export type {
diff --git a/packages/core/src/figma-api/proxy.ts b/packages/core/src/figma-api/proxy.ts
index fa1ccf60d..5c2bd5639 100644
--- a/packages/core/src/figma-api/proxy.ts
+++ b/packages/core/src/figma-api/proxy.ts
@@ -11,6 +11,7 @@ import type {
NodeType,
Fill,
Stroke,
+ LayoutGrid,
LayoutMode
} from '@open-pencil/scene-graph'
import {
@@ -122,6 +123,7 @@ export class FigmaNodeProxy {
declare cornerSmoothing: number
declare layoutMode: LayoutMode
+ declare layoutGrids: readonly LayoutGrid[]
declare layoutDirection: string
declare primaryAxisAlignItems: string
declare counterAxisAlignItems: string
diff --git a/packages/core/tests/editor/clipboard/placement.test.ts b/packages/core/tests/editor/clipboard/placement.test.ts
index 275ea5865..2710c9dcd 100644
--- a/packages/core/tests/editor/clipboard/placement.test.ts
+++ b/packages/core/tests/editor/clipboard/placement.test.ts
@@ -433,3 +433,68 @@ describe('paste orientation', () => {
}
})
})
+
+// Repeats Figma desktop 126: a paste with nothing selected.
+describe('paste with nothing selected', () => {
+ function sourceSetup() {
+ const page = setup()
+ editor.state.zoom = 0.2
+ const frame = node('FRAME', page, { x: 1000, y: 100, width: 300, height: 200 })
+ const box = node('RECTANGLE', frame.id, { x: 40, y: 50, width: 60, height: 30 })
+ return { page, frame, box }
+ }
+
+ async function pasteWithNothingSelected(snapshot: Awaited<ReturnType<typeof copy>>) {
+ editor.select([])
+ await editor.pasteSnapshot(snapshot)
+ return selected()
+ }
+
+ test('a layer copied out of a frame or section goes back into it', async () => {
+ const { page, frame, box } = sourceSetup()
+ expect(await pasteWithNothingSelected(await copy(box.id))).toMatchObject({
+ parentId: frame.id,
+ x: 40,
+ y: 50
+ })
+ const section = node('SECTION', page, { x: 1400, y: 100, width: 400, height: 300 })
+ const inSection = node('RECTANGLE', section.id, { x: 30, y: 40 })
+ expect(await pasteWithNothingSelected(await copy(inSection.id))).toMatchObject({
+ parentId: section.id,
+ x: 30,
+ y: 40
+ })
+ })
+
+ test('it keeps its place on the canvas from when it was copied, even after the frame moved', async () => {
+ const { frame, box } = sourceSetup()
+ const snapshot = await copy(box.id)
+ editor.graph.updateNode(frame.id, { y: 500 })
+ expect(await pasteWithNothingSelected(snapshot)).toMatchObject({
+ parentId: frame.id,
+ x: 40,
+ y: -350
+ })
+ })
+
+ test('out of view it goes onto the page, in the middle of the view', async () => {
+ const { page, box } = sourceSetup()
+ const snapshot = await copy(box.id)
+ editor.state.panX = -20000
+ editor.state.panY = -20000
+ const pasted = await pasteWithNothingSelected(snapshot)
+ expect(pasted.parentId).toBe(page)
+ expect(worldCenter(pasted)).toEqual({ x: 102000, y: 101500 })
+ })
+
+ test('a layer whose frame is gone goes onto the page where it was', async () => {
+ const { page, frame, box } = sourceSetup()
+ const snapshot = await copy(box.id)
+ editor.graph.deleteNode(frame.id)
+ expect(await pasteWithNothingSelected(snapshot)).toMatchObject({
+ parentId: page,
+ x: 1040,
+ y: 150
+ })
+ })
+})
diff --git a/packages/core/tests/editor/structure/layer-type.test.ts b/packages/core/tests/editor/structure/layer-type.test.ts
new file mode 100644
index 000000000..e0c7a1fc4
--- /dev/null
+++ b/packages/core/tests/editor/structure/layer-type.test.ts
@@ -0,0 +1,136 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core/editor'
+import { getAxisAlignedWorldBounds } from '@open-pencil/scene-graph/coordinate'
+
+// Each case repeats the layer type menu in Figma desktop 126's properties panel.
+
+function setup() {
+ const editor = createEditor()
+ const page = editor.state.currentPageId
+ const frame = editor.graph.createNode('FRAME', page, {
+ x: 9000,
+ y: 100,
+ width: 200,
+ height: 150,
+ fills: [{ type: 'SOLID', color: { r: 0.9, g: 0.9, b: 1, a: 1 }, opacity: 1, visible: true }],
+ strokes: [
+ {
+ type: 'SOLID',
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ opacity: 1,
+ visible: true,
+ weight: 1,
+ align: 'INSIDE'
+ }
+ ],
+ cornerRadius: 8,
+ clipsContent: true,
+ opacity: 0.8,
+ effects: [
+ {
+ type: 'DROP_SHADOW',
+ color: { r: 0, g: 0, b: 0, a: 0.25 },
+ offset: { x: 0, y: 4 },
+ radius: 4,
+ spread: 0,
+ visible: true
+ }
+ ]
+ })
+ const box = editor.graph.createNode('RECTANGLE', frame.id, {
+ x: 20,
+ y: 30,
+ width: 50,
+ height: 40
+ })
+ // Sticks out past the frame's right and bottom edges.
+ const dot = editor.graph.createNode('ELLIPSE', frame.id, {
+ x: 180,
+ y: 120,
+ width: 60,
+ height: 60
+ })
+ return { editor, frame, box, dot }
+}
+
+const canvasBox = (editor: ReturnType<typeof createEditor>, id: string) => {
+ const node = editor.graph.getNode(id)
+ if (!node) throw new Error(`Missing ${id}`)
+ const { x, y, width, height } = getAxisAlignedWorldBounds(node, editor.graph)
+ return [x, y, width, height]
+}
+
+describe('layer type menu', () => {
+ test('a frame becomes a group in place, fitting its layers and keeping its effects', () => {
+ const { editor, frame, box, dot } = setup()
+ const boxBefore = canvasBox(editor, box.id)
+ const dotBefore = canvasBox(editor, dot.id)
+ editor.convertLayerType(frame.id, 'GROUP')
+ const group = editor.graph.getNode(frame.id)
+ expect(group).toMatchObject({
+ type: 'GROUP',
+ fills: [],
+ strokes: [],
+ cornerRadius: 0,
+ opacity: 0.8
+ })
+ expect(group?.effects).toHaveLength(1)
+ expect(canvasBox(editor, frame.id)).toEqual([9020, 130, 220, 150])
+ expect(canvasBox(editor, box.id)).toEqual(boxBefore)
+ expect(canvasBox(editor, dot.id)).toEqual(dotBefore)
+
+ editor.undo.undo()
+ expect(editor.graph.getNode(frame.id)).toMatchObject({
+ type: 'FRAME',
+ x: 9000,
+ y: 100,
+ width: 200,
+ height: 150,
+ cornerRadius: 8,
+ clipsContent: true
+ })
+ expect(editor.graph.getNode(frame.id)?.fills).toHaveLength(1)
+ expect(canvasBox(editor, dot.id)).toEqual(dotBefore)
+ editor.undo.redo()
+ expect(editor.graph.getNode(frame.id)?.type).toBe('GROUP')
+ expect(canvasBox(editor, frame.id)).toEqual([9020, 130, 220, 150])
+ })
+
+ test('a group becomes a frame of its bounds that clips, with no fill', () => {
+ const { editor, frame } = setup()
+ editor.convertLayerType(frame.id, 'GROUP')
+ editor.convertLayerType(frame.id, 'FRAME')
+ expect(editor.graph.getNode(frame.id)).toMatchObject({
+ type: 'FRAME',
+ fills: [],
+ clipsContent: true,
+ opacity: 0.8
+ })
+ expect(canvasBox(editor, frame.id)).toEqual([9020, 130, 220, 150])
+ })
+
+ test('undo brings back a frame’s linked fill, stroke, and guide styles', () => {
+ const { editor, frame } = setup()
+ const styles = { fillStyleId: '1:10', strokeStyleId: '1:11', gridStyleId: '1:12' }
+ editor.graph.updateNode(frame.id, styles)
+ editor.convertLayerType(frame.id, 'GROUP')
+ expect(editor.graph.getNode(frame.id)).toMatchObject({
+ fillStyleId: null,
+ strokeStyleId: null,
+ gridStyleId: null
+ })
+ editor.undo.undo()
+ expect(editor.graph.getNode(frame.id)).toMatchObject(styles)
+ })
+
+ test('an empty frame has nothing to group', () => {
+ const editor = createEditor()
+ const frame = editor.graph.createNode('FRAME', editor.state.currentPageId, {
+ width: 100,
+ height: 100
+ })
+ editor.convertLayerType(frame.id, 'GROUP')
+ expect(editor.graph.getNode(frame.id)?.type).toBe('FRAME')
+ })
+})
diff --git a/packages/core/tests/figma-api/resize-constraints.test.ts b/packages/core/tests/figma-api/resize-constraints.test.ts
new file mode 100644
index 000000000..fd9d38333
--- /dev/null
+++ b/packages/core/tests/figma-api/resize-constraints.test.ts
@@ -0,0 +1,67 @@
+import { expect, test } from 'bun:test'
+
+import { FigmaAPI, type FigmaNodeProxy } from '@open-pencil/core/figma-api'
+import { hasInstanceOverride, SceneGraph } from '@open-pencil/scene-graph'
+
+// Recorded with the same script in Figma desktop 126.
+
+function setup(kind: 'frame' | 'component', graph = new SceneGraph()) {
+ const figma = new FigmaAPI(graph)
+ const host = kind === 'component' ? figma.createComponent() : figma.createFrame()
+ host.resize(100, 100)
+ for (const [name, constraint] of [
+ ['max', 'MAX'],
+ ['stretch', 'STRETCH'],
+ ['scale', 'SCALE']
+ ] as const) {
+ const layer = figma.createRectangle()
+ layer.name = name
+ host.appendChild(layer)
+ layer.x = 10
+ layer.y = 10
+ layer.resize(30, 30)
+ layer.constraints = { horizontal: constraint, vertical: constraint }
+ }
+ return host
+}
+
+const places = (node: FigmaNodeProxy) =>
+ (node.children as FigmaNodeProxy[]).map((child) => [
+ child.name,
+ child.x,
+ child.y,
+ child.width,
+ child.height
+ ])
+
+const CONSTRAINED = [
+ ['max', 110, 60, 30, 30],
+ ['stretch', 10, 10, 130, 80],
+ ['scale', 20, 15, 60, 45]
+]
+
+test('resize places a frame’s layers by their constraints; resizeWithoutConstraints does not', () => {
+ const frame = setup('frame')
+ frame.resize(200, 150)
+ expect(places(frame)).toEqual(CONSTRAINED)
+ const still = setup('frame')
+ still.resizeWithoutConstraints(200, 150)
+ expect(places(still).map(([, ...rect]) => rect)).toEqual([
+ [10, 10, 30, 30],
+ [10, 10, 30, 30],
+ [10, 10, 30, 30]
+ ])
+})
+
+test('an instance’s layers follow their constraints either way, claiming only its own size', () => {
+ const graph = new SceneGraph()
+ const component = setup('component', graph)
+ for (const resize of ['resize', 'resizeWithoutConstraints'] as const) {
+ const instance = component.createInstance()
+ instance[resize](200, 150)
+ expect(places(instance)).toEqual(CONSTRAINED)
+ expect(hasInstanceOverride(graph, instance.id, 'width')).toBe(true)
+ for (const layer of instance.children as FigmaNodeProxy[])
+ expect(hasInstanceOverride(graph, layer.id, 'width')).toBe(false)
+ }
+})
diff --git a/packages/core/tests/figma-api/set-properties.test.ts b/packages/core/tests/figma-api/set-properties.test.ts
new file mode 100644
index 000000000..5feb024c2
--- /dev/null
+++ b/packages/core/tests/figma-api/set-properties.test.ts
@@ -0,0 +1,73 @@
+import { 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.
+
+function setup() {
+ const figma = new FigmaAPI(new SceneGraph())
+ const labels: ReturnType<FigmaAPI['createText']>[] = []
+ const variant = (size: string, state: string, width: number) => {
+ const component = figma.createComponent()
+ component.name = `Size=${size}, State=${state}`
+ component.resize(width, 40)
+ const label = figma.createText()
+ label.name = 'Label'
+ label.characters = `${size} ${state}`
+ component.appendChild(label)
+ labels.push(label)
+ return component
+ }
+ const variants = [
+ variant('Small', 'Default', 80),
+ variant('Large', 'Default', 160),
+ variant('Small', 'Hover', 80)
+ ]
+ const set = figma.combineAsVariants(variants, figma.currentPage)
+ const text = set.addComponentProperty('Text', 'TEXT', 'Click')
+ for (const label of labels) label.componentPropertyReferences = { characters: text }
+ const icon = figma.createComponent()
+ const swap = set.addComponentProperty('Icon', 'INSTANCE_SWAP', icon.id)
+ const instance = variants[0].createInstance()
+ instance.setProperties({ [text]: 'Buy' })
+ const state = () => ({
+ main: instance.mainComponent?.name,
+ text: instance.componentProperties[text]?.value,
+ width: instance.width
+ })
+ return { instance, text, swap, state }
+}
+
+test('setProperties switches variants, one value or several, and keeps other properties', () => {
+ const { instance, text, state } = setup()
+ instance.setProperties({ Size: 'Large' })
+ expect(state()).toEqual({ main: 'Size=Large, State=Default', text: 'Buy', width: 160 })
+ instance.setProperties({ Size: 'Small', State: 'Hover' })
+ expect(state()).toEqual({ main: 'Size=Small, State=Hover', text: 'Buy', width: 80 })
+ instance.setProperties({ Size: 'Small', State: 'Default', [text]: 'Again' })
+ expect(state()).toEqual({ main: 'Size=Small, State=Default', text: 'Again', width: 80 })
+})
+
+test('setProperties changes nothing when no variant has the values, or a name is unknown', () => {
+ const { instance, text, state } = setup()
+ instance.setProperties({ State: 'Hover' })
+ const before = state()
+ const missing = 'in setProperties: Unable to find a variant with those property values'
+ expect(() => instance.setProperties({ Size: 'Large' })).toThrow(missing)
+ expect(() => instance.setProperties({ Size: 'Nope' })).toThrow(missing)
+ expect(() => instance.setProperties({ [text]: 'Lost', State: 'Bogus' })).toThrow(missing)
+ expect(() => instance.setProperties({ Colour: 'Red' })).toThrow(
+ "in setProperties: Could not find a component property with name: 'Colour'"
+ )
+ expect(state()).toEqual(before)
+})
+
+test('setProperties changes nothing when an instance swap value is no component', () => {
+ const { instance, text, swap, state } = setup()
+ const before = state()
+ expect(() =>
+ instance.setProperties({ Size: 'Large', [text]: 'Lost', [swap]: 'missing' })
+ ).toThrow('Unable to apply component property: Icon')
+ expect(state()).toEqual(before)
+})
diff --git a/packages/core/tests/io/formats/fig/export/gold-edit.test.ts b/packages/core/tests/io/formats/fig/export/gold-edit.test.ts
index 45cd63ff5..607472f8b 100644
--- a/packages/core/tests/io/formats/fig/export/gold-edit.test.ts
+++ b/packages/core/tests/io/formats/fig/export/gold-edit.test.ts
@@ -95,7 +95,9 @@ test('Gold document exposes effective Boolean assignments and supports editor un
return avatar?.componentId ? restored.getNode(avatar.componentId)?.name : undefined
})
).toEqual(originalComponents)
- expect({ width: input.width, height: input.height }).toEqual(originalInputSize)
+ // Setting the property lays the instance out again, which may move the size by float error.
+ expect(input.width).toBeCloseTo(originalInputSize.width, 3)
+ expect(input.height).toBeCloseTo(originalInputSize.height, 3)
expect(
restoredContents.map((node) => {
const avatar = restored
diff --git a/packages/core/tests/io/formats/fig/roundtrip/instance-overrides.test.ts b/packages/core/tests/io/formats/fig/roundtrip/instance-overrides.test.ts
index 4fd47a059..14423da91 100644
--- a/packages/core/tests/io/formats/fig/roundtrip/instance-overrides.test.ts
+++ b/packages/core/tests/io/formats/fig/roundtrip/instance-overrides.test.ts
@@ -27,7 +27,10 @@ test('instance style overrides come back as overrides after saving and reopening
const reopened = await parseFigFile((await exportFigFile(graph)).slice().buffer)
const nodes = [...reopened.getAllNodes()]
- const copy = expectDefined(nodes.find((node) => node.type === 'INSTANCE'), 'reopened instance')
+ const copy = expectDefined(
+ nodes.find((node) => node.type === 'INSTANCE'),
+ 'reopened instance'
+ )
const component = expectDefined(nodes.find((node) => node.type === 'COMPONENT'))
const [reopenedBar, reopenedLabel] = reopened.getChildren(copy.id)
expect(reopenedBar.strokeWeight).toBe(6)
@@ -35,7 +38,11 @@ test('instance style overrides come back as overrides after saving and reopening
expect(reopenedBar.cornerSmoothing).toBeCloseTo(0.6)
expect(reopenedLabel.letterSpacing).toBe(2)
expect(reopenedLabel.styleRuns).toEqual([
- expect.objectContaining({ start: 0, length: 5, style: expect.objectContaining({ fontSize: 30 }) })
+ expect.objectContaining({
+ start: 0,
+ length: 5,
+ style: expect.objectContaining({ fontSize: 30 })
+ })
])
for (const [layer, field] of [
[reopenedBar, 'strokeWeight'],
@@ -53,3 +60,41 @@ test('instance style overrides come back as overrides after saving and reopening
expect([reopenedBar.strokeWeight, reopenedBar.strokeAlign]).toEqual([6, 'OUTSIDE'])
expect([reopenedLabel.letterSpacing, reopenedLabel.textCase]).toEqual([2, 'UPPER'])
})
+
+test('an instance that clears its component’s fill style keeps it cleared after reopening', async () => {
+ // Figma desktop 126 claims the cleared style as the unset GUID, with the paints it keeps.
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const red = {
+ type: 'SOLID' as const,
+ color: { r: 1, g: 0, b: 0, a: 1 },
+ opacity: 1,
+ visible: true
+ }
+ const style = graph.createNode('RECTANGLE', page, {
+ name: 'Red',
+ sharedStyleType: 'FILL',
+ fills: [red]
+ })
+ const card = graph.createNode('COMPONENT', page, { name: 'Card', width: 100, height: 100 })
+ graph.createNode('RECTANGLE', card.id, { name: 'Box', fills: [red], fillStyleId: style.id })
+ const instance = expectDefined(graph.createInstance(card.id, page))
+ const [box] = graph.getChildren(instance.id)
+ graph.updateNode(box.id, { fillStyleId: null })
+ recordInstanceOverride(graph, box.id, ['fillStyleId', 'fills'])
+
+ const reopened = await parseFigFile((await exportFigFile(graph)).slice().buffer)
+ const nodes = [...reopened.getAllNodes()]
+ const copy = expectDefined(nodes.find((node) => node.type === 'INSTANCE'))
+ const component = expectDefined(nodes.find((node) => node.type === 'COMPONENT'))
+ const [reopenedBox] = reopened.getChildren(copy.id)
+ const [componentBox] = reopened.getChildren(component.id)
+ expect(componentBox.fillStyleId).toBeTruthy()
+ expect(reopenedBox.fillStyleId).toBeFalsy()
+ expect(hasInstanceOverride(reopened, reopenedBox.id, 'fillStyleId')).toBe(true)
+ reopened.syncInstances(component.id)
+ expect(reopenedBox.fillStyleId).toBeFalsy()
+ expect(reopenedBox.fills).toEqual([
+ expect.objectContaining({ color: expect.objectContaining({ r: 1 }) })
+ ])
+})
diff --git a/packages/core/tests/io/formats/fig/roundtrip/layout-guides.test.ts b/packages/core/tests/io/formats/fig/roundtrip/layout-guides.test.ts
new file mode 100644
index 000000000..7bd55f603
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/roundtrip/layout-guides.test.ts
@@ -0,0 +1,121 @@
+import { beforeAll, expect, test } from 'bun:test'
+
+import { exportFigFile, initCodec, parseFigFile, SceneGraph } from '@open-pencil/core'
+import { FigmaAPI, type FigmaNodeProxy } from '@open-pencil/core/figma-api'
+
+beforeAll(async () => {
+ await initCodec()
+})
+
+// Colors a float32 archive keeps exactly.
+const red = { r: 1, g: 0, b: 0, a: 0.25 }
+const blue = { r: 0, g: 0, b: 1, a: 0.5 }
+const green = { r: 0, g: 0.5, b: 0, a: 0.125 }
+
+async function reopen(graph: SceneGraph) {
+ return parseFigFile((await exportFigFile(graph)).slice().buffer)
+}
+
+const guidesOf = (graph: SceneGraph) =>
+ new FigmaAPI(graph).currentPage.findOne((node: FigmaNodeProxy) => node.name === 'Guides')
+ ?.layoutGrids
+
+test('layout guides set from a script or the panel save and reopen in Figma’s shape', async () => {
+ const graph = new SceneGraph()
+ const figma = new FigmaAPI(graph)
+ const frame = figma.createFrame()
+ frame.name = 'Guides'
+ frame.layoutGrids = [
+ {
+ pattern: 'COLUMNS',
+ alignment: 'STRETCH',
+ gutterSize: 20,
+ count: 5,
+ offset: 0,
+ visible: true,
+ color: red
+ },
+ {
+ pattern: 'ROWS',
+ alignment: 'MIN',
+ gutterSize: 8,
+ count: 3,
+ sectionSize: 40,
+ offset: 4,
+ visible: false,
+ color: blue
+ },
+ // Figma reports an Auto count, set as `Infinity`, as `null`.
+ {
+ pattern: 'COLUMNS',
+ alignment: 'CENTER',
+ gutterSize: 10,
+ count: Infinity,
+ sectionSize: 40,
+ offset: 0,
+ visible: true,
+ color: green
+ },
+ { pattern: 'GRID', sectionSize: 10, visible: true, color: green }
+ ]
+ expect(guidesOf(await reopen(graph))).toEqual([
+ {
+ pattern: 'COLUMNS',
+ alignment: 'STRETCH',
+ gutterSize: 20,
+ count: 5,
+ offset: 0,
+ visible: true,
+ color: red
+ },
+ {
+ pattern: 'ROWS',
+ alignment: 'MIN',
+ gutterSize: 8,
+ count: 3,
+ sectionSize: 40,
+ offset: 4,
+ visible: false,
+ color: blue
+ },
+ {
+ pattern: 'COLUMNS',
+ alignment: 'CENTER',
+ gutterSize: 10,
+ count: null,
+ sectionSize: 40,
+ offset: 0,
+ visible: true,
+ color: green
+ },
+ { pattern: 'GRID', sectionSize: 10, visible: true, color: green }
+ ])
+})
+
+test('a count edited on a guide read from a file is the count that saves', async () => {
+ const graph = new SceneGraph()
+ const frame = new FigmaAPI(graph).createFrame()
+ frame.name = 'Guides'
+ frame.layoutGrids = [
+ { pattern: 'COLUMNS', alignment: 'STRETCH', gutterSize: 20, count: 5, offset: 0 }
+ ]
+ const opened = await reopen(graph)
+ const node = [...opened.getAllNodes()].find((item) => item.name === 'Guides')
+ if (!node) throw new Error('Missing frame')
+ // The panel edits the count it shows, over the file's own.
+ opened.updateNode(node.id, {
+ layoutGrids: node.layoutGrids.map((grid) => ({ ...grid, count: 8 }))
+ })
+ expect(guidesOf(await reopen(opened))?.map((grid) => grid.count)).toEqual([8])
+})
+
+test('a grid saved without a size is Figma’s 10 px one', async () => {
+ const graph = new SceneGraph()
+ graph.createNode('FRAME', graph.getPages()[0].id, {
+ name: 'Guides',
+ layoutGrids: [{ pattern: 'GRID', color: blue }]
+ })
+ expect(guidesOf(await reopen(graph))).toEqual([
+ { pattern: 'GRID', sectionSize: 10, visible: true, color: blue }
+ ])
+})
diff --git a/packages/fig/src/instance-overrides/fields.ts b/packages/fig/src/instance-overrides/fields.ts
index a136c6967..55c9277c3 100644
--- a/packages/fig/src/instance-overrides/fields.ts
+++ b/packages/fig/src/instance-overrides/fields.ts
@@ -1,7 +1,11 @@
import { groupBy } from 'es-toolkit'
+import { UNSET_GUID } from '@open-pencil/kiwi/fig/guid'
import type { SceneNode } from '@open-pencil/scene-graph'
+/** The style reference Figma writes for a style an instance has cleared. */
+export const CLEARED_STYLE = { guid: { ...UNSET_GUID } }
+
/**
* How a claim on a raw Kiwi field maps onto SceneGraph. Materialization records the
* mapped scene fields as overridden, uniform scale multiplies `length` values, and
@@ -93,9 +97,10 @@ export const OVERRIDE_FIELDS = {
effects: { scene: ['effects'], kind: 'node', absent: [] },
locked: { scene: ['locked'], kind: 'node', absent: false },
layoutGrids: { scene: ['layoutGrids'], kind: 'node', absent: [] },
- styleIdForFill: { scene: ['fillStyleId'], kind: 'node' },
- styleIdForStrokeFill: { scene: ['strokeStyleId'], kind: 'node' },
- styleIdForEffect: { scene: ['effectStyleId'], kind: 'node' },
+ // An instance that clears a style the component applies claims the unset GUID (desktop 126).
+ styleIdForFill: { scene: ['fillStyleId'], kind: 'node', absent: CLEARED_STYLE },
+ styleIdForStrokeFill: { scene: ['strokeStyleId'], kind: 'node', absent: CLEARED_STYLE },
+ styleIdForEffect: { scene: ['effectStyleId'], kind: 'node', absent: CLEARED_STYLE },
stackPrimaryAlignItems: { scene: ['primaryAxisAlign'], kind: 'node' },
stackCounterAlignItems: { scene: ['counterAxisAlign'], kind: 'node' },
stackPositioning: { scene: ['layoutPositioning'], kind: 'node' },
diff --git a/packages/fig/src/node-change/export/node.ts b/packages/fig/src/node-change/export/node.ts
index 06d26ec0a..8c2bc7213 100644
--- a/packages/fig/src/node-change/export/node.ts
+++ b/packages/fig/src/node-change/export/node.ts
@@ -6,6 +6,7 @@ import { stringToGuid } from '@open-pencil/kiwi/fig/guid'
import type {
ComponentPropertyDefinition,
ComponentPropertyReferenceField,
+ LayoutGrid,
SceneGraph,
SceneNode
} from '@open-pencil/scene-graph'
@@ -15,6 +16,7 @@ import {
OPEN_PENCIL_PLUGIN_DATA,
withPluginData
} from '@open-pencil/scene-graph'
+import { layoutGridCount } from '@open-pencil/scene-graph/layout'
import { siblingOrderKeys } from '@open-pencil/scene-graph/order-keys'
import type { GUID, Matrix, Vector } from '@open-pencil/scene-graph/primitives'
@@ -803,6 +805,26 @@ function nodeForGeometryExport(node: SceneNode): SceneNode {
}
}
+/**
+ * A layout guide as the archive stores it: stripes along an axis or a grid, whichever shape it was
+ * given in, Figma's plugin names (`COLUMNS`, `count`, `alignment`) or the archive's own.
+ */
+function kiwiLayoutGrid(grid: LayoutGrid): LayoutGrid {
+ const rows = grid.pattern === 'ROWS' || (grid.pattern !== 'COLUMNS' && grid.axis === 'Y')
+ return {
+ type: grid.type ?? grid.alignment ?? 'STRETCH',
+ axis: rows ? 'Y' : 'X',
+ visible: grid.visible ?? true,
+ numSections: layoutGridCount(grid),
+ offset: grid.offset ?? 0,
+ // Figma's new grid is 10 px, the size the plugin API reports for one without a size.
+ sectionSize: grid.sectionSize ?? (grid.pattern === 'GRID' ? 10 : 0),
+ gutterSize: grid.gutterSize ?? 0,
+ color: grid.color ?? { r: 1, g: 0, b: 0, a: 0.1 },
+ pattern: grid.pattern === 'GRID' ? 'GRID' : 'STRIPES'
+ }
+}
+
function applySharedStyleProps(
context: SceneNodeToKiwiContext,
node: SceneNode,
@@ -814,7 +836,7 @@ function applySharedStyleProps(
if (node.textStyleId) nc.styleIdForText = reference(node.textStyleId)
if (node.effectStyleId) nc.styleIdForEffect = reference(node.effectStyleId)
if (node.gridStyleId) nc.styleIdForGrid = reference(node.gridStyleId)
- if (node.layoutGrids.length > 0) nc.layoutGrids = structuredClone(node.layoutGrids)
+ if (node.layoutGrids.length > 0) nc.layoutGrids = node.layoutGrids.map(kiwiLayoutGrid)
if (node.guides.length > 0) nc.guides = exportCanvasGuides(node.guides)
}
diff --git a/packages/fig/src/node-change/export/override-claims.ts b/packages/fig/src/node-change/export/override-claims.ts
index 9d9f3daf6..0f795aad5 100644
--- a/packages/fig/src/node-change/export/override-claims.ts
+++ b/packages/fig/src/node-change/export/override-claims.ts
@@ -1,4 +1,8 @@
-import { type OverrideField, SCENE_OVERRIDE_FIELDS } from '#fig/instance-overrides/fields'
+import {
+ CLEARED_STYLE,
+ type OverrideField,
+ SCENE_OVERRIDE_FIELDS
+} from '#fig/instance-overrides/fields'
import { compact } from 'es-toolkit'
import {
@@ -138,9 +142,11 @@ function rawClaim(
return { textData: { ...nodeFields().textData, characters } }
}
case 'text-style':
- return target.textStyleId
- ? { styleIdForText: exportedStyleReference(context, target.textStyleId) }
- : undefined
+ return {
+ styleIdForText: target.textStyleId
+ ? exportedStyleReference(context, target.textStyleId)
+ : structuredClone(CLEARED_STYLE)
+ }
case 'paint':
return raw === 'fillPaints'
? { fillPaints: createFillPaints(context, target) }
diff --git a/packages/scene-graph/src/hit-test.ts b/packages/scene-graph/src/hit-test.ts
index 82eaac84e..0543c83b0 100644
--- a/packages/scene-graph/src/hit-test.ts
+++ b/packages/scene-graph/src/hit-test.ts
@@ -49,20 +49,22 @@ function hasTransformedAncestor(
return transformed
}
+/** Whether the point lies in the node's box, grown by `pad` canvas units on every side. */
function containsPoint(
px: number,
py: number,
node: SceneNode,
graph: SceneGraph,
- transformCache: Map<string, boolean>
+ transformCache: Map<string, boolean>,
+ pad = 0
): boolean {
if (!hasTransformedAncestor(node, graph, transformCache)) {
const absolute = graph.getAbsolutePosition(node.id)
return (
- px >= absolute.x &&
- px <= absolute.x + node.width &&
- py >= absolute.y &&
- py <= absolute.y + node.height
+ px >= absolute.x - pad &&
+ px <= absolute.x + node.width + pad &&
+ py >= absolute.y - pad &&
+ py <= absolute.y + node.height + pad
)
}
@@ -72,7 +74,9 @@ function containsPoint(
if (!inv) return false
const [localX, localY] = Matrix.mapPoints(inv, [px, py])
- return localX >= 0 && localX <= node.width && localY >= 0 && localY <= node.height
+ return (
+ localX >= -pad && localX <= node.width + pad && localY >= -pad && localY <= node.height + pad
+ )
}
function hitTestOpaqueContainer(
@@ -82,10 +86,11 @@ function hitTestOpaqueContainer(
child: SceneNode,
childId: string,
deep: boolean,
- transformCache: Map<string, boolean>
+ transformCache: Map<string, boolean>,
+ pad: number
): SceneNode | null {
if (!containsPoint(px, py, child, graph, transformCache)) return null
- const childHit = hitTestChildren(graph, px, py, childId, deep, transformCache)
+ const childHit = hitTestChildren(graph, px, py, childId, deep, transformCache, pad)
if (childHit) return child
if (hasVisibleFillOrStroke(child)) return child
return null
@@ -97,17 +102,18 @@ function hitTestTransparentContainer(
child: SceneNode,
childId: string,
deep: boolean,
- transformCache: Map<string, boolean>
+ transformCache: Map<string, boolean>,
+ pad: number
): SceneNode | null {
if (child.type === 'GROUP') {
- if (!containsPoint(px, py, child, graph, transformCache)) return null
-
- if (deep) return hitTestChildren(graph, px, py, childId, deep, transformCache) ?? child
-
- return child
+ // A group fits its layers, so a padded click on one at its edge falls just outside it.
+ if (!containsPoint(px, py, child, graph, transformCache, pad)) return null
+ const childHit = hitTestChildren(graph, px, py, childId, deep, transformCache, pad)
+ if (childHit) return deep ? childHit : child
+ return containsPoint(px, py, child, graph, transformCache) ? child : null
}
- const childHit = hitTestChildren(graph, px, py, childId, deep, transformCache)
+ const childHit = hitTestChildren(graph, px, py, childId, deep, transformCache, pad)
if (childHit) {
if (child.locked) return child
return childHit
@@ -121,13 +127,18 @@ function hitTestTransparentContainer(
return null
}
+/**
+ * The topmost layer under the point among a container's children. `pad`, in canvas units, grows
+ * each leaf layer's box, as Figma takes a click a few screen pixels outside a shape.
+ */
function hitTestChildren(
graph: SceneGraph,
px: number,
py: number,
parentId: string,
deep = false,
- transformCache = new Map<string, boolean>()
+ transformCache = new Map<string, boolean>(),
+ pad = 0
): SceneNode | null {
const parent = graph.nodes.get(parentId)
if (!parent) return null
@@ -142,17 +153,26 @@ function hitTestChildren(
if (!child || child.internalOnly || !child.visible) continue
if (CONTAINER_TYPES.has(child.type)) {
if (OPAQUE_CONTAINER_TYPES.has(child.type) && !deep) {
- const hit = hitTestOpaqueContainer(graph, px, py, child, childId, deep, transformCache)
+ const hit = hitTestOpaqueContainer(graph, px, py, child, childId, deep, transformCache, pad)
if (hit) return hit
continue
}
- const hit = hitTestTransparentContainer(graph, px, py, child, childId, deep, transformCache)
+ const hit = hitTestTransparentContainer(
+ graph,
+ px,
+ py,
+ child,
+ childId,
+ deep,
+ transformCache,
+ pad
+ )
if (hit) return hit
continue
}
- if (containsPoint(px, py, child, graph, transformCache)) return child
+ if (containsPoint(px, py, child, graph, transformCache, pad)) return child
}
return null
@@ -172,10 +192,11 @@ export function hitTestDeep(
graph: SceneGraph,
px: number,
py: number,
- scopeId?: string
+ scopeId?: string,
+ pad = 0
): SceneNode | null {
const scope = scopeId ?? graph.rootId
- return hitTestChildren(graph, px, py, scope, true)
+ return hitTestChildren(graph, px, py, scope, true, new Map(), pad)
}
/**
@@ -253,9 +274,10 @@ export function hitTestSelectable(
px: number,
py: number,
scopeId: string,
- selectedIds: ReadonlySet<string>
+ selectedIds: ReadonlySet<string>,
+ pad = 0
): SceneNode | null {
- const deepest = hitTestChildren(graph, px, py, scopeId, true)
+ const deepest = hitTestChildren(graph, px, py, scopeId, true, new Map(), pad)
if (!deepest) {
const scope = graph.nodes.get(scopeId)
return scope ? frameChildAt(graph, scope, px, py) : null
diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.ts
index 99922204a..dd20cbd41 100644
--- a/packages/scene-graph/src/index.ts
+++ b/packages/scene-graph/src/index.ts
@@ -853,17 +853,19 @@ export class SceneGraph {
return HitTest.hitTest(this, px, py, scopeId)
}
- hitTestDeep(px: number, py: number, scopeId?: string): SceneNode | null {
- return HitTest.hitTestDeep(this, px, py, scopeId)
+ /** `pad`, in canvas units, grows each shape's box, as Figma takes clicks just outside one. */
+ hitTestDeep(px: number, py: number, scopeId?: string, pad = 0): SceneNode | null {
+ return HitTest.hitTestDeep(this, px, py, scopeId, pad)
}
hitTestSelectable(
px: number,
py: number,
scopeId: string,
- selectedIds: ReadonlySet<string>
+ selectedIds: ReadonlySet<string>,
+ pad = 0
): SceneNode | null {
- return HitTest.hitTestSelectable(this, px, py, scopeId, selectedIds)
+ return HitTest.hitTestSelectable(this, px, py, scopeId, selectedIds, pad)
}
hitTestOpenContainer(px: number, py: number, scopeId: string): SceneNode | null {
diff --git a/packages/scene-graph/src/instances.ts b/packages/scene-graph/src/instances.ts
index 88372a8c7..572037243 100644
--- a/packages/scene-graph/src/instances.ts
+++ b/packages/scene-graph/src/instances.ts
@@ -6,6 +6,7 @@ import {
hasInstanceOverride as hasNodeInstanceOverride,
setInstanceOverride
} from './instance-overrides'
+import { keepOwnContentSize } from './instances/content-size'
import {
createInstanceSyncContext,
groupCopyRemovals,
@@ -194,6 +195,8 @@ function syncInstancesOf(
if (isProtectedSyncField(instance, key, protectedField)) continue
copyProp(updates, source, key)
}
+ // An instance that hugs its layers sizes to what it shows, not to the component.
+ keepOwnContentSize(graph, updates, instance, source)
updateSyncedProps(graph, instance, updates)
const context = createInstanceSyncContext(instance.id, instance.instanceOverrides)
syncChildren(graph, component.id, instance.id, instance.instanceOverrides, context)
diff --git a/packages/scene-graph/src/instances/content-size.ts b/packages/scene-graph/src/instances/content-size.ts
new file mode 100644
index 000000000..4f45cffbc
--- /dev/null
+++ b/packages/scene-graph/src/instances/content-size.ts
@@ -0,0 +1,58 @@
+import type { SceneGraph, SceneNode } from '../'
+import { TEXT_METRIC_FIELDS } from '../fields/text'
+import { layoutSizing } from '../layout/sizing'
+
+const METRIC_FIELDS: ReadonlySet<string> = new Set(TEXT_METRIC_FIELDS)
+
+/**
+ * The axes along which a copy sizes itself to its own content rather than to its component,
+ * judged by the state the copy is about to have.
+ */
+function contentSizedAxes(
+ graph: SceneGraph,
+ current: SceneNode,
+ source: SceneNode,
+ updates: Partial<SceneNode>
+): { width: boolean; height: boolean } {
+ const copy: SceneNode = { ...current, ...updates }
+ // Text measures its own characters, set on the copy or by a property of an instance around it.
+ if (copy.type === 'TEXT') {
+ if (copy.text === source.text) return { width: false, height: false }
+ const mode = copy.textAutoResize
+ return {
+ width: mode === 'WIDTH_AND_HEIGHT',
+ height: mode === 'WIDTH_AND_HEIGHT' || mode === 'HEIGHT'
+ }
+ }
+ // Auto layout hugs the copy's own layers, which may show or size differently.
+ if (copy.layoutMode === 'NONE') return { width: false, height: false }
+ return {
+ width: layoutSizing(graph, copy, 'HORIZONTAL') === 'HUG',
+ height: layoutSizing(graph, copy, 'VERTICAL') === 'HUG'
+ }
+}
+
+/**
+ * Keeps a copy's own size along the axes it sizes to its own content, as Figma sizes a badge to
+ * its count and the layers it shows rather than to the component's placeholder. Layout measures
+ * those axes; the component's size there would be stale.
+ */
+export function keepOwnContentSize(
+ graph: SceneGraph,
+ updates: Partial<SceneNode>,
+ copy: SceneNode,
+ source: SceneNode
+): void {
+ const axes = contentSizedAxes(graph, copy, source, updates)
+ if (axes.width) Reflect.deleteProperty(updates, 'width')
+ if (axes.height) Reflect.deleteProperty(updates, 'height')
+}
+
+/**
+ * Drops the size a text copy kept from the file once a metric reaches it from the component, so
+ * layout measures its characters again instead of trusting the size Figma saved for the old style.
+ */
+export function remeasureChangedText(updates: Partial<SceneNode>, copy: SceneNode): void {
+ if (copy.type !== 'TEXT' || !copy.derivedLayout) return
+ if (Object.keys(updates).some((key) => METRIC_FIELDS.has(key))) updates.derivedLayout = null
+}
diff --git a/packages/scene-graph/src/instances/sync.ts b/packages/scene-graph/src/instances/sync.ts
index b56b788f7..1c204a4cb 100644
--- a/packages/scene-graph/src/instances/sync.ts
+++ b/packages/scene-graph/src/instances/sync.ts
@@ -13,6 +13,7 @@ import {
import { scaleNodeChanges } from '../scaling/node'
import { ownsSlotContent, slotPropertyId } from '../slots/frames'
import { scaleVariableBindingUnits } from '../variables/units'
+import { keepOwnContentSize, remeasureChangedText } from './content-size'
import {
createInstanceSyncContext,
hasUnplacedCopiesBelow,
@@ -151,6 +152,7 @@ function copySyncedFields(
if (isEqual(copy[key], from[key])) continue
copyProp(updates, from, key)
}
+ remeasureChangedText(updates, copy)
}
export function updateSyncedProps(
@@ -187,9 +189,7 @@ export function cloneChildrenWithMapping(
destParentId: string,
mode: NodeCloneMode = 'deep'
): void {
- // Guard against cloning a subtree into itself or its own descendant. Without this,
- // a self-referential or cyclic component (e.g. an INSTANCE whose componentId points
- // to an ancestor) causes unbounded recursion and eventual stack overflow / OOM.
+ // A cyclic component, such as an instance of an ancestor, would clone itself without end.
if (sourceParentId === destParentId || graph.isDescendant(destParentId, sourceParentId)) return
const sourceParent = graph.nodes.get(sourceParentId)
@@ -581,6 +581,7 @@ export function syncChildren(
skip: (key) => driven.has(key) || isProtectedSyncField(instChild, key, protectedField)
})
Object.assign(updates, assignedFieldValues(graph, instChild, compChild))
+ keepOwnContentSize(graph, updates, instChild, source)
updateSyncedProps(graph, instChild, updates)
if (
diff --git a/packages/scene-graph/src/layout/guides.ts b/packages/scene-graph/src/layout/guides.ts
index 4b8e081f2..a373f4196 100644
--- a/packages/scene-graph/src/layout/guides.ts
+++ b/packages/scene-graph/src/layout/guides.ts
@@ -7,10 +7,21 @@ export interface LayoutGuideLine {
const MAX_LAYOUT_GUIDE_LINES = 10_000
-function normalizedCount(grid: LayoutGrid): number {
- const value = grid.count ?? grid.numSections ?? 1
- if (!Number.isFinite(value)) return 0
- return Math.min(MAX_LAYOUT_GUIDE_LINES, Math.max(0, Math.floor(value)))
+/** Figma's Auto count, as its archive stores it: as many sections as fit. */
+export const AUTO_LAYOUT_GRID_COUNT = 2_147_483_647
+
+/** Whether a guide's count is Auto: the archive's value, or the plugin API's `Infinity` or `null`. */
+export function isAutoGridCount(count: number | null | undefined): boolean {
+ return count === null || count === Infinity || (count ?? 0) >= AUTO_LAYOUT_GRID_COUNT
+}
+
+/**
+ * A guide's count, set in Figma's plugin shape (`count`) or read from a file (`numSections`); an
+ * edit's `count` wins over the count the file had. Auto is {@link AUTO_LAYOUT_GRID_COUNT}.
+ */
+export function layoutGridCount(grid: LayoutGrid): number {
+ const count = grid.count === undefined ? grid.numSections : grid.count
+ return isAutoGridCount(count) ? AUTO_LAYOUT_GRID_COUNT : (count ?? 1)
}
function pattern(grid: LayoutGrid): 'COLUMNS' | 'ROWS' | 'GRID' {
@@ -25,17 +36,35 @@ function alignment(grid: LayoutGrid): 'MIN' | 'CENTER' | 'MAX' | 'STRETCH' {
return 'MIN'
}
-function sectionSize(nodeSize: number, grid: LayoutGrid): number {
+/**
+ * How many sections a guide draws. Auto fits as many fixed sections as the frame holds, counting
+ * the offset once from the aligned edge, as Figma desktop 126 draws them.
+ */
+function sectionCount(nodeSize: number, grid: LayoutGrid): number {
+ const value = layoutGridCount(grid)
+ if (value === AUTO_LAYOUT_GRID_COUNT) {
+ const size = grid.sectionSize ?? 0
+ if (alignment(grid) === 'STRETCH' || size <= 0) return 0
+ const gutter = grid.gutterSize ?? 0
+ const offset = alignment(grid) === 'CENTER' ? 0 : (grid.offset ?? 0)
+ return Math.min(
+ MAX_LAYOUT_GUIDE_LINES,
+ Math.max(0, Math.floor((nodeSize - offset + gutter) / (size + gutter)))
+ )
+ }
+ if (!Number.isFinite(value)) return 0
+ return Math.min(MAX_LAYOUT_GUIDE_LINES, Math.max(0, Math.floor(value)))
+}
+
+function sectionSize(nodeSize: number, grid: LayoutGrid, count: number): number {
const fixed = grid.sectionSize ?? 0
if (alignment(grid) !== 'STRETCH') return fixed
- const count = normalizedCount(grid)
const gutter = grid.gutterSize ?? 0
const offset = grid.offset ?? 0
return (nodeSize - offset * 2 - Math.max(0, count - 1) * gutter) / count
}
-function start(nodeSize: number, grid: LayoutGrid, size: number): number {
- const count = normalizedCount(grid)
+function start(nodeSize: number, grid: LayoutGrid, size: number, count: number): number {
const gutter = grid.gutterSize ?? 0
const offset = grid.offset ?? 0
const span = count * size + Math.max(0, count - 1) * gutter
@@ -57,10 +86,10 @@ export function layoutGuideSections(
if (grid.visible === false || pattern(grid) === 'GRID') return []
const axis = pattern(grid) === 'ROWS' ? 'y' : 'x'
const nodeSize = axis === 'x' ? node.width : node.height
- const size = sectionSize(nodeSize, grid)
- const count = normalizedCount(grid)
+ const count = sectionCount(nodeSize, grid)
+ const size = sectionSize(nodeSize, grid, count)
if (count <= 0 || size <= 0) return []
- const first = start(nodeSize, grid, size)
+ const first = start(nodeSize, grid, size, count)
const step = size + (grid.gutterSize ?? 0)
return Array.from({ length: count }, (_, index) => {
const sectionStart = first + index * step
diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.ts
index ece385196..9b1df8f08 100644
--- a/packages/scene-graph/src/types.ts
+++ b/packages/scene-graph/src/types.ts
@@ -196,12 +196,14 @@ export type MaskType = 'ALPHA' | 'VECTOR' | 'LUMINANCE'
export interface LayoutGrid {
visible?: boolean
color?: Color
- pattern?: 'COLUMNS' | 'ROWS' | 'GRID'
+ /** `STRIPES` is the archive's name for columns or rows, along `axis`. */
+ pattern?: 'COLUMNS' | 'ROWS' | 'GRID' | 'STRIPES'
axis?: 'X' | 'Y'
type?: 'MIN' | 'CENTER' | 'MAX' | 'STRETCH'
alignment?: 'MIN' | 'CENTER' | 'MAX' | 'STRETCH'
numSections?: number
- count?: number
+ /** Figma's plugin API reports an Auto count as `null` and accepts `Infinity` for it. */
+ count?: number | null
offset?: number
sectionSize?: number
gutterSize?: number
diff --git a/packages/scene-graph/tests/basic/selectable-hit.test.ts b/packages/scene-graph/tests/basic/selectable-hit.test.ts
index c85b053c6..b71b1fd5f 100644
--- a/packages/scene-graph/tests/basic/selectable-hit.test.ts
+++ b/packages/scene-graph/tests/basic/selectable-hit.test.ts
@@ -261,3 +261,63 @@ describe('unfilled frames inside a top-level frame', () => {
expect(click(430, 700)).toBe('Empty in section')
})
})
+
+describe('a click just outside a shape', () => {
+ // Figma desktop 126 takes a click up to 3.5 screen pixels outside any shape, at every zoom,
+ // whatever its size; the caller gives that distance in canvas units.
+ test('selects the shape within the pad, and nothing beyond it', () => {
+ const graph = new SceneGraph()
+ const page = pageId(graph)
+ const dot = graph.createNode('RECTANGLE', page, {
+ x: 100,
+ y: 100,
+ width: 6,
+ height: 6,
+ fills: FILL
+ })
+ const line = graph.createNode('RECTANGLE', page, {
+ x: 100,
+ y: 200,
+ width: 100,
+ height: 1,
+ fills: FILL
+ })
+ const hit = (x: number, y: number, zoom: number) =>
+ graph.hitTestSelectable(x, y, page, new Set(), 3.5 / zoom)?.name ?? null
+ for (const zoom of [0.5, 1, 4]) {
+ const inside = 3.4 / zoom
+ const outside = 3.6 / zoom
+ expect([hit(106 + inside, 103, zoom), hit(106 + outside, 103, zoom)]).toEqual([
+ dot.name,
+ null
+ ])
+ expect([hit(150, 201 + inside, zoom), hit(150, 201 + outside, zoom)]).toEqual([
+ line.name,
+ null
+ ])
+ }
+ })
+
+ test('reaches a shape at its group’s edge, and the group only through its shapes', () => {
+ const graph = new SceneGraph()
+ const page = pageId(graph)
+ const group = graph.createNode('GROUP', page, {
+ name: 'Group',
+ x: 100,
+ y: 100,
+ width: 50,
+ height: 50
+ })
+ graph.createNode('RECTANGLE', group.id, { name: 'Box', width: 50, height: 50, fills: FILL })
+ expect(graph.hitTestSelectable(152, 120, page, new Set(), 3.5)?.name).toBe('Group')
+ expect(graph.hitTestDeep(152, 120, page, 3.5)?.name).toBe('Box')
+ expect(graph.hitTestSelectable(155, 120, page, new Set(), 3.5)).toBeNull()
+ })
+
+ test('leaves a frame’s edge exact, so the page around it starts a marquee', () => {
+ const graph = new SceneGraph()
+ const page = pageId(graph)
+ graph.createNode('FRAME', page, { name: 'Empty', width: 100, height: 100, fills: FILL })
+ expect(graph.hitTestSelectable(102, 50, page, new Set(), 3.5)).toBeNull()
+ })
+})
diff --git a/packages/scene-graph/tests/components/sync-field-contract.test.ts b/packages/scene-graph/tests/components/sync-field-contract.test.ts
index 164e3da1a..a7804b945 100644
--- a/packages/scene-graph/tests/components/sync-field-contract.test.ts
+++ b/packages/scene-graph/tests/components/sync-field-contract.test.ts
@@ -76,7 +76,13 @@ test('a component edit reaches every field its instances do not override, as in
const overridden = expectDefined(graph.createInstance(card.id, page))
const overriddenBar = graph.getChildren(overridden.id)[1]
graph.updateNode(overriddenBar.id, { strokeWeight: 6 })
- setInstanceOverride(overridden.instanceOverrides, overridden.id, overriddenBar.id, 'strokeWeight', 6)
+ setInstanceOverride(
+ overridden.instanceOverrides,
+ overridden.id,
+ overriddenBar.id,
+ 'strokeWeight',
+ 6
+ )
graph.updateNode(dot.id, { x: 150, y: 30, rotation: 30 })
graph.updateNode(bar.id, { x: 40, strokeWeight: 3, strokeAlign: 'OUTSIDE', cornerSmoothing: 0.6 })
@@ -98,7 +104,11 @@ test('a component edit reaches every field its instances do not override, as in
test('a layer in an auto layout flow takes its place from the layout, not the component', () => {
const graph = new SceneGraph()
const page = graph.getPages()[0].id
- const row = graph.createNode('COMPONENT', page, { layoutMode: 'HORIZONTAL', width: 100, height: 20 })
+ const row = graph.createNode('COMPONENT', page, {
+ layoutMode: 'HORIZONTAL',
+ width: 100,
+ height: 20
+ })
const item = graph.createNode('RECTANGLE', row.id, { x: 0, y: 0, width: 20, height: 20 })
const instance = expectDefined(graph.createInstance(row.id, page))
const copy = graph.getChildren(instance.id)[0]
@@ -125,3 +135,91 @@ test('restyled ranges reach instances, except one that overrides its text', () =
expect(graph.getChildren(plain.id)[0].styleRuns).toEqual(italic)
expect(copy.styleRuns).toEqual(runs)
})
+
+test('a copy that sizes itself to its own content keeps that size through a component edit', () => {
+ // A badge's count, as in gold-preview's lists: the instance's text is its own, the component's
+ // a longer placeholder, and Figma sizes the count and its hugging frame to the instance's text.
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const badge = graph.createNode('COMPONENT', page, {
+ width: 76,
+ height: 18,
+ layoutMode: 'HORIZONTAL',
+ primaryAxisSizing: 'HUG',
+ counterAxisSizing: 'HUG'
+ })
+ const label = graph.createNode('FRAME', badge.id, {
+ width: 60,
+ height: 16,
+ layoutMode: 'HORIZONTAL',
+ primaryAxisSizing: 'HUG',
+ counterAxisSizing: 'HUG'
+ })
+ const text = graph.createNode('TEXT', label.id, {
+ text: 'Badge-sm',
+ width: 60,
+ height: 16,
+ textAutoResize: 'WIDTH_AND_HEIGHT'
+ })
+ const instance = expectDefined(graph.createInstance(badge.id, page))
+ const [copyLabel] = graph.getChildren(instance.id)
+ const [copyText] = graph.getChildren(copyLabel.id)
+ graph.updateNode(copyText.id, { text: '2', width: 8 })
+ graph.updateNode(copyLabel.id, { width: 8 })
+ graph.updateNode(instance.id, { width: 24 })
+ setInstanceOverride(instance.instanceOverrides, instance.id, copyText.id, 'text', true)
+
+ graph.updateNode(text.id, { width: 64, letterSpacing: 1 })
+ graph.updateNode(label.id, { width: 64 })
+ graph.syncInstances(badge.id)
+ expect([copyText.text, copyText.width, copyLabel.width, instance.width]).toEqual(['2', 8, 8, 24])
+ expect(copyText.letterSpacing).toBe(1)
+})
+
+test('a copy takes the component’s size once the component stops hugging its layers', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const badge = graph.createNode('COMPONENT', page, { width: 76, height: 18 })
+ const label = graph.createNode('FRAME', badge.id, {
+ width: 60,
+ height: 16,
+ layoutMode: 'HORIZONTAL',
+ primaryAxisSizing: 'HUG',
+ counterAxisSizing: 'HUG'
+ })
+ const instance = expectDefined(graph.createInstance(badge.id, page))
+ const [copyLabel] = graph.getChildren(instance.id)
+ graph.updateNode(copyLabel.id, { width: 8 })
+
+ graph.updateNode(label.id, { primaryAxisSizing: 'FIXED', width: 64 })
+ graph.syncInstances(badge.id)
+ expect([copyLabel.primaryAxisSizing, copyLabel.width]).toEqual(['FIXED', 64])
+})
+
+test('text a property gives a copy when its layer is linked later drops the size saved for the old text', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const button = graph.createNode('COMPONENT', page, {
+ width: 80,
+ height: 24,
+ componentPropertyDefinitions: [{ id: 'label', name: 'Label', type: 'TEXT', defaultValue: 'Go' }]
+ })
+ const text = graph.createNode('TEXT', button.id, {
+ text: 'Go',
+ width: 20,
+ height: 16,
+ textAutoResize: 'WIDTH_AND_HEIGHT',
+ derivedLayout: { width: 20, height: 16 }
+ })
+ const instance = expectDefined(graph.createInstance(button.id, page))
+ graph.updateNode(instance.id, { componentPropertyAssignments: { label: 'Checkout' } })
+ const [copy] = graph.getChildren(instance.id)
+ // The sizes Figma saved for the texts the component and the copy showed.
+ graph.updateNode(copy.id, { derivedLayout: { width: 22, height: 16 } })
+
+ graph.updateNode(text.id, {
+ componentPropertyReferences: [{ propertyId: 'label', field: 'TEXT' }]
+ })
+ graph.syncInstances(button.id)
+ expect([copy.text, copy.derivedLayout]).toEqual(['Checkout', null])
+})
diff --git a/packages/scene-graph/tests/layout/guides.test.ts b/packages/scene-graph/tests/layout/guides.test.ts
index 8d711f1bd..3df1e6a96 100644
--- a/packages/scene-graph/tests/layout/guides.test.ts
+++ b/packages/scene-graph/tests/layout/guides.test.ts
@@ -1,6 +1,10 @@
import { describe, expect, test } from 'bun:test'
-import { layoutGuideLines, layoutGuideSections } from '@open-pencil/scene-graph/layout'
+import {
+ AUTO_LAYOUT_GRID_COUNT,
+ layoutGuideLines,
+ layoutGuideSections
+} from '@open-pencil/scene-graph/layout'
describe('layout guide geometry bounds', () => {
test('normalizes fractional section counts', () => {
@@ -26,4 +30,32 @@ describe('layout guide geometry bounds', () => {
)
).toHaveLength(20_000)
})
+
+ // Measured on Figma desktop 126's canvas: 40 px columns, a 10 px gutter, a 300 px frame.
+ test('an Auto count fits as many sections as the frame holds, offset once from its edge', () => {
+ const auto = (alignment: 'MIN' | 'CENTER' | 'MAX', offset: number) =>
+ layoutGuideSections(
+ { width: 300, height: 200 },
+ {
+ pattern: 'STRIPES',
+ axis: 'X',
+ type: alignment,
+ numSections: AUTO_LAYOUT_GRID_COUNT,
+ sectionSize: 40,
+ gutterSize: 10,
+ offset
+ }
+ ).map((section) => [section.start, section.end])
+ const from = (start: number) =>
+ Array.from({ length: 6 }, (_, index) => [start + index * 50, start + index * 50 + 40])
+ expect(auto('MIN', 7)).toEqual(from(7))
+ expect(auto('CENTER', 0)).toEqual(from(5))
+ expect(auto('MAX', 7)).toEqual(from(3))
+ expect(
+ layoutGuideSections(
+ { width: 300, height: 200 },
+ { pattern: 'COLUMNS', alignment: 'MIN', count: Infinity, sectionSize: 40, gutterSize: 10 }
+ )
+ ).toHaveLength(6)
+ })
})
diff --git a/packages/vue/src/canvas/transform/marquee.ts b/packages/vue/src/canvas/transform/marquee.ts
index 0418af227..ea62e6dce 100644
--- a/packages/vue/src/canvas/transform/marquee.ts
+++ b/packages/vue/src/canvas/transform/marquee.ts
@@ -2,6 +2,7 @@ import type { Editor } from '@open-pencil/core/editor'
import { getAxisAlignedWorldBounds } from '@open-pencil/scene-graph/coordinate'
import type { Rect } from '@open-pencil/scene-graph/primitives'
+import { isPastPointerDragThreshold } from '#vue/shared/input/drag-threshold'
import type { DragMarquee } from '#vue/shared/input/types'
function intersects(a: Rect, b: Rect) {
@@ -39,3 +40,14 @@ export function handleMarqueeMove(editor: Editor, d: DragMarquee, cx: number, cy
editor.select(hits)
editor.setMarquee(marquee)
}
+
+/** Ends a marquee; a click on a section's empty area, without a drag, selects it, as in Figma. */
+export function finishMarquee(editor: Editor, d: DragMarquee) {
+ const container = d.containerId ? editor.graph.getNode(d.containerId) : undefined
+ const marquee = editor.state.marquee
+ const zoom = editor.state.zoom
+ const dragged =
+ !!marquee && isPastPointerDragThreshold(0, 0, marquee.width * zoom, marquee.height * zoom)
+ if (!dragged && container?.type === 'SECTION') editor.select([container.id])
+ editor.setMarquee(null)
+}
diff --git a/packages/vue/src/canvas/useCanvasInput.ts b/packages/vue/src/canvas/useCanvasInput.ts
index fb56eb071..ce63e0bb2 100644
--- a/packages/vue/src/canvas/useCanvasInput.ts
+++ b/packages/vue/src/canvas/useCanvasInput.ts
@@ -11,6 +11,7 @@ import { createCanvasPointer } from '#vue/canvas/pointer/use'
import { createTextEditInput } from '#vue/canvas/text-edit/input'
import { handleToolMouseDown } from '#vue/canvas/tools/input'
import { createCanvasTransformInput } from '#vue/canvas/transform/input'
+import { finishMarquee } from '#vue/canvas/transform/marquee'
import {
handleBendHandleMove,
handleNodeEditPointerUp,
@@ -417,7 +418,7 @@ export function useCanvasInput(
}
if (editor.state.rotationPreview === preview) editor.setRotationPreview(null)
} else if (d.type === 'draw' || d.type === 'gradient' || d.type === 'shape-handle') d.commit()
- else if (d.type === 'marquee') editor.setMarquee(null)
+ else if (d.type === 'marquee') finishMarquee(editor, d)
drag.value = null
cursorOverride.value = null
diff --git a/packages/vue/src/i18n/locales/de/panels.json b/packages/vue/src/i18n/locales/de/panels.json
index 02bbfa3e8..95be7dba6 100644
--- a/packages/vue/src/i18n/locales/de/panels.json
+++ b/packages/vue/src/i18n/locales/de/panels.json
@@ -8,6 +8,8 @@
"page": "Seite",
"selectionColors": "Auswahlfarben",
"frame": "Frame",
+ "group": "Gruppe",
+ "layerType": "Ebenentyp",
"framePreset": "Frame-Voreinstellung",
"framePresetCustom": "Benutzerdefiniert",
"framePresetCategoryPhone": "Telefon",
@@ -162,6 +164,24 @@
"gridRows": "Zeilen",
"gridCount": "Anzahl",
"gridSectionSize": "Abschnittsgröße",
+ "gridSettings": "Einstellungen für Layoutraster",
+ "gridType": "Typ",
+ "gridWidth": "Breite",
+ "gridHeight": "Höhe",
+ "gridOffset": "Versatz",
+ "gridSize": "Größe",
+ "gridColor": "Farbe",
+ "gridAuto": "Auto",
+ "gridAlignLeft": "Links",
+ "gridAlignRight": "Rechts",
+ "gridAlignTop": "Oben",
+ "gridAlignBottom": "Unten",
+ "gridAlignCenter": "Mitte",
+ "gridAlignStretch": "Strecken",
+ "gridSummaryColumns": "{count} Spalten",
+ "gridSummaryRows": "{count} Zeilen",
+ "gridSummaryGrid": "Raster {size} px",
+ "gridSummaryFixed": "{summary} ({size} px)",
"gridGutter": "Zwischenraum",
"gridMargin": "Rand",
"resizing": "Größenänderung",
diff --git a/packages/vue/src/i18n/locales/es/panels.json b/packages/vue/src/i18n/locales/es/panels.json
index 20c3b0c1b..66713653f 100644
--- a/packages/vue/src/i18n/locales/es/panels.json
+++ b/packages/vue/src/i18n/locales/es/panels.json
@@ -9,6 +9,8 @@
"page": "Página",
"selectionColors": "Colores de la selección",
"frame": "Marco",
+ "group": "Grupo",
+ "layerType": "Tipo de capa",
"framePreset": "Preajuste de marco",
"framePresetCustom": "Personalizado",
"framePresetCategoryPhone": "Teléfono",
@@ -177,6 +179,24 @@
"gridRows": "Filas",
"gridCount": "Cantidad",
"gridSectionSize": "Tamaño de sección",
+ "gridSettings": "Ajustes de la guía de diseño",
+ "gridType": "Tipo",
+ "gridWidth": "Ancho",
+ "gridHeight": "Alto",
+ "gridOffset": "Desplazamiento",
+ "gridSize": "Tamaño",
+ "gridColor": "Color",
+ "gridAuto": "Auto",
+ "gridAlignLeft": "Izquierda",
+ "gridAlignRight": "Derecha",
+ "gridAlignTop": "Arriba",
+ "gridAlignBottom": "Abajo",
+ "gridAlignCenter": "Centro",
+ "gridAlignStretch": "Estirar",
+ "gridSummaryColumns": "{count} columnas",
+ "gridSummaryRows": "{count} filas",
+ "gridSummaryGrid": "Cuadrícula {size} px",
+ "gridSummaryFixed": "{summary} ({size} px)",
"gridGutter": "Canal",
"gridMargin": "Margen",
"resizing": "Redimensionado",
diff --git a/packages/vue/src/i18n/locales/fr/panels.json b/packages/vue/src/i18n/locales/fr/panels.json
index d0a941507..464045989 100644
--- a/packages/vue/src/i18n/locales/fr/panels.json
+++ b/packages/vue/src/i18n/locales/fr/panels.json
@@ -8,6 +8,8 @@
"page": "Page",
"selectionColors": "Couleurs de la sélection",
"frame": "Cadre",
+ "group": "Groupe",
+ "layerType": "Type de calque",
"framePreset": "Préréglage de cadre",
"framePresetCustom": "Personnalisé",
"framePresetCategoryPhone": "Téléphone",
@@ -162,6 +164,24 @@
"gridRows": "Rangées",
"gridCount": "Nombre",
"gridSectionSize": "Taille de section",
+ "gridSettings": "Réglages du guide de mise en page",
+ "gridType": "Type",
+ "gridWidth": "Largeur",
+ "gridHeight": "Hauteur",
+ "gridOffset": "Décalage",
+ "gridSize": "Taille",
+ "gridColor": "Couleur",
+ "gridAuto": "Auto",
+ "gridAlignLeft": "Gauche",
+ "gridAlignRight": "Droite",
+ "gridAlignTop": "Haut",
+ "gridAlignBottom": "Bas",
+ "gridAlignCenter": "Centre",
+ "gridAlignStretch": "Étirer",
+ "gridSummaryColumns": "{count} colonnes",
+ "gridSummaryRows": "{count} lignes",
+ "gridSummaryGrid": "Grille {size} px",
+ "gridSummaryFixed": "{summary} ({size} px)",
"gridGutter": "Gouttière",
"gridMargin": "Marge",
"resizing": "Redimensionnement",
diff --git a/packages/vue/src/i18n/locales/it/panels.json b/packages/vue/src/i18n/locales/it/panels.json
index 296f3bfc9..3e7377809 100644
--- a/packages/vue/src/i18n/locales/it/panels.json
+++ b/packages/vue/src/i18n/locales/it/panels.json
@@ -8,6 +8,8 @@
"page": "Pagina",
"selectionColors": "Colori della selezione",
"frame": "Cornice",
+ "group": "Gruppo",
+ "layerType": "Tipo di livello",
"framePreset": "Preimpostazione cornice",
"framePresetCustom": "Personalizzata",
"framePresetCategoryPhone": "Telefono",
@@ -162,6 +164,24 @@
"gridRows": "Righe",
"gridCount": "Numero",
"gridSectionSize": "Dimensione sezione",
+ "gridSettings": "Impostazioni della guida di layout",
+ "gridType": "Tipo",
+ "gridWidth": "Larghezza",
+ "gridHeight": "Altezza",
+ "gridOffset": "Scostamento",
+ "gridSize": "Dimensione",
+ "gridColor": "Colore",
+ "gridAuto": "Auto",
+ "gridAlignLeft": "Sinistra",
+ "gridAlignRight": "Destra",
+ "gridAlignTop": "Alto",
+ "gridAlignBottom": "Basso",
+ "gridAlignCenter": "Centro",
+ "gridAlignStretch": "Estendi",
+ "gridSummaryColumns": "{count} colonne",
+ "gridSummaryRows": "{count} righe",
+ "gridSummaryGrid": "Griglia {size} px",
+ "gridSummaryFixed": "{summary} ({size} px)",
"gridGutter": "Spaziatura",
"gridMargin": "Margine",
"resizing": "Ridimensionamento",
diff --git a/packages/vue/src/i18n/locales/ja/panels.json b/packages/vue/src/i18n/locales/ja/panels.json
index dbc06487c..6c5fbafde 100644
--- a/packages/vue/src/i18n/locales/ja/panels.json
+++ b/packages/vue/src/i18n/locales/ja/panels.json
@@ -9,6 +9,8 @@
"page": "ページ",
"selectionColors": "選択範囲の色",
"frame": "フレーム",
+ "group": "グループ",
+ "layerType": "レイヤーの種類",
"framePreset": "フレームプリセット",
"framePresetCustom": "カスタム",
"framePresetCategoryPhone": "スマートフォン",
@@ -177,6 +179,24 @@
"gridRows": "行",
"gridCount": "数",
"gridSectionSize": "セクションサイズ",
+ "gridSettings": "レイアウトガイドの設定",
+ "gridType": "種類",
+ "gridWidth": "幅",
+ "gridHeight": "高さ",
+ "gridOffset": "オフセット",
+ "gridSize": "サイズ",
+ "gridColor": "色",
+ "gridAuto": "自動",
+ "gridAlignLeft": "左",
+ "gridAlignRight": "右",
+ "gridAlignTop": "上",
+ "gridAlignBottom": "下",
+ "gridAlignCenter": "中央",
+ "gridAlignStretch": "伸縮",
+ "gridSummaryColumns": "{count} 列",
+ "gridSummaryRows": "{count} 行",
+ "gridSummaryGrid": "グリッド {size}px",
+ "gridSummaryFixed": "{summary}({size}px)",
"gridGutter": "ガター",
"gridMargin": "マージン",
"resizing": "サイズ変更",
diff --git a/packages/vue/src/i18n/locales/pl/panels.json b/packages/vue/src/i18n/locales/pl/panels.json
index c0ba20189..93fd4c606 100644
--- a/packages/vue/src/i18n/locales/pl/panels.json
+++ b/packages/vue/src/i18n/locales/pl/panels.json
@@ -8,6 +8,8 @@
"page": "Strona",
"selectionColors": "Kolory zaznaczenia",
"frame": "Ramka",
+ "group": "Grupa",
+ "layerType": "Typ warstwy",
"framePreset": "Ustawienie ramki",
"framePresetCustom": "Niestandardowe",
"framePresetCategoryPhone": "Telefon",
@@ -162,6 +164,24 @@
"gridRows": "Wiersze",
"gridCount": "Liczba",
"gridSectionSize": "Rozmiar sekcji",
+ "gridSettings": "Ustawienia prowadnicy układu",
+ "gridType": "Typ",
+ "gridWidth": "Szerokość",
+ "gridHeight": "Wysokość",
+ "gridOffset": "Przesunięcie",
+ "gridSize": "Rozmiar",
+ "gridColor": "Kolor",
+ "gridAuto": "Auto",
+ "gridAlignLeft": "Do lewej",
+ "gridAlignRight": "Do prawej",
+ "gridAlignTop": "Do góry",
+ "gridAlignBottom": "Do dołu",
+ "gridAlignCenter": "Do środka",
+ "gridAlignStretch": "Rozciągnij",
+ "gridSummaryColumns": "Kolumny: {count}",
+ "gridSummaryRows": "Wiersze: {count}",
+ "gridSummaryGrid": "Siatka {size} px",
+ "gridSummaryFixed": "{summary} ({size} px)",
"gridGutter": "Odstęp",
"gridMargin": "Margines",
"resizing": "Zmiana rozmiaru",
diff --git a/packages/vue/src/i18n/locales/ru/panels.json b/packages/vue/src/i18n/locales/ru/panels.json
index 999535662..2c561759b 100644
--- a/packages/vue/src/i18n/locales/ru/panels.json
+++ b/packages/vue/src/i18n/locales/ru/panels.json
@@ -8,6 +8,8 @@
"page": "Страница",
"selectionColors": "Цвета выделения",
"frame": "Фрейм",
+ "group": "Группа",
+ "layerType": "Тип слоя",
"framePreset": "Размер фрейма",
"framePresetCustom": "Пользовательский",
"framePresetCategoryPhone": "Телефон",
@@ -162,6 +164,24 @@
"gridRows": "Строки",
"gridCount": "Количество",
"gridSectionSize": "Размер секции",
+ "gridSettings": "Настройки направляющей",
+ "gridType": "Тип",
+ "gridWidth": "Ширина",
+ "gridHeight": "Высота",
+ "gridOffset": "Смещение",
+ "gridSize": "Размер",
+ "gridColor": "Цвет",
+ "gridAuto": "Авто",
+ "gridAlignLeft": "Слева",
+ "gridAlignRight": "Справа",
+ "gridAlignTop": "Сверху",
+ "gridAlignBottom": "Снизу",
+ "gridAlignCenter": "По центру",
+ "gridAlignStretch": "Растянуть",
+ "gridSummaryColumns": "Колонок: {count}",
+ "gridSummaryRows": "Строк: {count}",
+ "gridSummaryGrid": "Сетка {size} px",
+ "gridSummaryFixed": "{summary} ({size} px)",
"gridGutter": "Межколонник",
"gridMargin": "Поле",
"resizing": "Изменение размера",
diff --git a/packages/vue/src/i18n/locales/zh-cn/panels.json b/packages/vue/src/i18n/locales/zh-cn/panels.json
index 66f02d215..0d697ff93 100644
--- a/packages/vue/src/i18n/locales/zh-cn/panels.json
+++ b/packages/vue/src/i18n/locales/zh-cn/panels.json
@@ -8,6 +8,8 @@
"page": "页面",
"selectionColors": "所选颜色",
"frame": "画框",
+ "group": "编组",
+ "layerType": "图层类型",
"framePreset": "画框预设",
"framePresetCustom": "自定义",
"framePresetCategoryPhone": "手机",
@@ -162,6 +164,24 @@
"gridRows": "行",
"gridCount": "数量",
"gridSectionSize": "分区大小",
+ "gridSettings": "布局参考线设置",
+ "gridType": "类型",
+ "gridWidth": "宽度",
+ "gridHeight": "高度",
+ "gridOffset": "偏移",
+ "gridSize": "大小",
+ "gridColor": "颜色",
+ "gridAuto": "自动",
+ "gridAlignLeft": "左",
+ "gridAlignRight": "右",
+ "gridAlignTop": "上",
+ "gridAlignBottom": "下",
+ "gridAlignCenter": "居中",
+ "gridAlignStretch": "拉伸",
+ "gridSummaryColumns": "{count} 列",
+ "gridSummaryRows": "{count} 行",
+ "gridSummaryGrid": "网格 {size}px",
+ "gridSummaryFixed": "{summary}({size}px)",
"gridGutter": "间距",
"gridMargin": "边距",
"resizing": "调整大小",
diff --git a/packages/vue/src/i18n/messages/panels.ts b/packages/vue/src/i18n/messages/panels.ts
index 4880b9dff..a6e2788d6 100644
--- a/packages/vue/src/i18n/messages/panels.ts
+++ b/packages/vue/src/i18n/messages/panels.ts
@@ -137,6 +137,8 @@ export const panelMessageDefaults = {
page: 'Page',
selectionColors: 'Selection colors',
frame: 'Frame',
+ group: 'Group',
+ layerType: 'Layer type',
framePreset: 'Frame preset',
framePresetCustom: 'Custom',
framePresetCategoryPhone: 'Phone',
@@ -532,6 +534,24 @@ export const panelMessageDefaults = {
gridGutter: 'Gutter',
gridMargin: 'Margin',
gridSectionSize: 'Section size',
+ gridSettings: 'Layout guide settings',
+ gridType: 'Type',
+ gridWidth: 'Width',
+ gridHeight: 'Height',
+ gridOffset: 'Offset',
+ gridSize: 'Size',
+ gridColor: 'Color',
+ gridAuto: 'Auto',
+ gridAlignLeft: 'Left',
+ gridAlignRight: 'Right',
+ gridAlignTop: 'Top',
+ gridAlignBottom: 'Bottom',
+ gridAlignCenter: 'Center',
+ gridAlignStretch: 'Stretch',
+ gridSummaryColumns: params('{count} columns'),
+ gridSummaryRows: params('{count} rows'),
+ gridSummaryGrid: params('Grid {size}px'),
+ gridSummaryFixed: params('{summary} ({size}px)'),
searchFonts: 'Search fonts...',
noFontsFound: 'No fonts found',
searchIcons: 'Search icons...',
diff --git a/packages/vue/src/shared/input/geometry.ts b/packages/vue/src/shared/input/geometry.ts
index 59a7a9a86..5887bb367 100644
--- a/packages/vue/src/shared/input/geometry.ts
+++ b/packages/vue/src/shared/input/geometry.ts
@@ -1,4 +1,4 @@
-import { HANDLE_HIT_RADIUS } from '@open-pencil/core/constants'
+import { HANDLE_HIT_RADIUS, LAYER_HIT_PAD } from '@open-pencil/core/constants'
import type { Editor } from '@open-pencil/core/editor'
import {
createSceneGeometry,
@@ -53,18 +53,12 @@ export function hitTestInEditorScope(
const renderer = editor.renderer
if (!renderer) return null
- if (scopeId) {
- if (!editor.graph.getNode(scopeId)) {
- editor.state.enteredContainerId = null
- } else {
- return deep
- ? editor.graph.hitTestDeep(cx, cy, scopeId)
- : editor.graph.hitTestSelectable(cx, cy, scopeId, editor.state.selectedIds)
- }
- }
+ const pad = LAYER_HIT_PAD / renderer.zoom
+ if (scopeId && !editor.graph.getNode(scopeId)) editor.state.enteredContainerId = null
+ const scope = editor.state.enteredContainerId ?? editor.state.currentPageId
return deep
- ? editor.graph.hitTestDeep(cx, cy, editor.state.currentPageId)
- : editor.graph.hitTestSelectable(cx, cy, editor.state.currentPageId, editor.state.selectedIds)
+ ? editor.graph.hitTestDeep(cx, cy, scope, pad)
+ : editor.graph.hitTestSelectable(cx, cy, scope, editor.state.selectedIds, pad)
}
export function isInsideEditorContainerBounds(
diff --git a/packages/vue/src/shared/input/resize.ts b/packages/vue/src/shared/input/resize.ts
index 104b15459..faa8a8e0e 100644
--- a/packages/vue/src/shared/input/resize.ts
+++ b/packages/vue/src/shared/input/resize.ts
@@ -6,8 +6,14 @@ import { toRaw } from 'vue'
import type { Editor } from '@open-pencil/core/editor'
import { computeAllLayouts } from '@open-pencil/core/layout'
import { calibratePathTextLayout, reflowPathTextGlyphs } from '@open-pencil/core/text'
-import { cloneVectorNetwork, recapturedAspectRatio } from '@open-pencil/scene-graph'
-import type { SceneNode } from '@open-pencil/scene-graph'
+import {
+ cloneInstanceOverrideState,
+ cloneVectorNetwork,
+ findInstanceAncestor,
+ recapturedAspectRatio,
+ recordInstanceOverride
+} from '@open-pencil/scene-graph'
+import type { InstanceOverrideState, SceneNode } from '@open-pencil/scene-graph'
import { copyDerivedGlyphs, copyGeometryPaths, copyStrokes } from '@open-pencil/scene-graph/copy'
import type { Rect } from '@open-pencil/scene-graph/primitives'
import {
@@ -250,6 +256,8 @@ function clearResizedRawGeometry(editor: Editor, nodeId: string): void {
if (node.type !== 'TEXT') delete raw.vectorData
}
+const RECT_FIELDS = ['x', 'y', 'width', 'height'] as const
+
function sameRect(a: Rect, b: Rect): boolean {
return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height
}
@@ -342,6 +350,29 @@ export function commitResizePreview(dragState: DragResize, editor: Editor) {
})
}
+/**
+ * Runs a resize that moves layers by their constraints while recording only the box fields the
+ * resize changed on the resized layer as an instance override: in Figma a layer inside an instance that its constraints
+ * place keeps following the component, so a later component edit still reaches it.
+ */
+function keepingOnlyOwnOverrides(
+ editor: Editor,
+ nodeId: string,
+ ownFields: readonly string[],
+ placedIds: readonly string[],
+ commit: () => void
+) {
+ const owners = new Map<string, InstanceOverrideState>()
+ for (const id of [nodeId, ...placedIds]) {
+ const owner = findInstanceAncestor(editor.graph, id)
+ if (owner && !owners.has(owner.id))
+ owners.set(owner.id, cloneInstanceOverrideState(owner.instanceOverrides))
+ }
+ commit()
+ for (const [id, state] of owners) editor.graph.updateNode(id, { instanceOverrides: state })
+ if (owners.size > 0) recordInstanceOverride(editor.graph, nodeId, ownFields)
+}
+
function commitResizeGeometry(d: DragResize, editor: Editor) {
optionalEditorState(editor)?.snapGuides.splice(0)
const node = editor.graph.getNode(d.nodeId)
@@ -360,12 +391,20 @@ function commitResizeGeometry(d: DragResize, editor: Editor) {
// Resize is geometric — the raw Figma import payload (vectorData,
// textPathStart, effects, ...) must survive or path-text reflow works
// exactly once and export fidelity degrades.
- editor.graph.preserveSourceMetadataDuring(() => {
- editor.updateNode(d.nodeId, finalChanges)
- for (const [childId, final] of finalChildren) {
- editor.updateNode(childId, final)
+ keepingOnlyOwnOverrides(
+ editor,
+ d.nodeId,
+ RECT_FIELDS.filter((key) => finalChanges[key] !== d.origRect[key]),
+ [...finalChildren.keys()],
+ () => {
+ editor.graph.preserveSourceMetadataDuring(() => {
+ editor.updateNode(d.nodeId, finalChanges)
+ for (const [childId, final] of finalChildren) {
+ editor.updateNode(childId, final)
+ }
+ })
}
- })
+ )
clearResizedRawGeometry(editor, d.nodeId)
for (const [childId] of finalChildren) clearResizedRawGeometry(editor, childId)
editor.commitGroupResize(d.nodeId, d.origRect, d.origChildren)
diff --git a/packages/vue/tests/shared/input/resize.test.ts b/packages/vue/tests/shared/input/resize.test.ts
index e691d5c84..e92c1dca2 100644
--- a/packages/vue/tests/shared/input/resize.test.ts
+++ b/packages/vue/tests/shared/input/resize.test.ts
@@ -1,7 +1,8 @@
import { describe, expect, test } from 'bun:test'
import { createEditor } from '@open-pencil/core/editor'
-import type { SceneNode } from '@open-pencil/scene-graph'
+import { hasInstanceOverride, type SceneNode } from '@open-pencil/scene-graph'
+import { createResizeSnapshot } from '@open-pencil/scene-graph/resize'
import { applyResize, cancelResizePreview, commitResizePreview } from '#vue/shared/input/resize'
import type { DragResize } from '#vue/shared/input/types'
@@ -74,7 +75,10 @@ describe('a resize that changes nothing', () => {
const editor = createEditor()
try {
const { graph } = editor
- const frame = graph.createNode('FRAME', editor.state.currentPageId, { width: 200, height: 40 })
+ const frame = graph.createNode('FRAME', editor.state.currentPageId, {
+ width: 200,
+ height: 40
+ })
graph.applyImportedStateDuring(() =>
graph.updateNode(frame.id, { source: { ...frame.source, format: 'fig', id: frame.id } })
)
@@ -102,9 +106,7 @@ test('a cancelled resize gives a vector back its own geometry', () => {
{ x: 0, y: 0 },
{ x: 100, y: 50 }
],
- segments: [
- { start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }
- ],
+ segments: [{ start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }],
regions: []
}
const vector = editor.graph.createNode('VECTOR', editor.state.currentPageId, {
@@ -121,3 +123,66 @@ test('a cancelled resize gives a vector back its own geometry', () => {
editor.dispose()
}
})
+
+describe('resizing an instance', () => {
+ test('places its layers by their constraints without making their sizes overrides', () => {
+ // Repeats a Figma desktop 126 script: an instance resized to twice its component's size
+ // claims only its own size, so a later component edit still sizes its layers.
+ const editor = createEditor()
+ try {
+ const { graph } = editor
+ const page = editor.state.currentPageId
+ const card = graph.createNode('COMPONENT', page, {
+ width: 140,
+ height: 140,
+ strokes: [
+ {
+ type: 'SOLID',
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ opacity: 1,
+ visible: true,
+ weight: 1,
+ align: 'INSIDE'
+ }
+ ]
+ })
+ const box = graph.createNode('RECTANGLE', card.id, {
+ x: 20,
+ y: 20,
+ width: 100,
+ height: 100,
+ horizontalConstraint: 'SCALE',
+ verticalConstraint: 'SCALE'
+ })
+ const instance = graph.createInstance(card.id, page, { x: 300 })
+ if (!instance) throw new Error('Expected an instance')
+ const [copy] = graph.getChildren(instance.id)
+ const resize: DragResize = {
+ ...drag(instance),
+ handle: 'se',
+ startX: instance.x + instance.width,
+ startY: instance.y + instance.height,
+ origChildren: new Map([[copy.id, createResizeSnapshot(copy)]])
+ }
+ applyResize(resize, instance.x + 280, instance.y + 280, false, editor, true)
+ commitResizePreview(resize, editor)
+ expect([instance.width, instance.height, copy.width, copy.height]).toEqual([
+ 280, 280, 200, 200
+ ])
+ expect(hasInstanceOverride(graph, instance.id, 'width')).toBe(true)
+ expect(hasInstanceOverride(graph, copy.id, 'width')).toBe(false)
+ // A corner drag leaves the instance in place, and resizes no strokes of its own.
+ expect(
+ (['x', 'y', 'strokes'] as const).map((field) =>
+ hasInstanceOverride(graph, instance.id, field)
+ )
+ ).toEqual([false, false, false])
+
+ graph.updateNode(box.id, { width: 115 })
+ graph.syncInstances(card.id)
+ expect(copy.width).toBe(230)
+ } finally {
+ editor.dispose()
+ }
+ })
+})
diff --git a/src/components/DesignPanel.vue b/src/components/DesignPanel.vue
index d306ecc45..ab965abd6 100644
--- a/src/components/DesignPanel.vue
+++ b/src/components/DesignPanel.vue
@@ -3,7 +3,7 @@ import { computed } from 'vue'
import { getNodeEditCapability } from '@open-pencil/core/editor'
import { readIcon } from '@open-pencil/scene-graph'
-import { useI18n, useSelectionState, useEditorCommands } from '@open-pencil/vue'
+import { useI18n, useSceneComputed, useSelectionState, useEditorCommands } from '@open-pencil/vue'
import { useEditorStore } from '@/app/editor/active-store'
import { COMPONENT_TYPES, sceneNodeIcon } from '@/app/editor/icons'
@@ -30,6 +30,7 @@ import FillSection from './properties/FillSection.vue'
import FramePresetSelect from './properties/frame-presets/FramePresetSelect.vue'
import FramePresetsSection from './properties/frame-presets/FramePresetsSection.vue'
import IconSection from './properties/IconSection.vue'
+import LayerTypeMenu from './properties/LayerTypeMenu.vue'
import LayoutGridSection from './properties/layout/guides/LayoutGridSection.vue'
import LayoutSection from './properties/layout/LayoutSection.vue'
import MaskSection from './properties/MaskSection.vue'
@@ -75,9 +76,11 @@ function openSelectedInstanceReview() {
initialInstanceId: instance.id
})
}
-const supportsLayoutGuides = computed(() => {
- const type = node.value?.type
- return type === 'FRAME' || type === 'COMPONENT' || type === 'COMPONENT_SET' || type === 'INSTANCE'
+const LAYOUT_GUIDE_TYPES = new Set(['FRAME', 'COMPONENT', 'COMPONENT_SET', 'INSTANCE'])
+// Figma offers layout guides while every selected layer is a frame.
+const supportsLayoutGuides = useSceneComputed(() => {
+ const nodes = store.getSelectedNodes()
+ return nodes.length > 0 && nodes.every((selected) => LAYOUT_GUIDE_TYPES.has(selected.type))
})
const { panels } = useI18n()
</script>
@@ -118,6 +121,7 @@ const { panels } = useI18n()
<StrokeSection />
<EffectsSection />
<SelectionColorsSection />
+ <LayoutGridSection v-if="supportsLayoutGuides" />
<ExportSection />
</div>
@@ -130,7 +134,12 @@ const { panels } = useI18n()
>
<PanelHeader :component="isComponentType">
<template #icon>
- <Tip :label="node.type">
+ <LayerTypeMenu
+ v-if="node.type === 'FRAME' || node.type === 'GROUP'"
+ :node="node"
+ :icon="selectedIcon"
+ />
+ <Tip v-else :label="node.type">
<span role="img" :aria-label="node.type" class="contents">
<component :is="selectedIcon" class="size-3.5" />
</span>
@@ -205,9 +214,9 @@ const { panels } = useI18n()
<TypographySection v-if="node.type === 'TEXT'" />
<FillSection />
<StrokeSection />
- <LayoutGridSection v-if="supportsLayoutGuides" />
<EffectsSection />
<SelectionColorsSection />
+ <LayoutGridSection v-if="supportsLayoutGuides" />
<ExportSection />
</div>
diff --git a/src/components/properties/LayerTypeMenu.vue b/src/components/properties/LayerTypeMenu.vue
new file mode 100644
index 000000000..2aa020742
--- /dev/null
+++ b/src/components/properties/LayerTypeMenu.vue
@@ -0,0 +1,71 @@
+<script setup lang="ts">
+import {
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuPortal,
+ DropdownMenuRoot,
+ DropdownMenuTrigger
+} from 'reka-ui'
+import type { Component } from 'vue'
+import IconCheck from '~icons/lucide/check'
+import IconChevronDown from '~icons/lucide/chevron-down'
+
+import type { SceneNode } from '@open-pencil/scene-graph'
+import { useI18n, useRetainedPopup } from '@open-pencil/vue'
+
+import { useEditorStore } from '@/app/editor/active-store'
+import { NODE_ICONS } from '@/app/editor/icons'
+import { menuItem, useMenuUI } from '@/components/ui/menu/menu'
+import Tip from '@/components/ui/overlay/Tip.vue'
+
+// Figma's layer type menu: a frame and a group switch to each other in place.
+const { node, icon } = defineProps<{ node: SceneNode; icon: Component | undefined }>()
+
+const store = useEditorStore()
+const { panels } = useI18n()
+const { open: popupOpen, portalActive } = useRetainedPopup()
+
+const types = [
+ { type: 'FRAME', icon: NODE_ICONS.FRAME, label: () => panels.value.frame },
+ { type: 'GROUP', icon: NODE_ICONS.GROUP, label: () => panels.value.group }
+] as const
+
+// A frame without layers has nothing to group.
+const disabled = (type: 'FRAME' | 'GROUP') => type === 'GROUP' && node.childIds.length === 0
+
+const menuCls = useMenuUI({ content: 'min-w-36' })
+const itemCls = menuItem({ justify: 'between' })
+</script>
+
+<template>
+ <DropdownMenuRoot v-model:open="popupOpen">
+ <Tip :label="panels.layerType">
+ <DropdownMenuTrigger as-child>
+ <button
+ :aria-label="panels.layerType"
+ class="-mx-1 -my-1.5 flex h-6 items-center gap-0.5 rounded-md px-1 text-muted hover:bg-hover hover:text-surface data-[state=open]:bg-active data-[state=open]:text-surface"
+ >
+ <component :is="icon" class="size-3.5" />
+ <IconChevronDown class="size-3" />
+ </button>
+ </DropdownMenuTrigger>
+ </Tip>
+ <DropdownMenuPortal v-if="portalActive">
+ <DropdownMenuContent align="start" side="bottom" :side-offset="4" :class="menuCls.content">
+ <DropdownMenuItem
+ v-for="item in types"
+ :key="item.type"
+ :class="itemCls"
+ :disabled="disabled(item.type)"
+ @select="item.type !== node.type && store.convertLayerType(node.id, item.type)"
+ >
+ <div class="flex min-w-0 items-center gap-2">
+ <component :is="item.icon" class="size-3.5 shrink-0 text-muted" />
+ <span>{{ item.label() }}</span>
+ </div>
+ <IconCheck v-if="item.type === node.type" class="ml-4 size-3.5" />
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenuPortal>
+ </DropdownMenuRoot>
+</template>
diff --git a/src/components/properties/layout/guides/LayoutGridSection.vue b/src/components/properties/layout/guides/LayoutGridSection.vue
index eb910bf99..4094e2720 100644
--- a/src/components/properties/layout/guides/LayoutGridSection.vue
+++ b/src/components/properties/layout/guides/LayoutGridSection.vue
@@ -1,9 +1,12 @@
<script setup lang="ts">
-import { computed } from 'vue'
+import { isEqual } from 'es-toolkit/predicate'
+import { computed, ref } from 'vue'
-import type { LayoutGrid } from '@open-pencil/scene-graph'
+import type { LayoutGrid, SceneNode } from '@open-pencil/scene-graph'
+import { AUTO_LAYOUT_GRID_COUNT, layoutGridCount } from '@open-pencil/scene-graph/layout'
import { useEditor, useI18n, useSceneComputed } from '@open-pencil/vue'
+import ColorInput from '@/components/ColorPicker/ColorInput.vue'
import NumberField from '@/components/inputs/NumberField.vue'
import SharedStyleField from '@/components/properties/shared-style/SharedStyleField.vue'
import IconButton from '@/components/ui/button/IconButton.vue'
@@ -12,44 +15,134 @@ import PanelFieldGroup from '@/components/ui/panel/PanelFieldGroup.vue'
import PanelGrid from '@/components/ui/panel/PanelGrid.vue'
import PanelItemRow from '@/components/ui/panel/PanelItemRow.vue'
import PanelSection from '@/components/ui/panel/PanelSection.vue'
-import SegmentedControl from '@/components/ui/select/SegmentedControl.vue'
+import AppSelect from '@/components/ui/select/AppSelect.vue'
const editor = useEditor()
const { panels } = useI18n()
-const selectedNode = useSceneComputed(() => editor.getSelectedNode() ?? null)
-const grids = computed<LayoutGrid[]>(() => selectedNode.value?.layoutGrids ?? [])
+// Every selected frame's guides, as Figma edits several frames at once: the panel lists them
+// while the frames' guides match, and offers only Add, which replaces them, while they differ.
+const targets = useSceneComputed(() => editor.getSelectedNodes())
+const mixed = computed(() => {
+ const [first, ...rest] = targets.value
+ return !!first && rest.some((node) => !isEqual(node.layoutGrids, first.layoutGrids))
+})
+const grids = computed<LayoutGrid[]>(() =>
+ mixed.value ? [] : (targets.value.at(0)?.layoutGrids ?? [])
+)
+
+// Figma lists the newest guide first.
+const rows = computed(() => grids.value.map((grid, index) => ({ grid, index })).reverse())
+const expanded = ref<number | null>(null)
+
+/** The value a stretched guide's size shows: its sections fill the frame. */
+const AUTO_SIZE = Symbol('auto')
+/** Figma's count for a new set of columns or rows. */
+const DEFAULT_COUNT = 5
+
+type GridPattern = 'COLUMNS' | 'ROWS' | 'GRID'
+type GridAlignment = NonNullable<LayoutGrid['alignment']>
const patternOptions = computed(() => [
+ { value: 'GRID' as const, label: panels.value.gridGrid },
{ value: 'COLUMNS' as const, label: panels.value.gridColumns },
- { value: 'ROWS' as const, label: panels.value.gridRows },
- { value: 'GRID' as const, label: panels.value.gridGrid }
+ { value: 'ROWS' as const, label: panels.value.gridRows }
])
+function alignmentOptions(pattern: GridPattern) {
+ const p = panels.value
+ const [start, end] =
+ pattern === 'ROWS' ? [p.gridAlignTop, p.gridAlignBottom] : [p.gridAlignLeft, p.gridAlignRight]
+ return [
+ { value: 'MIN' as const, label: start },
+ { value: 'CENTER' as const, label: p.gridAlignCenter },
+ { value: 'MAX' as const, label: end },
+ { value: 'STRETCH' as const, label: p.gridAlignStretch }
+ ]
+}
+
+const isAutoCount = (grid: LayoutGrid) => layoutGridCount(grid) === AUTO_LAYOUT_GRID_COUNT
+const gridAlignment = (grid: LayoutGrid): GridAlignment => grid.alignment ?? grid.type ?? 'STRETCH'
+
+/**
+ * What the row's dropdown reads, as Figma's: "5 columns", "3 rows (40px)", "Grid 10px", and
+ * "Columns (40px)" for as many as fit.
+ */
+function summary(grid: LayoutGrid): string {
+ const p = panels.value
+ const pattern = gridPattern(grid)
+ if (pattern === 'GRID') return p.gridSummaryGrid({ size: String(grid.sectionSize ?? 10) })
+ const count = String(layoutGridCount(grid))
+ const counted =
+ pattern === 'ROWS' ? p.gridSummaryRows({ count }) : p.gridSummaryColumns({ count })
+ const text = isAutoCount(grid) ? (pattern === 'ROWS' ? p.gridRows : p.gridColumns) : counted
+ return gridAlignment(grid) === 'STRETCH'
+ ? text
+ : p.gridSummaryFixed({ summary: text, size: String(grid.sectionSize ?? 0) })
+}
+
+/** Switches a guide's pattern, giving it the fields the new pattern needs, as Figma does. */
+function changePattern(index: number, grid: LayoutGrid, pattern: GridPattern) {
+ const stripes: Partial<LayoutGrid> = {
+ count: layoutGridCount(grid) > 1 ? layoutGridCount(grid) : DEFAULT_COUNT,
+ gutterSize: grid.gutterSize ?? 20,
+ offset: grid.offset ?? 0,
+ alignment: gridAlignment(grid)
+ }
+ patch(
+ index,
+ {
+ pattern,
+ axis: pattern === 'ROWS' ? 'Y' : 'X',
+ ...(pattern === 'GRID' ? { sectionSize: grid.sectionSize || 10 } : stripes)
+ },
+ 'Change grid pattern'
+ )
+}
+
+/** A stretched guide needs a count, so one that fit as many as it could gets Figma's default. */
+function changeAlignment(index: number, grid: LayoutGrid, alignment: GridAlignment) {
+ const count = alignment === 'STRETCH' && isAutoCount(grid) ? { count: DEFAULT_COUNT } : {}
+ patch(index, { alignment, type: alignment, ...count }, 'Change grid type')
+}
+
+function toggleExpanded(index: number) {
+ expanded.value = expanded.value === index ? null : index
+}
+
+/** Figma's new guide: a 10 px grid in translucent red. */
function defaultGrid(): LayoutGrid {
return {
visible: true,
color: { r: 1, g: 0, b: 0, a: 0.1 },
- pattern: 'COLUMNS',
+ pattern: 'GRID',
alignment: 'STRETCH',
- count: 5,
+ count: DEFAULT_COUNT,
gutterSize: 20,
offset: 0,
- sectionSize: 0
+ sectionSize: 10
}
}
+/** Runs one edit per selected frame, as one undo step. */
+function eachTarget(label: string, edit: (node: SceneNode) => void) {
+ const nodes = targets.value
+ if (nodes.length > 1) editor.undo.runBatch(label, () => nodes.forEach(edit))
+ else if (nodes[0]) edit(nodes[0])
+}
+
function commit(next: LayoutGrid[], label: string) {
- const node = selectedNode.value
- if (!node) return
- editor.updateNodeWithUndo(node.id, { layoutGrids: next }, label)
+ eachTarget(label, (node) =>
+ editor.updateNodeWithUndo(node.id, { layoutGrids: structuredClone(next) }, label)
+ )
}
function add() {
- commit([...grids.value, defaultGrid()], 'Add layout guide')
+ commit(mixed.value ? [defaultGrid()] : [...grids.value, defaultGrid()], 'Add layout guide')
}
function remove(index: number) {
+ expanded.value = null
commit(
grids.value.filter((_, i) => i !== index),
'Remove layout guide'
@@ -65,116 +158,211 @@ function patch(index: number, changes: Partial<LayoutGrid>, label = 'Edit layout
type NumericGridField = 'count' | 'gutterSize' | 'sectionSize' | 'offset'
+function withValue(index: number, key: NumericGridField, value: number) {
+ return grids.value.map((grid, i) => (i === index ? { ...grid, [key]: value } : grid))
+}
+
function updateNumber(index: number, key: NumericGridField, value: number) {
- const node = selectedNode.value
- if (!node) return
- editor.updateNode(node.id, {
- layoutGrids: grids.value.map((grid, i) => (i === index ? { ...grid, [key]: value } : grid))
- })
+ const next = withValue(index, key, value)
+ for (const node of targets.value)
+ editor.updateNode(node.id, { layoutGrids: structuredClone(next) })
}
function commitNumber(index: number, key: NumericGridField, previous: number) {
- const node = selectedNode.value
- if (!node) return
- editor.commitNodeUpdate(
- node.id,
- {
- layoutGrids: grids.value.map((grid, i) => (i === index ? { ...grid, [key]: previous } : grid))
- },
- 'Edit layout guide'
+ const before = withValue(index, key, previous)
+ eachTarget('Edit layout guide', (node) =>
+ editor.commitNodeUpdate(node.id, { layoutGrids: structuredClone(before) }, 'Edit layout guide')
)
}
-function gridPattern(grid: LayoutGrid): 'COLUMNS' | 'ROWS' | 'GRID' {
- if (grid.pattern) return grid.pattern
+/** A guide's pattern; one read from a file names stripes along an axis instead. */
+function gridPattern(grid: LayoutGrid): GridPattern {
+ if (grid.pattern === 'GRID' || grid.pattern === 'COLUMNS' || grid.pattern === 'ROWS')
+ return grid.pattern
return grid.axis === 'Y' ? 'ROWS' : 'COLUMNS'
}
-
-function isGrid(grid: LayoutGrid): boolean {
- return gridPattern(grid) === 'GRID'
-}
</script>
<template>
<PanelSection :label="panels.layoutGrids" :empty="grids.length === 0">
- <SharedStyleField kind="grid" :label="panels.gridStyle" />
+ <SharedStyleField v-if="targets.length === 1" kind="grid" :label="panels.gridStyle" />
<template #actions>
<IconButton :label="panels.addLayoutGrid" @click="add">
<icon-lucide-plus class="size-3.5" />
</IconButton>
</template>
- <PanelItemRow v-for="(grid, index) in grids" :key="index" class="items-start">
- <div class="flex min-w-0 flex-1 flex-col gap-1.5">
- <SegmentedControl
- :model-value="gridPattern(grid)"
- :options="patternOptions"
- :label="panels.layoutGrids"
- @change="
- patch(index, { pattern: $event as LayoutGrid['pattern'] }, 'Change grid pattern')
- "
- >
- <template #option="{ option }">
- <Tip :label="option.label">
- <span class="flex items-center justify-center">
- <icon-lucide-columns-3 v-if="option.value === 'COLUMNS'" class="size-3.5" />
- <icon-lucide-rows-3 v-else-if="option.value === 'ROWS'" class="size-3.5" />
- <icon-lucide-layout-grid v-else class="size-3.5" />
- </span>
- </Tip>
- </template>
- </SegmentedControl>
- <PanelGrid :columns="2">
+ <div v-for="{ grid, index } in rows" :key="index" data-layout-guide>
+ <PanelItemRow>
+ <div class="flex min-w-0 flex-1 items-center gap-1.5">
+ <Tip :label="panels.gridSettings">
+ <IconButton
+ :label="panels.gridSettings"
+ :active="expanded === index"
+ :aria-expanded="expanded === index"
+ data-property="layout-guide-settings"
+ @click="toggleExpanded(index)"
+ >
+ <icon-lucide-columns-3 v-if="gridPattern(grid) === 'COLUMNS'" class="size-3.5" />
+ <icon-lucide-rows-3 v-else-if="gridPattern(grid) === 'ROWS'" class="size-3.5" />
+ <icon-lucide-layout-grid v-else class="size-3.5" />
+ </IconButton>
+ </Tip>
+ <AppSelect
+ class="min-w-0 flex-1"
+ :model-value="gridPattern(grid)"
+ :options="patternOptions"
+ :display-label="summary(grid)"
+ :label="panels.layoutGrids"
+ data-property="layout-guide-pattern"
+ @update:model-value="changePattern(index, grid, $event)"
+ />
+ </div>
+ <template #rail>
+ <IconButton
+ :label="panels.toggleVisibility"
+ :active="grid.visible === false"
+ @click="patch(index, { visible: grid.visible === false }, 'Toggle layout guide')"
+ >
+ <icon-lucide-eye-off v-if="grid.visible === false" class="size-3.5" />
+ <icon-lucide-eye v-else class="size-3.5" />
+ </IconButton>
+ <IconButton :label="panels.removeLayoutGrid" @click="remove(index)">
+ <icon-lucide-minus class="size-3.5" />
+ </IconButton>
+ </template>
+ </PanelItemRow>
+
+ <div
+ v-if="expanded === index"
+ class="flex flex-col gap-1.5 py-2"
+ data-slot="layout-guide-settings"
+ >
+ <PanelGrid v-if="gridPattern(grid) !== 'GRID'" :columns="2">
<PanelFieldGroup :label="panels.gridCount">
<NumberField
- :model-value="grid.count ?? grid.numSections ?? 1"
+ :model-value="isAutoCount(grid) ? AUTO_SIZE : layoutGridCount(grid)"
+ :placeholder="panels.gridAuto"
:min="1"
:aria-label="panels.gridCount"
@update:model-value="updateNumber(index, 'count', $event)"
@commit="(_value, previous) => commitNumber(index, 'count', previous)"
+ >
+ <template #icon><icon-lucide-hash class="size-3" /></template>
+ </NumberField>
+ </PanelFieldGroup>
+ <PanelFieldGroup :label="panels.gridType">
+ <AppSelect
+ :model-value="gridAlignment(grid)"
+ :options="alignmentOptions(gridPattern(grid))"
+ :label="panels.gridType"
+ data-property="layout-guide-type"
+ @update:model-value="changeAlignment(index, grid, $event)"
/>
</PanelFieldGroup>
- <PanelFieldGroup v-if="!isGrid(grid)" :label="panels.gridGutter">
+ <PanelFieldGroup
+ :label="gridPattern(grid) === 'ROWS' ? panels.gridHeight : panels.gridWidth"
+ >
+ <NumberField
+ :model-value="gridAlignment(grid) === 'STRETCH' ? AUTO_SIZE : (grid.sectionSize ?? 0)"
+ :placeholder="panels.gridAuto"
+ :disabled="gridAlignment(grid) === 'STRETCH'"
+ :min="1"
+ :aria-label="gridPattern(grid) === 'ROWS' ? panels.gridHeight : panels.gridWidth"
+ @update:model-value="updateNumber(index, 'sectionSize', $event)"
+ @commit="(_value, previous) => commitNumber(index, 'sectionSize', previous)"
+ >
+ <template #icon>
+ <icon-lucide-move-vertical v-if="gridPattern(grid) === 'ROWS'" class="size-3" />
+ <icon-lucide-move-horizontal v-else class="size-3" />
+ </template>
+ </NumberField>
+ </PanelFieldGroup>
+ <PanelFieldGroup
+ :label="gridPattern(grid) === 'ROWS' ? panels.gridOffset : panels.gridMargin"
+ >
+ <NumberField
+ :model-value="grid.offset ?? 0"
+ :aria-label="gridPattern(grid) === 'ROWS' ? panels.gridOffset : panels.gridMargin"
+ @update:model-value="updateNumber(index, 'offset', $event)"
+ @commit="(_value, previous) => commitNumber(index, 'offset', previous)"
+ >
+ <template #icon>
+ <icon-lucide-arrow-down-to-line
+ v-if="gridPattern(grid) === 'ROWS'"
+ class="size-3"
+ />
+ <icon-lucide-arrow-right-to-line v-else class="size-3" />
+ </template>
+ </NumberField>
+ </PanelFieldGroup>
+ <PanelFieldGroup :label="panels.gridGutter">
<NumberField
:model-value="grid.gutterSize ?? 0"
:min="0"
:aria-label="panels.gridGutter"
@update:model-value="updateNumber(index, 'gutterSize', $event)"
@commit="(_value, previous) => commitNumber(index, 'gutterSize', previous)"
- />
+ >
+ <template #icon>
+ <icon-lucide-separator-horizontal
+ v-if="gridPattern(grid) === 'ROWS'"
+ class="size-3"
+ />
+ <icon-lucide-separator-vertical v-else class="size-3" />
+ </template>
+ </NumberField>
</PanelFieldGroup>
- <PanelFieldGroup v-if="isGrid(grid)" :label="panels.gridSectionSize">
+ </PanelGrid>
+ <PanelGrid v-else :columns="2">
+ <PanelFieldGroup :label="panels.gridSize">
<NumberField
- :model-value="grid.sectionSize ?? 0"
+ :model-value="grid.sectionSize ?? 10"
:min="1"
- :aria-label="panels.gridSectionSize"
+ :aria-label="panels.gridSize"
@update:model-value="updateNumber(index, 'sectionSize', $event)"
@commit="(_value, previous) => commitNumber(index, 'sectionSize', previous)"
- />
- </PanelFieldGroup>
- <PanelFieldGroup :label="panels.gridMargin">
- <NumberField
- :model-value="grid.offset ?? 0"
- :aria-label="panels.gridMargin"
- @update:model-value="updateNumber(index, 'offset', $event)"
- @commit="(_value, previous) => commitNumber(index, 'offset', previous)"
- />
+ >
+ <template #icon><icon-lucide-layout-grid class="size-3" /></template>
+ </NumberField>
</PanelFieldGroup>
</PanelGrid>
+ <PanelFieldGroup :label="panels.gridColor">
+ <div class="flex items-center gap-1.5">
+ <ColorInput
+ class="min-w-0 flex-1"
+ :color="grid.color ?? { r: 1, g: 0, b: 0, a: 0.1 }"
+ editable
+ @update="
+ patch(index, { color: { ...$event, a: grid.color?.a ?? 0.1 } }, 'Change grid color')
+ "
+ />
+ <Tip :label="panels.opacity">
+ <NumberField
+ class="w-14"
+ suffix="%"
+ :model-value="Math.round((grid.color?.a ?? 0.1) * 100)"
+ :min="0"
+ :max="100"
+ :aria-label="panels.opacity"
+ @commit="
+ (value) =>
+ patch(
+ index,
+ {
+ color: {
+ ...(grid.color ?? { r: 1, g: 0, b: 0, a: 0.1 }),
+ a: Math.max(0, Math.min(1, value / 100))
+ }
+ },
+ 'Change grid color'
+ )
+ "
+ />
+ </Tip>
+ </div>
+ </PanelFieldGroup>
</div>
- <template #rail>
- <IconButton
- :label="panels.toggleVisibility"
- :active="grid.visible === false"
- @click="patch(index, { visible: grid.visible === false }, 'Toggle layout guide')"
- >
- <icon-lucide-eye-off v-if="grid.visible === false" class="size-3.5" />
- <icon-lucide-eye v-else class="size-3.5" />
- </IconButton>
- <IconButton :label="panels.removeLayoutGrid" @click="remove(index)">
- <icon-lucide-minus class="size-3.5" />
- </IconButton>
- </template>
- </PanelItemRow>
+ </div>
</PanelSection>
</template>
diff --git a/src/components/ui/select/AppSelect.vue b/src/components/ui/select/AppSelect.vue
index 434427134..448d8a5e6 100644
--- a/src/components/ui/select/AppSelect.vue
+++ b/src/components/ui/select/AppSelect.vue
@@ -30,6 +30,8 @@ interface AppSelectProps<TValue extends string | number> {
groups?: AppSelectGroup<TValue>[]
/** Shown when the value matches no option, such as a size that fits no preset. */
placeholder?: string
+ /** Shown in the trigger instead of the chosen option, such as a summary of what it sets. */
+ displayLabel?: string
/**
* Defaults to `over` when the built-in trigger shows a chosen option, and to `below` for a
* `trigger` slot or a value outside the options: there is no row to line up with the trigger.
@@ -40,7 +42,8 @@ interface AppSelectProps<TValue extends string | number> {
defineOptions({ inheritAttrs: false })
-const { options, groups, label, placeholder, placement, ui } = defineProps<AppSelectProps<T>>()
+const { options, groups, label, placeholder, displayLabel, placement, ui } =
+ defineProps<AppSelectProps<T>>()
const modelValue = defineModel<T>({ required: true })
const slots = useSlots()
const styles = tv(theme)()
@@ -76,7 +79,7 @@ const itemUI = computed(() => ({ item: ui?.item, indicator: ui?.indicator }))
:class="styles.trigger({ class: ui?.trigger })"
>
<SelectValue :placeholder="placeholder" :class="styles.value({ class: ui?.value })">
- {{ selectedLabel ?? placeholder }}
+ {{ displayLabel ?? selectedLabel ?? placeholder }}
</SelectValue>
<icon-lucide-chevron-down :class="styles.chevron({ class: ui?.chevron })" />
</SelectTrigger>
diff --git a/src/theme/panel/header.ts b/src/theme/panel/header.ts
index 5aadfa31d..ea4f552c5 100644
--- a/src/theme/panel/header.ts
+++ b/src/theme/panel/header.ts
@@ -1,7 +1,7 @@
const panelHeaderTheme = {
slots: {
- root: 'grid min-w-0 grid-cols-[14px_minmax(0,1fr)_auto] items-center gap-1.5 border-b border-border px-3 py-2 text-surface',
- icon: 'flex size-3.5 items-center justify-center text-muted',
+ root: 'grid min-w-0 grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-1.5 border-b border-border px-3 py-2 text-surface',
+ icon: 'flex min-h-3.5 min-w-3.5 items-center justify-center text-muted',
title: 'min-w-0 truncate text-xs font-semibold text-surface',
actions:
'flex min-w-0 items-center justify-end gap-0.5 [&_[data-slot=icon-button]]:size-6 [&_[data-slot=icon-button]]:rounded'
diff --git a/tests/e2e/canvas/accent-selection.spec.ts-snapshots/green-selection-openpencil-darwin.png b/tests/e2e/canvas/accent-selection.spec.ts-snapshots/green-selection-openpencil-darwin.png
index 64c99f5c1..4512d56bd 100644
Binary files a/tests/e2e/canvas/accent-selection.spec.ts-snapshots/green-selection-openpencil-darwin.png and b/tests/e2e/canvas/accent-selection.spec.ts-snapshots/green-selection-openpencil-darwin.png differ
diff --git a/tests/e2e/canvas/frame-overlays.spec.ts b/tests/e2e/canvas/frame-overlays.spec.ts
index 38268b002..c6d7cad58 100644
--- a/tests/e2e/canvas/frame-overlays.spec.ts
+++ b/tests/e2e/canvas/frame-overlays.spec.ts
@@ -235,3 +235,33 @@ for (const angle of [-32, 32]) {
}
})
}
+
+// Figma desktop 126 draws neither handles nor a size label on a layer under 10 screen pixels both
+// ways, and both on a larger one.
+for (const [name, size] of [
+ ['tiny-layer-selected', 9],
+ ['small-layer-selected', 16]
+] as const) {
+ test(`a selected ${size} px layer ${size < 10 ? 'has no handles or size label' : 'has handles and its size'}`, async () => {
+ await editor.page.evaluate((side) => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const dot = store.graph.createNode('RECTANGLE', store.state.currentPageId, {
+ x: 200,
+ y: 200,
+ width: side,
+ height: side,
+ fills: [
+ { type: 'SOLID', color: { r: 0.8, g: 0.8, b: 0.8, a: 1 }, visible: true, opacity: 1 }
+ ]
+ })
+ store.state.zoom = 1
+ store.state.panX = 0
+ store.state.panY = 0
+ store.select([dot.id])
+ store.requestRender()
+ }, size)
+ await editor.canvas.waitForRender()
+ await expectCanvas(name)
+ })
+}
diff --git a/tests/e2e/canvas/frame-overlays.spec.ts-snapshots/small-layer-selected-openpencil-darwin.png b/tests/e2e/canvas/frame-overlays.spec.ts-snapshots/small-layer-selected-openpencil-darwin.png
new file mode 100644
index 000000000..c2db6711a
Binary files /dev/null and b/tests/e2e/canvas/frame-overlays.spec.ts-snapshots/small-layer-selected-openpencil-darwin.png differ
diff --git a/tests/e2e/canvas/frame-overlays.spec.ts-snapshots/tiny-layer-selected-openpencil-darwin.png b/tests/e2e/canvas/frame-overlays.spec.ts-snapshots/tiny-layer-selected-openpencil-darwin.png
new file mode 100644
index 000000000..e3bf59704
Binary files /dev/null and b/tests/e2e/canvas/frame-overlays.spec.ts-snapshots/tiny-layer-selected-openpencil-darwin.png differ
diff --git a/tests/e2e/canvas/scene-picture-freshness.spec.ts-snapshots/fresh-scene-picture-openpencil-darwin.png b/tests/e2e/canvas/scene-picture-freshness.spec.ts-snapshots/fresh-scene-picture-openpencil-darwin.png
index c28443268..112ee9924 100644
Binary files a/tests/e2e/canvas/scene-picture-freshness.spec.ts-snapshots/fresh-scene-picture-openpencil-darwin.png and b/tests/e2e/canvas/scene-picture-freshness.spec.ts-snapshots/fresh-scene-picture-openpencil-darwin.png differ
diff --git a/tests/e2e/canvas/section-clicks.spec.ts b/tests/e2e/canvas/section-clicks.spec.ts
new file mode 100644
index 000000000..84cb588fe
--- /dev/null
+++ b/tests/e2e/canvas/section-clicks.spec.ts
@@ -0,0 +1,42 @@
+import { expect, test } from '@playwright/test'
+
+import { CanvasHelper } from '#tests/helpers/canvas'
+import { sectionClicksDriver } from '#tests/helpers/canvas/section-clicks-driver'
+
+// Each case repeats a click in Figma desktop 126 on a section holding two frames.
+
+let scene: ReturnType<typeof sectionClicksDriver>
+let canvas: CanvasHelper
+
+test.beforeEach(async ({ page }) => {
+ await page.goto('/?test')
+ canvas = new CanvasHelper(page)
+ await canvas.waitForInit()
+ scene = sectionClicksDriver(() => page)
+ await scene.build()
+})
+
+test('a click on a section’s empty area selects it, a drag there marquee-selects inside it', async () => {
+ await canvas.click(750, 450)
+ await expect.poll(() => scene.selection()).toEqual(['Section'])
+ await scene.clearSelection()
+ await canvas.drag(80, 100, 550, 300)
+ await expect.poll(() => scene.selection()).toEqual(['Empty', 'Full'])
+})
+
+test('a right-click selects the frame or section whose empty area is under it', async ({
+ page
+}) => {
+ const clicked = scene
+ for (const [x, y, name] of [
+ [450, 180, 'Full'],
+ [150, 155, 'Empty'],
+ [700, 400, 'Section']
+ ] as const) {
+ await clicked.clearSelection()
+ const point = await clicked.point(x, y)
+ await page.mouse.click(point.x, point.y, { button: 'right' })
+ await expect.poll(() => clicked.selection()).toEqual([name])
+ await page.keyboard.press('Escape')
+ }
+})
diff --git a/tests/e2e/properties/layer-type.spec.ts b/tests/e2e/properties/layer-type.spec.ts
new file mode 100644
index 000000000..0f370f7a2
--- /dev/null
+++ b/tests/e2e/properties/layer-type.spec.ts
@@ -0,0 +1,18 @@
+import { expect, test } from '@playwright/test'
+
+import { CanvasHelper } from '#tests/helpers/canvas'
+import { layerTypeDriver } from '#tests/helpers/properties/layer-type-driver'
+
+test('the layer type menu turns a frame into a group and back', async ({ page }) => {
+ await page.goto('/?test')
+ await new CanvasHelper(page).waitForInit()
+ const layer = layerTypeDriver(() => page)
+ await layer.build()
+ const trigger = page.getByRole('button', { name: 'Layer type', exact: true })
+ await trigger.click()
+ await page.getByRole('menuitem', { name: 'Group', exact: true }).click()
+ await expect.poll(() => layer.type()).toBe('GROUP')
+ await trigger.click()
+ await page.getByRole('menuitem', { name: 'Frame', exact: true }).click()
+ await expect.poll(() => layer.type()).toBe('FRAME')
+})
diff --git a/tests/e2e/properties/layout-guides.spec.ts b/tests/e2e/properties/layout-guides.spec.ts
new file mode 100644
index 000000000..fc1efca30
--- /dev/null
+++ b/tests/e2e/properties/layout-guides.spec.ts
@@ -0,0 +1,69 @@
+import { expect, test, type Page } from '@playwright/test'
+
+import { CanvasHelper } from '#tests/helpers/canvas'
+import { layoutGuidesDriver } from '#tests/helpers/properties/layout-guides-driver'
+
+// Each case repeats a selection made in Figma desktop 126.
+
+const COLUMNS = {
+ pattern: 'COLUMNS' as const,
+ count: 5,
+ gutterSize: 20,
+ offset: 0,
+ visible: true,
+ color: { r: 1, g: 0, b: 0, a: 0.1 }
+}
+
+async function setup(page: Page, guides: (typeof COLUMNS)[][]) {
+ await page.goto('/?test')
+ await new CanvasHelper(page).waitForInit()
+ const scene = layoutGuidesDriver(() => page)
+ return { scene, ...(await scene.build(guides)) }
+}
+
+const heading = (page: Page) => page.getByRole('heading', { name: 'Layout guide', exact: true })
+
+test('frames with the same guides list them, and an edit changes every frame in one Undo', async ({
+ page
+}) => {
+ const { scene, frames } = await setup(page, [[COLUMNS], [COLUMNS]])
+ await scene.select(frames)
+ await expect(page.locator('[data-property="layout-guide-pattern"]')).toHaveText('5 columns')
+ await page.locator('[data-property="layout-guide-settings"]').click()
+ const count = page.getByRole('spinbutton', { name: 'Count', exact: true })
+ await expect(count).toBeVisible()
+ await count.dblclick()
+ await count.fill('8')
+ await count.press('Enter')
+ await expect.poll(() => scene.guides(frames)).toEqual([['COLUMNS 8'], ['COLUMNS 8']])
+ await heading(page).click()
+ await page.keyboard.press('ControlOrMeta+z')
+ await expect.poll(() => scene.guides(frames)).toEqual([['COLUMNS 5'], ['COLUMNS 5']])
+})
+
+test('frames with different guides show none, and Add gives each one 10 px grid', async ({
+ page
+}) => {
+ const { scene, frames } = await setup(page, [[COLUMNS], []])
+ await scene.select(frames)
+ await expect(heading(page)).toBeVisible()
+ await expect(page.locator('[data-property="layout-guide-settings"]')).toHaveCount(0)
+ await page.getByRole('button', { name: 'Add layout guide' }).click()
+ await expect.poll(() => scene.guides(frames)).toEqual([['GRID 5 10'], ['GRID 5 10']])
+})
+
+test('switching a guide to rows keeps its count and names the new pattern', async ({ page }) => {
+ const { scene, frames } = await setup(page, [[COLUMNS]])
+ await scene.select(frames)
+ await page.locator('[data-property="layout-guide-pattern"]').click()
+ await page.getByRole('option', { name: 'Rows', exact: true }).click()
+ await expect.poll(() => scene.guides(frames)).toEqual([['ROWS 5']])
+ await expect(page.locator('[data-property="layout-guide-pattern"]')).toHaveText('5 rows')
+})
+
+test('a selection with a layer that is not a frame has no layout guides', async ({ page }) => {
+ const { scene, frames, rect } = await setup(page, [[COLUMNS]])
+ await scene.select([frames[0], rect])
+ await expect(page.getByRole('heading', { name: 'Fill', exact: true })).toBeVisible()
+ await expect(heading(page)).toHaveCount(0)
+})
diff --git a/tests/engine/io/fig/export/shared-styles.test.ts b/tests/engine/io/fig/export/shared-styles.test.ts
index 75134f96b..ce908d973 100644
--- a/tests/engine/io/fig/export/shared-styles.test.ts
+++ b/tests/engine/io/fig/export/shared-styles.test.ts
@@ -36,7 +36,16 @@ describe('Figma shared style export', () => {
styleIdForText: { guid: { sessionID: 1, localID: 12 } },
styleIdForEffect: { guid: { sessionID: 1, localID: 13 } },
styleIdForGrid: { guid: { sessionID: 1, localID: 14 } },
- layoutGrids: [{ pattern: 'COLUMNS', count: 12, gutterSize: 16, visible: true }]
+ layoutGrids: [
+ {
+ pattern: 'STRIPES',
+ axis: 'X',
+ type: 'STRETCH',
+ numSections: 12,
+ gutterSize: 16,
+ visible: true
+ }
+ ]
})
})
diff --git a/tests/helpers/canvas/section-clicks-driver.ts b/tests/helpers/canvas/section-clicks-driver.ts
new file mode 100644
index 000000000..4aebc3d3c
--- /dev/null
+++ b/tests/helpers/canvas/section-clicks-driver.ts
@@ -0,0 +1,45 @@
+import type { Page } from '@playwright/test'
+
+import type * as SectionScene from '#tests/helpers/canvas/section-clicks'
+
+/** The view offset the scene is shown at, at zoom 1, so canvas points are scene points plus it. */
+const PAN = 50
+
+/** Builds the section-click scene and reads back what pointer input selected. */
+export function sectionClicksDriver(page: () => Page) {
+ return {
+ build() {
+ return page().evaluate(async (pan) => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const fixtureURL = '/tests/helpers/canvas/section-clicks.ts'
+ const scene: typeof SectionScene = await import(fixtureURL)
+ scene.createSectionClickScene(store.graph, store.state.currentPageId)
+ store.state.zoom = 1
+ store.state.panX = pan
+ store.state.panY = pan
+ store.clearSelection()
+ store.requestRender()
+ }, PAN)
+ },
+
+ clearSelection() {
+ return page().evaluate(() => window.openPencil?.getStore?.().clearSelection())
+ },
+
+ /** The selected layers' names. */
+ selection() {
+ return page().evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ return [...(store?.state.selectedIds ?? [])].map((id) => store?.graph.getNode(id)?.name)
+ })
+ },
+
+ /** The page point over a scene point. */
+ async point(x: number, y: number) {
+ const box = await page().getByTestId('canvas-element').boundingBox()
+ if (!box) throw new Error('Canvas has no bounding box')
+ return { x: box.x + PAN + x, y: box.y + PAN + y }
+ }
+ }
+}
diff --git a/tests/helpers/canvas/section-clicks.ts b/tests/helpers/canvas/section-clicks.ts
new file mode 100644
index 000000000..16d8b6493
--- /dev/null
+++ b/tests/helpers/canvas/section-clicks.ts
@@ -0,0 +1,32 @@
+import type { Fill, SceneGraph } from '@open-pencil/scene-graph'
+
+const WHITE: Fill[] = [
+ { type: 'SOLID', color: { r: 1, g: 1, b: 1, a: 1 }, opacity: 1, visible: true }
+]
+
+/** The section Figma desktop 126 was clicked on: an empty frame and one holding a rectangle. */
+export function createSectionClickScene(graph: SceneGraph, pageId: string) {
+ const section = graph.createNode('SECTION', pageId, {
+ name: 'Section',
+ width: 800,
+ height: 500,
+ fills: WHITE
+ })
+ graph.createNode('FRAME', section.id, {
+ name: 'Empty',
+ x: 50,
+ y: 80,
+ width: 200,
+ height: 150,
+ fills: WHITE
+ })
+ const full = graph.createNode('FRAME', section.id, {
+ name: 'Full',
+ x: 300,
+ y: 80,
+ width: 200,
+ height: 150,
+ fills: WHITE
+ })
+ graph.createNode('RECTANGLE', full.id, { name: 'Child', x: 10, y: 10, width: 40, height: 40 })
+}
diff --git a/tests/helpers/properties/layer-type-driver.ts b/tests/helpers/properties/layer-type-driver.ts
new file mode 100644
index 000000000..34f807914
--- /dev/null
+++ b/tests/helpers/properties/layer-type-driver.ts
@@ -0,0 +1,27 @@
+import type { Page } from '@playwright/test'
+
+/** Builds a frame holding a rectangle, selected, and reads back the layer's type. */
+export function layerTypeDriver(page: () => Page) {
+ let id: string | undefined
+
+ return {
+ async build() {
+ id = await page().evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const frame = store.createShape('FRAME', 100, 100, 200, 150)
+ store.createShape('RECTANGLE', 20, 20, 40, 40, frame)
+ store.select([frame])
+ return frame
+ })
+ },
+
+ type() {
+ if (!id) throw new Error('Build the scene first')
+ return page().evaluate(
+ (nodeId) => window.openPencil?.getStore?.().graph.getNode(nodeId)?.type,
+ id
+ )
+ }
+ }
+}
diff --git a/tests/helpers/properties/layout-guides-driver.ts b/tests/helpers/properties/layout-guides-driver.ts
new file mode 100644
index 000000000..a3ec7bce0
--- /dev/null
+++ b/tests/helpers/properties/layout-guides-driver.ts
@@ -0,0 +1,43 @@
+import type { Page } from '@playwright/test'
+
+import type { LayoutGrid } from '@open-pencil/scene-graph'
+
+/** Builds frames with layout guides and a rectangle, selects them, and reads their guides back. */
+export function layoutGuidesDriver(page: () => Page) {
+ return {
+ /** One frame per guide list, side by side, and a rectangle below them. */
+ build(guides: LayoutGrid[][]) {
+ return page().evaluate((guides) => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const frames = guides.map((layoutGrids, index) => {
+ const id = store.createShape('FRAME', 100 + index * 260, 100, 200, 150)
+ store.updateNode(id, { layoutGrids })
+ return id
+ })
+ const rect = store.createShape('RECTANGLE', 100, 400, 100, 100)
+ return { frames, rect }
+ }, guides)
+ },
+
+ select(ids: string[]) {
+ return page().evaluate((ids) => window.openPencil?.getStore?.().select(ids), ids)
+ },
+
+ /** Each layer's guides, as "PATTERN count sectionSize". */
+ guides(ids: string[]) {
+ return page().evaluate(
+ (ids) =>
+ ids.map((id) =>
+ window.openPencil
+ ?.getStore?.()
+ .graph.getNode(id)
+ ?.layoutGrids.map((grid) =>
+ `${grid.pattern} ${grid.count ?? ''} ${grid.sectionSize ?? ''}`.trim()
+ )
+ ),
+ ids
+ )
+ }
+ }
+}
diff --git a/tools/checks/i18n/mixed-script-baseline.txt b/tools/checks/i18n/mixed-script-baseline.txt
index 745a5e9fa..682802e3e 100644
--- a/tools/checks/i18n/mixed-script-baseline.txt
+++ b/tools/checks/i18n/mixed-script-baseline.txt
@@ -427,3 +427,5 @@ zh-cn:variables.conditionCustom
zh-cn:panels.shaderPreset
zh-cn:panels.invalidShaderPreset
zh-cn:panels.shaderNeedsWebGPU
+ja:panels.gridSummaryGrid
+zh-cn:panels.gridSummaryGrid
diff --git a/tools/checks/i18n/translation-baseline.txt b/tools/checks/i18n/translation-baseline.txt
index aa6e03bf4..c63a6fec2 100644
--- a/tools/checks/i18n/translation-baseline.txt
+++ b/tools/checks/i18n/translation-baseline.txt
@@ -342,3 +342,10 @@ pl:variables.unitAuto
es:menu.variables
fr:menu.variables
fr:variables.collections
+de:panels.gridAuto
+es:panels.gridColor
+es:panels.gridAuto
+fr:panels.gridType
+fr:panels.gridAuto
+it:panels.gridAuto
+pl:panels.gridAuto