Skip to content

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

fix: remaining Figma parity for overrides, sections, sizing, paste, and gaps (#1112)

Danila Poyarkov529d9b847022
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1209a19c1..2e8d2b32d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -34,19 +34,23 @@ This is a pre-release that lists changes since 0.16.0-beta.1: npm packages are p
### Breaking changes
+- `useCanvasInput` in `@open-pencil/vue` returns `autoLayoutValueEdit` with `updateAutoLayoutValueEdit`, `commitAutoLayoutValueEdit`, and `cancelAutoLayoutValueEdit` in place of the padding-only `autoLayoutPaddingEdit` and its functions; the edit names its `field` (a padding or `itemSpacing`), and `autoLayoutValueAnchor` places its editor.
- `CORNER_ROTATE_ZONE` is removed from `@open-pencil/core/constants`; the selection's resize and rotation zones are `TRANSFORM_ZONE` and `transformZoneAt` in `@open-pencil/core/geometry`, which also owns the `HandlePosition` and `CornerPosition` types.
- In scripts, a text node's `textCase`, `textStyleId`, and `fillStyleId` now also read `figma.mixed` while its characters differ, as in Figma, instead of the text's own value, and setting one restyles every character.
### Added
+- Double-click an auto layout gap on the canvas to edit it, as a padding, as in Figma.
+- In scripts, an instance's `overrides` lists each layer edited in it, nested instances included, under Figma's field names, and `resetOverrides()` returns the instance and the instances inside it to their components, keeping the values component properties set.
- Enter opens a selected vector's path for editing, as a double-click does, as in Figma.
- 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.
+- Switch a frame, group, or section to another of them 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. A frame or group on the page or in a section becomes a section that keeps its fill, strokes, corners, and layers where they are, and a section becomes a frame.
- 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
+- In scripts, as in Figma, a new frame or component hugs along its main axis once auto layout is on, `resize` fixes a hugging auto layout frame's size, a grid's sizing is fixed, setting a layer inside an instance to the value it already has makes no override, and `counterAxisAlignContent` is refused on a layer inside an instance.
- 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.
@@ -60,6 +64,9 @@ This is a pre-release that lists changes since 0.16.0-beta.1: npm packages are p
### Fixed
+- A row that hugs its height around a stretched layer keeps that height when pasted or saved into Figma, which shrank it to its other layers. The padding and gap values shown on hover fit their numbers, as in Figma.
+- Editing a component keeps the size of a text copy that styles its text on its own and of a copy that fills its parent, so instances around them no longer grow or shrink.
+- Path editing closes when its vector is deleted, by undo or a script, or when another document opens.
- Preview draws controls as the canvas does: in the variable modes the canvas is showing, also after a mode switch or a variable edit, with icons and vector layers as drawn and shader fills playing behind their layers from the canvas's own shader players.
- Opening a page also loads the pages holding the component sets its instances use, so the variant picker and preview can switch to any variant of a set kept on a page not opened yet. Library copies on Figma's internal canvas stay as the file stores them, and a page that opens later no longer re-reads components an earlier page already built.
- A slot frame whose corner radius or other field is bound to a variable stays a slot when the file is saved and reopened.
diff --git a/packages/core/src/canvas/overlays/auto-layout-hover.ts b/packages/core/src/canvas/overlays/auto-layout-hover.ts
index 6a9859c10..067c2a54a 100644
--- a/packages/core/src/canvas/overlays/auto-layout-hover.ts
+++ b/packages/core/src/canvas/overlays/auto-layout-hover.ts
@@ -15,6 +15,8 @@ import {
AUTO_LAYOUT_HOVER_STROKE_WIDTH,
AUTO_LAYOUT_HOVER_TICK_LENGTH,
AUTO_LAYOUT_HOVER_VALUE_OFFSET,
+ AUTO_LAYOUT_HOVER_GAP_PILL,
+ AUTO_LAYOUT_HOVER_PADDING_PILL,
AUTO_LAYOUT_HOVER_VALUE_PILL_HEIGHT,
AUTO_LAYOUT_HOVER_VALUE_PILL_PADDING_X,
AUTO_LAYOUT_HOVER_VALUE_PILL_RADIUS
@@ -104,25 +106,39 @@ function drawStripedRect(
immutablePath.delete()
}
-function drawValuePill(r: SkiaRenderer, canvas: Canvas, text: string, x: number, y: number) {
- if (!r.labelFont) return
- const width = Math.max(24, text.length * 8 + AUTO_LAYOUT_HOVER_VALUE_PILL_PADDING_X * 2)
+/** A value in a pill as wide as its text, its digits centred, as Figma draws padding and gaps. */
+function drawValuePill(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ text: string,
+ x: number,
+ y: number,
+ color: Color
+) {
+ const font = r.valueFont ?? r.labelFont
+ if (!font) return
+ const glyphs = font.getGlyphIDs(text)
+ let advance = 0
+ for (const glyphWidth of font.getGlyphWidths(glyphs)) advance += glyphWidth
+ // The ink's top and bottom, so the digits sit in the middle whatever the font's metrics.
+ const bounds = font.getGlyphBounds(glyphs)
+ let top = 0
+ let bottom = 0
+ for (let i = 0; i < bounds.length; i += 4) {
+ top = Math.min(top, bounds[i + 1])
+ bottom = Math.max(bottom, bounds[i + 3])
+ }
+ const width = advance + AUTO_LAYOUT_HOVER_VALUE_PILL_PADDING_X * 2
const height = AUTO_LAYOUT_HOVER_VALUE_PILL_HEIGHT
const rect = r.ck.RRectXY(
r.ck.LTRBRect(x - width / 2, y - height / 2, x + width / 2, y + height / 2),
AUTO_LAYOUT_HOVER_VALUE_PILL_RADIUS,
AUTO_LAYOUT_HOVER_VALUE_PILL_RADIUS
)
- r.auxFill.setColor(r.selColor())
+ r.auxFill.setColor(canvasColor(r, color))
canvas.drawRRect(rect, r.auxFill)
r.auxFill.setColor(r.ck.Color4f(1, 1, 1, 1))
- canvas.drawText(
- text,
- x - width / 2 + AUTO_LAYOUT_HOVER_VALUE_PILL_PADDING_X,
- y + 5,
- r.auxFill,
- r.labelFont
- )
+ canvas.drawText(text, x - advance / 2, y - (top + bottom) / 2, r.auxFill, font)
}
function gapRects(node: SceneNode, graph: SceneGraph): RectTuple[] {
@@ -226,7 +242,8 @@ function drawSpacingHover(
canvas,
String(Math.round(node.itemSpacing)),
(x + width / 2) * r.zoom + r.panX + AUTO_LAYOUT_HOVER_VALUE_OFFSET,
- (y + height / 2) * r.zoom + r.panY - AUTO_LAYOUT_HOVER_VALUE_OFFSET
+ (y + height / 2) * r.zoom + r.panY - AUTO_LAYOUT_HOVER_VALUE_OFFSET,
+ AUTO_LAYOUT_HOVER_GAP_PILL
)
}
@@ -249,7 +266,8 @@ function drawPaddingHover(
canvas,
String(Math.round(value)),
(x + width / 2) * r.zoom + r.panX + AUTO_LAYOUT_HOVER_VALUE_OFFSET,
- (y + height / 2) * r.zoom + r.panY - AUTO_LAYOUT_HOVER_VALUE_OFFSET
+ (y + height / 2) * r.zoom + r.panY - AUTO_LAYOUT_HOVER_VALUE_OFFSET,
+ AUTO_LAYOUT_HOVER_PADDING_PILL
)
}
diff --git a/packages/core/src/canvas/renderer.ts b/packages/core/src/canvas/renderer.ts
index 06e163806..351b91d66 100644
--- a/packages/core/src/canvas/renderer.ts
+++ b/packages/core/src/canvas/renderer.ts
@@ -117,6 +117,8 @@ export class SkiaRenderer {
textFont: Font | null = null
labelFont: Font | null = null
sizeFont: Font | null = null
+ /** Inter SemiBold at 11 px, which Figma sets the padding and gap values on the canvas in. */
+ valueFont: Font | null = null
sectionTitleFont: Font | null = null
componentLabelFont: Font | null = null
fontMgr: FontMgr | null = null
diff --git a/packages/core/src/canvas/renderer/fonts.ts b/packages/core/src/canvas/renderer/fonts.ts
index c5e7a03c7..28cf01638 100644
--- a/packages/core/src/canvas/renderer/fonts.ts
+++ b/packages/core/src/canvas/renderer/fonts.ts
@@ -9,7 +9,8 @@ import {
SECTION_TITLE_FONT_FAMILY,
SECTION_TITLE_FONT_SIZE,
SECTION_TITLE_FONT_URL,
- SIZE_FONT_SIZE
+ SIZE_FONT_SIZE,
+ VALUE_FONT_SIZE
} from '#core/constants'
import { withTextMeasurer } from '#core/layout/text-measurement'
import { fontManager } from '#core/text/fonts'
@@ -95,6 +96,15 @@ export function getFontProvider(r: SkiaRenderer) {
function registerSectionTitleFont(r: SkiaRenderer, data: ArrayBuffer) {
r.fontProvider?.registerFont(data, SECTION_TITLE_FONT_FAMILY)
fontManager.registerFontInBrowser(SECTION_TITLE_FONT_FAMILY, 'SemiBold', data)
+ const typeface = r.ck.Typeface.MakeFreeTypeFaceFromData(data)
+ if (!typeface) return
+ try {
+ r.valueFont?.delete()
+ r.valueFont = new r.ck.Font(typeface, VALUE_FONT_SIZE)
+ } finally {
+ // The font holds its own reference to the face.
+ typeface.delete()
+ }
}
export async function loadFonts(
diff --git a/packages/core/src/canvas/renderer/lifecycle.ts b/packages/core/src/canvas/renderer/lifecycle.ts
index d6d15db76..4eb578ec5 100644
--- a/packages/core/src/canvas/renderer/lifecycle.ts
+++ b/packages/core/src/canvas/renderer/lifecycle.ts
@@ -60,6 +60,7 @@ export function destroyRenderer(r: SkiaRenderer): void {
r.textFont?.delete()
r.labelFont?.delete()
r.sizeFont?.delete()
+ r.valueFont?.delete()
r.sectionTitleFont?.delete()
r.componentLabelFont?.delete()
r.fontMgr?.delete()
diff --git a/packages/core/src/constants.ts b/packages/core/src/constants.ts
index 005f5c159..2fd6bfee5 100644
--- a/packages/core/src/constants.ts
+++ b/packages/core/src/constants.ts
@@ -54,6 +54,7 @@ export const DEFAULT_STROKE_MITER_LIMIT = 4
/** Figma's stroke weight for a node that has not been given one. */
export const LABEL_FONT_SIZE = 11
export const SIZE_FONT_SIZE = 10
+export const VALUE_FONT_SIZE = 11
export const HANDLE_HALF_SIZE = 3
@@ -80,9 +81,10 @@ export const AUTO_LAYOUT_HOVER_STROKE_WIDTH = 1.5
export const LAYOUT_OUTLINE_DASH = 1.75
export const LAYOUT_OUTLINE_GAP = 1.25
export const AUTO_LAYOUT_HOVER_VALUE_OFFSET = 18
-export const AUTO_LAYOUT_HOVER_VALUE_PILL_HEIGHT = 22
-export const AUTO_LAYOUT_HOVER_VALUE_PILL_RADIUS = 5
-export const AUTO_LAYOUT_HOVER_VALUE_PILL_PADDING_X = 5
+// Measured on Figma desktop 126's padding and gap value pills.
+export const AUTO_LAYOUT_HOVER_VALUE_PILL_HEIGHT = 16.5
+export const AUTO_LAYOUT_HOVER_VALUE_PILL_RADIUS = 2.5
+export const AUTO_LAYOUT_HOVER_VALUE_PILL_PADDING_X = 4.5
export const AUTO_LAYOUT_HOVER_GAP_REGION_TOLERANCE = 12
export const AUTO_LAYOUT_HOVER_TICK_HIT_TOLERANCE = 8
export const AUTO_LAYOUT_HOVER_PADDING_REGION_TOLERANCE = 20
@@ -92,6 +94,9 @@ export const AUTO_LAYOUT_HOVER_BLUE = { r: 0.28, g: 0.64, b: 1, a: 0.82 } satisf
export const AUTO_LAYOUT_HOVER_BLUE_FILL = { r: 0.28, g: 0.64, b: 1, a: 0.1 } satisfies Color
export const AUTO_LAYOUT_HOVER_MAGENTA = { r: 1, g: 0.32, b: 0.68, a: 0.78 } satisfies Color
export const AUTO_LAYOUT_HOVER_MAGENTA_FILL = { r: 1, g: 0.32, b: 0.68, a: 0.1 } satisfies Color
+// The value pills over a gap and a padding, sampled from Figma desktop 126.
+export const AUTO_LAYOUT_HOVER_GAP_PILL = { r: 0.886, g: 0.271, b: 0.686, a: 1 } satisfies Color
+export const AUTO_LAYOUT_HOVER_PADDING_PILL = { r: 0.271, g: 0.592, b: 0.973, a: 1 } satisfies Color
export const SECTION_TITLE_HEIGHT = 24
export const SECTION_TITLE_PADDING_X = 6
diff --git a/packages/core/src/editor/bridges/lint.ts b/packages/core/src/editor/bridges/lint.ts
index 6c43a5761..97c55be16 100644
--- a/packages/core/src/editor/bridges/lint.ts
+++ b/packages/core/src/editor/bridges/lint.ts
@@ -22,7 +22,7 @@ export function createLintFixBridge(
graph: ctx.graph,
updateNode: (id, changes) => nodes.updateNodeWithUndo(id, changes, 'Fix design issue'),
bindVariable: nodes.bindVariable,
- convertToFrame: structure.convertGroupToFrame,
+ convertToFrame: (id) => structure.convertLayerType(id, 'FRAME'),
deleteNodes: (ids) => clipboard.deleteNodes(ids)
},
requests
diff --git a/packages/core/src/editor/bridges/structure.ts b/packages/core/src/editor/bridges/structure.ts
index e3f2aed24..14adba6ba 100644
--- a/packages/core/src/editor/bridges/structure.ts
+++ b/packages/core/src/editor/bridges/structure.ts
@@ -1,5 +1,6 @@
import type { createSelectionActions } from '#core/editor/selection'
import type { createStructureActions } from '#core/editor/structure'
+import type { LayerType } from '#core/editor/structure/layer-type'
type SelectionActions = ReturnType<typeof createSelectionActions>
type StructureActions = ReturnType<typeof createStructureActions>
@@ -15,10 +16,7 @@ export function createStructureBridge(structure: StructureActions, selection: Se
outlineTextSelected: () => structure.outlineTextSelected(selection.getSelectedNodes()),
outlineStrokeSelected: () => structure.outlineStrokeSelected(selection.getSelectedNodes()),
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)
+ /** Switches a layer to another type in place, as Figma's layer type menu does. */
+ convertLayerType: (nodeId: string, type: LayerType) => structure.convertLayerType(nodeId, type)
}
}
diff --git a/packages/core/src/editor/index.ts b/packages/core/src/editor/index.ts
index 8d9d7d81d..39a194f09 100644
--- a/packages/core/src/editor/index.ts
+++ b/packages/core/src/editor/index.ts
@@ -40,6 +40,7 @@ export { reapplyInstanceComponentProperties } from './components/properties'
export { createGuideActions } from './guides'
export { createTextActions } from './text'
export { opacityFromBuffer } from './nodes'
+export { layerTypeOptions, type LayerType } from './structure/layer-type'
export type { NodePreview } from './node-preview'
export { EDITOR_TOOLS, TOOL_SHORTCUTS } from './tool-registry'
export type { RenameSelectionOptions, RenameSelectionPreview } from './structure/rename'
diff --git a/packages/core/src/editor/structure.ts b/packages/core/src/editor/structure.ts
index 0331ce958..184ec1469 100644
--- a/packages/core/src/editor/structure.ts
+++ b/packages/core/src/editor/structure.ts
@@ -1,14 +1,5 @@
-import { pick } from 'es-toolkit/object'
+import { createsComponentCycle, type SceneNode } from '@open-pencil/scene-graph'
-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 +14,7 @@ import {
outlineStrokeSelected as outlineStrokeSelectedImpl
} from './structure/flatten'
import { ungroupSelected as ungroupImpl } from './structure/group'
+import { createLayerTypeActions } from './structure/layer-type'
import {
defaultNodeName,
previewRenamedNodes,
@@ -32,28 +24,10 @@ 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)
+ const layerTypeActions = createLayerTypeActions(ctx)
function isTopLevel(parentId: string | null): boolean {
return !parentId || parentId === ctx.graph.rootId || parentId === ctx.state.currentPageId
@@ -106,75 +80,6 @@ export function createStructureActions(ctx: EditorContext) {
return wrapSelectionInContainer('FRAME', selectedNodes)
}
- /**
- * 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 = (changes: Partial<SceneNode>) => {
- ctx.graph.updateNode(nodeId, changes)
- ctx.runLayoutForNode(nodeId)
- }
- 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(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)
- }
- })
- }
-
function booleanOperationSelected(selectedNodes: SceneNode[], operation: BooleanOperation) {
return booleanOperationSelectedImpl(ctx, selectedNodes, operation)
}
@@ -253,8 +158,7 @@ export function createStructureActions(ctx: EditorContext) {
wrapInAutoLayout,
groupSelected,
frameSelection,
- convertFrameToGroup,
- convertGroupToFrame,
+ ...layerTypeActions,
booleanOperationSelected,
ungroupSelected,
flattenSelected,
diff --git a/packages/core/src/editor/structure/layer-type.ts b/packages/core/src/editor/structure/layer-type.ts
new file mode 100644
index 000000000..04e8ff0be
--- /dev/null
+++ b/packages/core/src/editor/structure/layer-type.ts
@@ -0,0 +1,172 @@
+import { pick } from 'es-toolkit/object'
+
+import {
+ fitEnclosingGroups,
+ redoGroupFit,
+ undoGroupFit,
+ type SceneGraph,
+ type SceneNode
+} from '@open-pencil/scene-graph'
+
+import { groupFitOptions } from '#core/canvas/boolean'
+import type { EditorContext } from '#core/editor/types'
+
+/** The types Figma's layer type menu switches between. */
+export type LayerType = 'FRAME' | 'GROUP' | 'SECTION'
+
+/** 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
+
+/** What a frame or group has and a section does not, restored when the change is undone. */
+const NON_SECTION_FIELDS = [
+ 'type',
+ 'opacity',
+ 'effects',
+ 'effectStyleId',
+ 'clipsContent',
+ 'layoutMode',
+ 'strokeWeight',
+ 'strokes'
+] as const
+
+/**
+ * The types a layer can switch to from Figma's layer type menu (Figma desktop 126): a section
+ * sits on the page or in a section, a group needs layers, a section never becomes a group, and
+ * one holding a section never becomes a frame.
+ */
+export function layerTypeOptions(graph: SceneGraph, node: SceneNode): Record<LayerType, boolean> {
+ const parent = node.parentId ? graph.getNode(node.parentId) : undefined
+ const topLevel = parent?.type === 'CANVAS' || parent?.type === 'SECTION'
+ // A frame cannot hold a section, so a section holding one stays a section.
+ const holdsSection = node.childIds.some((id) => graph.getNode(id)?.type === 'SECTION')
+ return {
+ FRAME: !holdsSection,
+ GROUP: node.type !== 'SECTION' && node.childIds.length > 0,
+ SECTION: topLevel
+ }
+}
+
+export function createLayerTypeActions(ctx: EditorContext) {
+ function pushChange(
+ label: string,
+ nodeId: string,
+ before: Partial<SceneNode>,
+ after: Partial<SceneNode>
+ ) {
+ const apply = (changes: Partial<SceneNode>) => {
+ ctx.graph.updateNode(nodeId, structuredClone(changes))
+ ctx.runLayoutForNode(nodeId)
+ }
+ apply(after)
+ ctx.undo.push({ label, forward: () => apply(after), inverse: () => apply(before) })
+ }
+
+ /**
+ * 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. A section becomes a frame the same way, keeping its fill and strokes.
+ */
+ function convertToFrame(nodeId: string) {
+ const node = ctx.graph.getNode(nodeId)
+ if (node?.type !== 'GROUP' && node?.type !== 'SECTION') return
+ if (!layerTypeOptions(ctx.graph, node).FRAME) return
+ const before = { type: node.type, clipsContent: node.clipsContent }
+ pushChange('Convert to frame', nodeId, before, { type: 'FRAME', clipsContent: true })
+ }
+
+ /**
+ * 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)
+ }
+ })
+ }
+
+ /**
+ * Turns a frame or group on the page or in a section into a section in place, as Figma's layer
+ * type menu does: its layers stay where they are, auto layout included, and it keeps its fill,
+ * strokes and corners, but not what a section lacks: opacity, effects, clipping, auto layout,
+ * and a stroke weight of its own.
+ */
+ function convertToSection(nodeId: string) {
+ const node = ctx.graph.getNode(nodeId)
+ if (node?.type !== 'FRAME' && node?.type !== 'GROUP') return
+ if (!layerTypeOptions(ctx.graph, node).SECTION) return
+ const before = structuredClone(pick(node, NON_SECTION_FIELDS))
+ pushChange('Convert to section', nodeId, before, {
+ type: 'SECTION',
+ opacity: 1,
+ effects: [],
+ effectStyleId: null,
+ clipsContent: false,
+ layoutMode: 'NONE',
+ strokeWeight: 1,
+ strokes: node.strokes.map((stroke) => ({ ...stroke, weight: 1 }))
+ })
+ }
+
+ /** Switches a layer to another type in place, as Figma's layer type menu does. */
+ function convertLayerType(nodeId: string, type: LayerType) {
+ if (type === 'GROUP') convertFrameToGroup(nodeId)
+ else if (type === 'SECTION') convertToSection(nodeId)
+ else convertToFrame(nodeId)
+ }
+
+ return { convertLayerType }
+}
diff --git a/packages/core/src/figma-api/accessor-utils.ts b/packages/core/src/figma-api/accessor-utils.ts
index 3a210077e..5c35dba62 100644
--- a/packages/core/src/figma-api/accessor-utils.ts
+++ b/packages/core/src/figma-api/accessor-utils.ts
@@ -1,3 +1,5 @@
+import { isEqual } from 'es-toolkit/predicate'
+
import {
fitEnclosingGroups,
FITTED_CONTAINER_TYPES,
@@ -56,6 +58,7 @@ export function prepareFollowedFieldEdit(
| 'mask-type'
| 'vector-data'
| 'handle-mirroring'
+ | 'stack-counter-align-content'
): void {
if (!node.parentId) return
const scope = slotScope(scene, node.parentId)
@@ -110,8 +113,13 @@ export function updateNode(
if (Object.keys(applied).length === 0) return
// Auto-sizing text measures its new content, as the editor's updates do.
Object.assign(applied, textAutoResizeChanges(g.getNode(id), applied))
+ const before = g.getNode(id)
+ // Figma overrides only what an edit changes, so setting a layer's own value claims nothing.
+ const changed = Object.keys(applied).filter(
+ (key) => !before || !isEqual(Reflect.get(applied, key), Reflect.get(before, key))
+ )
g.updateNode(id, applied)
- recordInstanceOverride(g, id, Object.keys(applied))
+ recordInstanceOverride(g, id, changed)
if (Object.keys(applied).some((key) => GEOMETRY_FIELDS.has(key))) {
fitGroupsAround(g, g.getNode(id)?.parentId, hostFitOptions(target, internals))
}
diff --git a/packages/core/src/figma-api/accessors/basic.ts b/packages/core/src/figma-api/accessors/basic.ts
index 445d8d6a6..0d670d579 100644
--- a/packages/core/src/figma-api/accessors/basic.ts
+++ b/packages/core/src/figma-api/accessors/basic.ts
@@ -1,3 +1,5 @@
+import { pickBy } from 'es-toolkit'
+
import {
getAxisAlignedWorldBounds,
getWorldMatrix,
@@ -289,10 +291,19 @@ function resizeNode(
(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)
+ // Auto layout given a size keeps it, as in Figma: hugging axes become fixed.
+ const fixed = node.layoutMode === 'HORIZONTAL' || node.layoutMode === 'VERTICAL'
+ const sizing = fixed
+ ? pickBy(
+ { primaryAxisSizing: 'FIXED' as const, counterAxisSizing: 'FIXED' as const },
+ (value, key) => node[key] !== value
+ )
+ : {}
scene.updateNode(node.id, {
width,
height,
...recaptured,
+ ...sizing,
...(fixesText ? { textAutoResize: 'NONE' as const } : {})
})
if (placed.size > 0 && size.width > 0 && size.height > 0) {
@@ -303,6 +314,7 @@ function resizeNode(
'width',
'height',
...Object.keys(recaptured),
+ ...Object.keys(sizing),
...(fixesText ? ['textAutoResize'] : [])
])
setTransform(target, internals, () => before)
diff --git a/packages/core/src/figma-api/accessors/layout.ts b/packages/core/src/figma-api/accessors/layout.ts
index 71d839abc..6ba555e39 100644
--- a/packages/core/src/figma-api/accessors/layout.ts
+++ b/packages/core/src/figma-api/accessors/layout.ts
@@ -53,7 +53,19 @@ export function installLayoutNodeProxyAccessors(
internals: NodeProxyInternals
): void {
Object.defineProperties(prototype, {
- layoutMode: simpleAccessor(internals, 'layoutMode'),
+ layoutMode: {
+ get(this: ProxyThis): LayoutMode {
+ return raw(this, internals).layoutMode
+ },
+ set(this: ProxyThis, value: LayoutMode) {
+ // A grid sizes to its tracks, so Figma fixes both axes; a flow keeps the sizing it had.
+ const sizing =
+ value === 'GRID'
+ ? { primaryAxisSizing: 'FIXED' as const, counterAxisSizing: 'FIXED' as const }
+ : {}
+ updateNode(this, internals, { layoutMode: value, ...sizing })
+ }
+ },
// Figma's grids, as a frame's Layout guide section shows them.
layoutGrids: {
get(this: ProxyThis): readonly LayoutGrid[] {
@@ -88,7 +100,20 @@ export function installLayoutNodeProxyAccessors(
layoutWrap: mappedAccessor(internals, 'layoutWrap'),
primaryAxisSizingMode: axisSizingModeAccessor(internals, 'primaryAxisSizing'),
counterAxisSizingMode: axisSizingModeAccessor(internals, 'counterAxisSizing'),
- counterAxisAlignContent: mappedAccessor(internals, 'counterAxisAlignContent'),
+ counterAxisAlignContent: {
+ get(this: ProxyThis): SceneNode['counterAxisAlignContent'] {
+ return raw(this, internals).counterAxisAlignContent
+ },
+ set(this: ProxyThis, value: SceneNode['counterAxisAlignContent']) {
+ prepareFollowedFieldEdit(
+ graph(this, internals),
+ raw(this, internals),
+ 'counterAxisAlignContent',
+ 'stack-counter-align-content'
+ )
+ updateNode(this, internals, { counterAxisAlignContent: value })
+ }
+ },
itemReverseZIndex: simpleAccessor(internals, 'itemReverseZIndex'),
strokesIncludedInLayout: simpleAccessor(internals, 'strokesIncludedInLayout'),
layoutPositioning: mappedAccessor(internals, 'layoutPositioning'),
diff --git a/packages/core/src/figma-api/index.ts b/packages/core/src/figma-api/index.ts
index 009fcc07a..36bc4dd99 100644
--- a/packages/core/src/figma-api/index.ts
+++ b/packages/core/src/figma-api/index.ts
@@ -173,9 +173,10 @@ export class FigmaAPI implements NodeProxyHost {
/** New layers start as the editor's tools make them, which is how Figma's plugin API makes them. */
private _createNode(type: NodeType): FigmaNodeProxy {
const defaults = newLayerDefaults(type, this.theme)
- // Figma's plugin API makes a line 100 wide with no height, and a section 496 square.
+ // Figma's plugin API makes a line with no height, a 496 px section, and a hugging frame.
if (type === 'LINE') defaults.height = 0
if (type === 'SECTION') Object.assign(defaults, { width: 496, height: 496 })
+ if (type === 'FRAME' || type === 'COMPONENT') defaults.primaryAxisSizing = 'HUG'
const node = this.graph.createNode(type, this._currentPageId, defaults)
return this.wrapNode(node.id)
}
diff --git a/packages/core/src/figma-api/overrides.ts b/packages/core/src/figma-api/overrides.ts
new file mode 100644
index 000000000..0129fce92
--- /dev/null
+++ b/packages/core/src/figma-api/overrides.ts
@@ -0,0 +1,265 @@
+import { omit, uniq } from 'es-toolkit'
+import { isEqual } from 'es-toolkit/predicate'
+
+import {
+ findInstanceAncestor,
+ type ComponentPropertyReferenceField,
+ type InstanceOverrideState,
+ type SceneGraph,
+ type SceneNode,
+ type Stroke
+} from '@open-pencil/scene-graph'
+
+import type { NodeProxyInternals, ProxyThis } from './accessor-utils'
+import { assertProxyEditable, graph, raw } from './accessor-utils'
+import { flushPendingLayout } from './pending-layout'
+
+/** One layer of an instance and the fields an edit changed on it, as Figma's `overrides`. */
+export interface FigmaInstanceOverride {
+ id: string
+ overriddenFields: string[]
+}
+
+/**
+ * The fields Figma desktop 126 lists for an override of each of ours. Unlisted fields are ones
+ * Figma does not report: a layer's own size, size limits, clipping, the layout mode, a swap.
+ * Figma spells the top stroke weight `stokeTopWeight`.
+ */
+const FIGMA_OVERRIDE_FIELDS: Readonly<Partial<Record<string, readonly string[]>>> = {
+ // Figma keeps a size as one field, so a changed width or height lists both.
+ width: ['height', 'width'],
+ height: ['height', 'width'],
+ name: ['name'],
+ visible: ['visible'],
+ locked: ['locked'],
+ text: ['characters', 'styledTextSegments'],
+ styleRuns: ['styledTextSegments'],
+ textParagraphs: ['styledTextSegments'],
+ listSpacing: ['styledTextSegments'],
+ fontSize: ['fontSize'],
+ fontFamily: ['fontName'],
+ fontWeight: ['fontName'],
+ italic: ['fontName'],
+ letterSpacing: ['letterSpacing'],
+ lineHeight: ['lineHeight'],
+ textCase: ['textCase'],
+ textDecoration: ['textDecoration'],
+ textDecorationStyle: ['textDecorationStyle'],
+ textDecorationThickness: ['textDecorationThickness'],
+ textUnderlineOffset: ['textDecorationOffset'],
+ textDecorationFills: ['textDecorationColor'],
+ textDecorationSkipInk: ['textDecorationSkipInk'],
+ textAlignHorizontal: ['textAlignHorizontal'],
+ textAlignVertical: ['textAlignVertical'],
+ textAutoResize: ['textAutoResize'],
+ textTruncation: ['textTruncation'],
+ maxLines: ['maxLines'],
+ leadingTrim: ['leadingTrim'],
+ paragraphSpacing: ['paragraphSpacing'],
+ paragraphIndent: ['paragraphIndent'],
+ hangingList: ['hangingList'],
+ fills: ['fills'],
+ strokes: ['strokes'],
+ effects: ['effects'],
+ opacity: ['opacity'],
+ blendMode: ['blendMode'],
+ cornerRadius: [
+ 'bottomLeftRadius',
+ 'bottomRightRadius',
+ 'cornerRadius',
+ 'topLeftRadius',
+ 'topRightRadius'
+ ],
+ topLeftRadius: ['topLeftRadius'],
+ topRightRadius: ['topRightRadius'],
+ bottomRightRadius: ['bottomRightRadius'],
+ bottomLeftRadius: ['bottomLeftRadius'],
+ cornerSmoothing: ['cornerSmoothing'],
+ strokeWeight: [
+ 'strokeBottomWeight',
+ 'strokeLeftWeight',
+ 'strokeRightWeight',
+ 'stokeTopWeight',
+ 'strokeWeight'
+ ],
+ borderTopWeight: ['stokeTopWeight'],
+ borderRightWeight: ['strokeRightWeight'],
+ borderBottomWeight: ['strokeBottomWeight'],
+ borderLeftWeight: ['strokeLeftWeight'],
+ strokeAlign: ['strokeAlign'],
+ strokeCap: ['strokeCap'],
+ strokeJoin: ['strokeJoin'],
+ strokeMiterLimit: ['strokeMiterLimit'],
+ dashPattern: ['dashPattern'],
+ layoutWrap: ['layoutWrap'],
+ primaryAxisAlign: ['primaryAxisAlignItems'],
+ counterAxisAlign: ['counterAxisAlignItems'],
+ primaryAxisSizing: ['primaryAxisSizingMode'],
+ counterAxisSizing: ['counterAxisSizingMode'],
+ itemSpacing: ['itemSpacing'],
+ counterAxisSpacing: ['counterAxisSpacing'],
+ paddingTop: ['paddingTop'],
+ paddingRight: ['paddingRight'],
+ paddingBottom: ['paddingBottom'],
+ paddingLeft: ['paddingLeft'],
+ gridColumnGap: ['gridColumnGap'],
+ gridRowGap: ['gridRowGap'],
+ itemReverseZIndex: ['itemReverseZIndex'],
+ layoutGrids: ['layoutGrids'],
+ layoutGrow: ['layoutGrow'],
+ layoutAlignSelf: ['layoutAlign'],
+ boundVariables: ['boundVariables'],
+ variableModes: ['explicitVariableModes'],
+ fillStyleId: ['fillStyleId'],
+ strokeStyleId: ['strokeStyleId'],
+ textStyleId: ['textStyleId'],
+ effectStyleId: ['effectStyleId'],
+ gridStyleId: ['gridStyleId']
+}
+
+/** Fields a component property sets on a layer, which Figma reports as the property's, not an override. */
+const PROPERTY_FIELDS: Record<ComponentPropertyReferenceField, readonly string[]> = {
+ TEXT: ['text', 'styleRuns', 'textParagraphs'],
+ VISIBLE: ['visible'],
+ INSTANCE_SWAP: ['componentId', 'name'],
+ SLOT_CONTENT: []
+}
+
+function propertyFields(node: SceneNode): Set<string> {
+ return new Set(node.componentPropertyReferences.flatMap(({ field }) => PROPERTY_FIELDS[field]))
+}
+
+/** Figma sorts the names as spelled right, so its misspelled top weight sorts as `strokeTop…`. */
+const sortKey = (name: string) => (name === 'stokeTopWeight' ? 'strokeTopWeight' : name)
+
+function figmaFields(fields: Iterable<string>, skipped: Set<string>): string[] {
+ const names = new Set<string>()
+ for (const field of fields) {
+ if (skipped.has(field)) continue
+ for (const name of FIGMA_OVERRIDE_FIELDS[field] ?? []) names.add(name)
+ }
+ return [...names].sort((a, b) => sortKey(a).localeCompare(sortKey(b)))
+}
+
+/**
+ * The layer of the component a node copies, which its overrides are measured against. A nested
+ * instance links to the component's instance it copies, until a swap points it at a component;
+ * the enclosing instance then keeps the layer it copied.
+ */
+function componentLayer(graph: SceneGraph, node: SceneNode, owner: SceneNode | undefined) {
+ const linked = node.componentId ? graph.getNode(node.componentId) : undefined
+ if (node.type !== 'INSTANCE' || linked?.type === 'INSTANCE') return linked
+ const source = owner?.instanceOverrides.descendants.get(node.id)?.get('sourceComponentId')
+ return typeof source === 'string' ? graph.getNode(source) : undefined
+}
+
+/** Figma keeps stroke weight and alignment on the layer, so a paint differs by its colour alone. */
+const paints = (strokes: readonly Stroke[]) =>
+ strokes.map((stroke) => omit(stroke, ['weight', 'align']))
+
+function differs(node: SceneNode, source: SceneNode | undefined, field: string): boolean {
+ if (!source) return true
+ if (field === 'strokes') return !isEqual(paints(node.strokes), paints(source.strokes))
+ return !isEqual(Reflect.get(node, field), Reflect.get(source, field))
+}
+
+/**
+ * The fields recorded as edited on a node that still differ from its component layer: an edit
+ * kept in the nearest instance above it, and one kept on the node itself if it is an instance.
+ * Figma lists a field as overridden only while it differs.
+ */
+function editedFields(graph: SceneGraph, node: SceneNode, root: SceneNode): string[] {
+ const owner =
+ node.id === root.id || !node.parentId ? undefined : findInstanceAncestor(graph, node.parentId)
+ const source =
+ node.id === root.id ? graph.getNode(root.componentId ?? '') : componentLayer(graph, node, owner)
+ const fields = [
+ ...(node.type === 'INSTANCE' ? node.instanceOverrides.self.keys() : []),
+ ...(owner?.instanceOverrides.descendants.get(node.id)?.keys() ?? [])
+ ]
+ // The instance's own size counts once it differs, as a layer that grows it makes it.
+ if (node.id === root.id) fields.push('width', 'height')
+ return uniq(fields).filter((field) => differs(node, source, field))
+}
+
+/**
+ * Figma's `overrides`: each layer of the instance, itself first and then in layer order, with
+ * the fields edited on it, including those inside nested instances. Figma lists no layer's own
+ * size but the instance's.
+ */
+export function instanceOverrides(graph: SceneGraph, root: SceneNode): FigmaInstanceOverride[] {
+ const result: FigmaInstanceOverride[] = []
+ const visit = (node: SceneNode) => {
+ const skipped = propertyFields(node)
+ if (node.id !== root.id) skipped.add('width').add('height')
+ const overriddenFields = figmaFields(editedFields(graph, node, root), skipped)
+ if (overriddenFields.length > 0) result.push({ id: node.id, overriddenFields })
+ for (const child of graph.getChildren(node.id)) visit(child)
+ }
+ visit(root)
+ return result
+}
+
+/** Clears an override state but what component properties set, which Figma keeps on reset. */
+function withoutEdits(graph: SceneGraph, state: InstanceOverrideState): InstanceOverrideState {
+ const keep = (nodeId: string, fields: Map<string, unknown>) => {
+ const node = graph.getNode(nodeId)
+ const driven = node ? propertyFields(node) : new Set<string>()
+ return new Map([...fields].filter(([field]) => driven.has(field)))
+ }
+ const descendants = new Map(
+ [...state.descendants]
+ .map(([nodeId, fields]) => [nodeId, keep(nodeId, fields)] as const)
+ .filter(([, fields]) => fields.size > 0)
+ )
+ return { self: new Map(), descendants }
+}
+
+/**
+ * Figma's `resetOverrides`: the instance and every instance inside it go back to their
+ * components, keeping the values their component properties set.
+ */
+function resetInstanceOverrides(graph: SceneGraph, root: SceneNode): void {
+ const visit = (node: SceneNode) => {
+ if (node.type === 'INSTANCE')
+ graph.updateNode(node.id, { instanceOverrides: withoutEdits(graph, node.instanceOverrides) })
+ for (const child of graph.getChildren(node.id)) visit(child)
+ }
+ visit(root)
+ // The outermost instance passes its component's content down to the ones inside it.
+ let outermost = root
+ for (
+ let parent = root.parentId ? findInstanceAncestor(graph, root.parentId) : undefined;
+ parent;
+ ) {
+ outermost = parent
+ parent = parent.parentId ? findInstanceAncestor(graph, parent.parentId) : undefined
+ }
+ graph.syncInstance(outermost.id)
+}
+
+export function installInstanceOverrideAccessors(
+ prototype: object,
+ internals: NodeProxyInternals
+): void {
+ Object.defineProperties(prototype, {
+ overrides: {
+ get(this: ProxyThis): FigmaInstanceOverride[] | undefined {
+ const node = raw(this, internals)
+ if (node.type !== 'INSTANCE') return undefined
+ // Figma lists the size its layout gives the instance.
+ flushPendingLayout(graph(this, internals))
+ return instanceOverrides(graph(this, internals), node)
+ }
+ },
+ resetOverrides: {
+ value(this: ProxyThis) {
+ const node = raw(this, internals)
+ if (node.type !== 'INSTANCE')
+ throw new TypeError('resetOverrides() can only be called on instances')
+ assertProxyEditable(this, internals)
+ resetInstanceOverrides(graph(this, internals), node)
+ }
+ }
+ })
+}
diff --git a/packages/core/src/figma-api/proxy.ts b/packages/core/src/figma-api/proxy.ts
index 5c2bd5639..d05943825 100644
--- a/packages/core/src/figma-api/proxy.ts
+++ b/packages/core/src/figma-api/proxy.ts
@@ -46,6 +46,7 @@ import {
import { installComponentPropertyAccessors } from './components'
import type { FigmaFontName } from './fonts'
import type { FigmaFrameNode, FigmaInstanceNode } from './node-types'
+import { installInstanceOverrideAccessors, type FigmaInstanceOverride } from './overrides'
import { getPageBackgrounds, setPageBackgrounds } from './page-backgrounds'
import * as PluginData from './plugin-data'
import { nodeProxyToJSON } from './serialization'
@@ -160,6 +161,8 @@ export class FigmaNodeProxy {
declare handleMirroring: SceneNode['handleMirroring'] | typeof MIXED
declare readonly explicitVariableModes: Readonly<Record<string, string>>
declare readonly resolvedVariableModes: Readonly<Record<string, string>>
+ declare readonly overrides: FigmaInstanceOverride[] | undefined
+ declare resetOverrides: () => void
declare strokeWeight: number
declare strokeAlign: string
@@ -572,4 +575,5 @@ installTextRangeMethods(FigmaNodeProxy.prototype, proxyInternals, MIXED)
installLayoutNodeProxyAccessors(FigmaNodeProxy.prototype, proxyInternals)
installVariableModeNodeProxyAccessors(FigmaNodeProxy.prototype, proxyInternals)
installComponentPropertyAccessors(FigmaNodeProxy.prototype, proxyInternals)
+installInstanceOverrideAccessors(FigmaNodeProxy.prototype, proxyInternals)
installSlotAccessors(FigmaNodeProxy.prototype, proxyInternals)
diff --git a/packages/core/tests/editor/structure/layer-type.test.ts b/packages/core/tests/editor/structure/layer-type.test.ts
index e0c7a1fc4..a49684b72 100644
--- a/packages/core/tests/editor/structure/layer-type.test.ts
+++ b/packages/core/tests/editor/structure/layer-type.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import { createEditor } from '@open-pencil/core/editor'
+import { createEditor, layerTypeOptions } 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.
@@ -133,4 +133,105 @@ describe('layer type menu', () => {
editor.convertLayerType(frame.id, 'GROUP')
expect(editor.graph.getNode(frame.id)?.type).toBe('FRAME')
})
+
+ test('a frame on the page becomes a section that keeps its look but what a section lacks', () => {
+ const { editor, frame, dot } = setup()
+ editor.graph.updateNode(frame.id, {
+ strokes: [{ ...frame.strokes[0], weight: 2 }],
+ strokeWeight: 2
+ })
+ const dotBefore = canvasBox(editor, dot.id)
+ editor.convertLayerType(frame.id, 'SECTION')
+ expect(editor.graph.getNode(frame.id)).toMatchObject({
+ type: 'SECTION',
+ cornerRadius: 8,
+ opacity: 1,
+ effects: [],
+ clipsContent: false,
+ strokeWeight: 1
+ })
+ expect(editor.graph.getNode(frame.id)?.fills).toHaveLength(1)
+ expect(editor.graph.getNode(frame.id)?.strokes.map((stroke) => stroke.weight)).toEqual([1])
+ expect(canvasBox(editor, frame.id)).toEqual([9000, 100, 200, 150])
+ expect(canvasBox(editor, dot.id)).toEqual(dotBefore)
+
+ editor.undo.undo()
+ expect(editor.graph.getNode(frame.id)).toMatchObject({
+ type: 'FRAME',
+ opacity: 0.8,
+ clipsContent: true,
+ strokeWeight: 2
+ })
+ expect(editor.graph.getNode(frame.id)?.effects).toHaveLength(1)
+
+ editor.undo.redo()
+ editor.convertLayerType(frame.id, 'FRAME')
+ expect(editor.graph.getNode(frame.id)).toMatchObject({
+ type: 'FRAME',
+ clipsContent: true,
+ cornerRadius: 8,
+ opacity: 1
+ })
+ expect(editor.graph.getNode(frame.id)?.fills).toHaveLength(1)
+ })
+
+ test('an auto layout frame becomes a section with its layers where layout put them', () => {
+ const editor = createEditor()
+ const frame = editor.graph.createNode('FRAME', editor.state.currentPageId, {
+ width: 200,
+ height: 100,
+ layoutMode: 'VERTICAL',
+ paddingLeft: 8
+ })
+ const child = editor.graph.createNode('RECTANGLE', frame.id, { width: 100, height: 40 })
+ editor.runLayoutForNode(frame.id)
+ const placed = canvasBox(editor, child.id)
+ editor.convertLayerType(frame.id, 'SECTION')
+ expect(editor.graph.getNode(frame.id)?.layoutMode).toBe('NONE')
+ expect(canvasBox(editor, child.id)).toEqual(placed)
+ })
+
+ test('a group becomes a section of its bounds, with no fill', () => {
+ const { editor, frame, box } = setup()
+ editor.convertLayerType(frame.id, 'GROUP')
+ const boxBefore = canvasBox(editor, box.id)
+ editor.convertLayerType(frame.id, 'SECTION')
+ expect(editor.graph.getNode(frame.id)).toMatchObject({ type: 'SECTION', fills: [], opacity: 1 })
+ expect(canvasBox(editor, frame.id)).toEqual([9020, 130, 220, 150])
+ expect(canvasBox(editor, box.id)).toEqual(boxBefore)
+ })
+
+ test('offers a section on the page or in a section, a group of layers, and no group of a section', () => {
+ const editor = createEditor()
+ const page = editor.state.currentPageId
+ const section = editor.graph.createNode('SECTION', page, { width: 400, height: 300 })
+ const inSection = editor.graph.createNode('FRAME', section.id, { width: 100, height: 80 })
+ const outer = editor.graph.createNode('FRAME', page, { width: 300, height: 250 })
+ const nested = editor.graph.createNode('FRAME', outer.id, { width: 100, height: 80 })
+ editor.graph.createNode('RECTANGLE', section.id, { width: 10, height: 10 })
+ const options = (id: string) => {
+ const node = editor.graph.getNode(id)
+ if (!node) throw new Error(`Missing ${id}`)
+ return layerTypeOptions(editor.graph, node)
+ }
+ expect(options(inSection.id)).toEqual({ FRAME: true, GROUP: false, SECTION: true })
+ expect(options(nested.id)).toEqual({ FRAME: true, GROUP: false, SECTION: false })
+ expect(options(section.id)).toEqual({ FRAME: true, GROUP: false, SECTION: true })
+ editor.convertLayerType(nested.id, 'SECTION')
+ expect(editor.graph.getNode(nested.id)?.type).toBe('FRAME')
+ })
+
+ test('a section holding a section stays one, as a frame cannot hold it', () => {
+ const editor = createEditor()
+ const outer = editor.graph.createNode('SECTION', editor.state.currentPageId, {
+ width: 600,
+ height: 400
+ })
+ editor.graph.createNode('SECTION', outer.id, { width: 200, height: 150 })
+ const node = editor.graph.getNode(outer.id)
+ if (!node) throw new Error('Missing section')
+ expect(layerTypeOptions(editor.graph, node).FRAME).toBe(false)
+ editor.convertLayerType(outer.id, 'FRAME')
+ expect(editor.graph.getNode(outer.id)?.type).toBe('SECTION')
+ })
})
diff --git a/packages/core/tests/figma-api/instance-overrides.test.ts b/packages/core/tests/figma-api/instance-overrides.test.ts
index ddf9eaf99..cdb448125 100644
--- a/packages/core/tests/figma-api/instance-overrides.test.ts
+++ b/packages/core/tests/figma-api/instance-overrides.test.ts
@@ -41,6 +41,9 @@ test('a layer inside an instance refuses the fields it always takes from its com
)
expect(() => (layer.isMask = true)).toThrow(refused('isMask', 'is-mask'))
expect(() => (layer.maskType = 'LUMINANCE')).toThrow(refused('maskType', 'mask-type'))
+ expect(() => (layer.counterAxisAlignContent = 'SPACE_BETWEEN')).toThrow(
+ refused('counterAxisAlignContent', 'stack-counter-align-content')
+ )
})
test('a vector inside an instance refuses its path and handle mirroring', async () => {
diff --git a/packages/core/tests/figma-api/overrides.test.ts b/packages/core/tests/figma-api/overrides.test.ts
new file mode 100644
index 000000000..c404bf1db
--- /dev/null
+++ b/packages/core/tests/figma-api/overrides.test.ts
@@ -0,0 +1,149 @@
+import { describe, expect, test } from 'bun:test'
+
+import { FigmaAPI, type FigmaNodeProxy } from '@open-pencil/core/figma-api'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+// Each case repeats a script run in Figma desktop 126; the lists are what Figma returned.
+
+const solid = (r: number, g: number, b: number) => ({
+ type: 'SOLID' as const,
+ color: { r, g, b, a: 1 },
+ opacity: 1,
+ visible: true
+})
+
+function setup() {
+ const figma = new FigmaAPI(new SceneGraph())
+ const icon = figma.createComponent()
+ icon.name = 'Icon'
+ icon.resize(16, 16)
+ const dot = figma.createEllipse()
+ dot.name = 'Dot'
+ dot.resize(16, 16)
+ icon.appendChild(dot)
+ const card = figma.createComponent()
+ card.name = 'Card'
+ card.resize(200, 120)
+ card.layoutMode = 'VERTICAL'
+ const label = figma.createText()
+ label.name = 'Label'
+ label.characters = 'Hello'
+ card.appendChild(label)
+ const box = figma.createRectangle()
+ box.name = 'Box'
+ box.resize(50, 20)
+ box.fills = [solid(1, 0, 0)]
+ card.appendChild(box)
+ const row = figma.createFrame()
+ row.name = 'Row'
+ row.layoutMode = 'HORIZONTAL'
+ row.resize(100, 30)
+ card.appendChild(row)
+ const nested = icon.createInstance()
+ nested.name = 'Nested'
+ row.appendChild(nested)
+ const show = card.addComponentProperty('Show', 'BOOLEAN', true)
+ box.componentPropertyReferences = { visible: show }
+ const instance = card.createInstance()
+ const find = (name: string) => {
+ const found = instance.findOne((node: FigmaNodeProxy) => node.name === name)
+ if (!found) throw new Error(`Missing ${name}`)
+ return found
+ }
+ // Names each entry by its layer, as the Figma script printed them.
+ const overrides = () =>
+ (instance.overrides ?? []).map((entry) => {
+ const layer =
+ entry.id === instance.id
+ ? 'SELF'
+ : instance.findOne((node: FigmaNodeProxy) => node.id === entry.id)?.name
+ return `${layer}: ${entry.overriddenFields.join(',')}`
+ })
+ return { figma, card, instance, find, overrides, show }
+}
+
+describe('instance.overrides', () => {
+ test('an untouched instance and its component have none to list', () => {
+ const { card, overrides } = setup()
+ expect(overrides()).toEqual([])
+ expect(card.overrides).toBeUndefined()
+ })
+
+ test('lists each edited layer once, under Figma’s field names', () => {
+ const { find, overrides } = setup()
+ find('Box').fills = [solid(0, 1, 0)]
+ find('Box').strokeWeight = 3
+ find('Box').cornerRadius = 4
+ find('Row').primaryAxisAlignItems = 'CENTER'
+ find('Row').itemSpacing = 7
+ expect(overrides()).toEqual([
+ 'Box: bottomLeftRadius,bottomRightRadius,cornerRadius,fills,strokeBottomWeight,strokeLeftWeight,strokeRightWeight,stokeTopWeight,strokeWeight,topLeftRadius,topRightRadius',
+ 'Row: itemSpacing,primaryAxisAlignItems'
+ ])
+ })
+
+ test('lists the instance’s own size once its layers grow it, and a nested instance’s layers', () => {
+ const { find, overrides } = setup()
+ find('Label').fontSize = 30
+ find('Dot').fills = [solid(0, 0, 1)]
+ find('Nested').opacity = 0.5
+ expect(overrides()).toEqual([
+ 'SELF: height,width',
+ 'Label: fontSize',
+ 'Nested: opacity',
+ 'Dot: fills'
+ ])
+ expect(find('Nested').overrides?.map((entry) => entry.overriddenFields)).toEqual([
+ ['opacity'],
+ ['fills']
+ ])
+ })
+
+ test('leaves out a value set to what the layer has and a property’s value, but not the size it gives', () => {
+ const { instance, find, overrides, show } = setup()
+ find('Label').characters = 'Hello'
+ find('Box').fills = [solid(1, 0, 0)]
+ expect(overrides()).toEqual([])
+ // The hidden box shrinks the hugging instance.
+ instance.setProperties({ [show]: false })
+ expect(overrides()).toEqual(['SELF: height,width'])
+ })
+})
+
+describe('instance.resetOverrides', () => {
+ test('returns the instance and the ones inside it to their components', () => {
+ const { card, instance, find, overrides } = setup()
+ find('Dot').fills = [solid(0, 0, 1)]
+ find('Label').fontSize = 30
+ find('Nested').opacity = 0.5
+ instance.resize(260, 160)
+ instance.resetOverrides()
+ expect(overrides()).toEqual([])
+ expect([instance.width, instance.height]).toEqual([card.width, card.height])
+ expect([find('Label').fontSize, find('Nested').opacity]).toEqual([12, 1])
+ const componentDot = card.findOne((node: FigmaNodeProxy) => node.name === 'Dot')
+ expect(find('Dot').fills).toEqual(componentDot?.fills ?? [])
+ })
+
+ test('keeps the values component properties set, and the size they give', () => {
+ const { instance, find, overrides, show } = setup()
+ instance.setProperties({ [show]: false })
+ find('Label').fontSize = 30
+ instance.resetOverrides()
+ expect([find('Box').visible, find('Label').fontSize]).toEqual([false, 12])
+ expect(overrides()).toEqual(['SELF: height,width'])
+ })
+
+ test('on a nested instance resets only what is inside it', () => {
+ const { find, overrides } = setup()
+ find('Dot').fills = [solid(0, 0, 1)]
+ find('Label').fontSize = 30
+ find('Nested').resetOverrides()
+ expect(overrides()).toEqual(['SELF: height,width', 'Label: fontSize'])
+ })
+
+ test('is an instance’s alone', () => {
+ const { card } = setup()
+ expect(() => card.resetOverrides()).toThrow('resetOverrides() can only be called on instances')
+ })
+})
diff --git a/packages/core/tests/io/formats/fig/export/filled-sizing-export.test.ts b/packages/core/tests/io/formats/fig/export/filled-sizing-export.test.ts
index 0d6bd7c66..f901f2f56 100644
--- a/packages/core/tests/io/formats/fig/export/filled-sizing-export.test.ts
+++ b/packages/core/tests/io/formats/fig/export/filled-sizing-export.test.ts
@@ -60,11 +60,11 @@ describe('own sizing of frames that fill their parent', () => {
const change = await exported(graph)
expect(change('Title row')).toMatchObject({
stackPrimarySizing: 'FIXED',
- stackCounterSizing: 'RESIZE_TO_FIT',
+ stackCounterSizing: 'RESIZE_TO_FIT_WITH_IMPLICIT_SIZE',
stackChildAlignSelf: 'STRETCH'
})
expect(change('Column')).toMatchObject({
- stackPrimarySizing: 'RESIZE_TO_FIT',
+ stackPrimarySizing: 'RESIZE_TO_FIT_WITH_IMPLICIT_SIZE',
stackCounterSizing: 'FIXED',
stackChildPrimaryGrow: 1
})
diff --git a/packages/fig/src/node-change/serialize.ts b/packages/fig/src/node-change/serialize.ts
index a614eeafa..51d3f71b2 100644
--- a/packages/fig/src/node-change/serialize.ts
+++ b/packages/fig/src/node-change/serialize.ts
@@ -230,8 +230,13 @@ function serializeSizeConstraints(node: SceneNode, nc: KiwiNodeChange): void {
}
}
+/**
+ * Hug as Figma desktop 126 writes it for its own frames, which counts the children stretched
+ * across the frame; the older `RESIZE_TO_FIT` leaves them out, so a row hugging a stretched
+ * column shrank to its other layers when pasted into Figma.
+ */
function exportSizing(value: SceneNode['primaryAxisSizing']) {
- return value === 'HUG' ? 'RESIZE_TO_FIT' : 'FIXED'
+ return value === 'HUG' ? 'RESIZE_TO_FIT_WITH_IMPLICIT_SIZE' : 'FIXED'
}
/** Layout fields whose edits decide whether a frame's own sizing still matches its fill. */
diff --git a/packages/scene-graph/src/instances/content-size.ts b/packages/scene-graph/src/instances/content-size.ts
index 4f45cffbc..ddce6697e 100644
--- a/packages/scene-graph/src/instances/content-size.ts
+++ b/packages/scene-graph/src/instances/content-size.ts
@@ -1,5 +1,7 @@
+import { isEqual } from 'es-toolkit/predicate'
+
import type { SceneGraph, SceneNode } from '../'
-import { TEXT_METRIC_FIELDS } from '../fields/text'
+import { TEXT_METRIC_FIELDS, TEXT_SHAPING_FIELDS } from '../fields/text'
import { layoutSizing } from '../layout/sizing'
const METRIC_FIELDS: ReadonlySet<string> = new Set(TEXT_METRIC_FIELDS)
@@ -15,21 +17,24 @@ function contentSizedAxes(
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.
+ // Text measures its own characters and their style, set on the copy or by a property of an
+ // instance around it; a copy styled as its component takes the component's measure.
if (copy.type === 'TEXT') {
- if (copy.text === source.text) return { width: false, height: false }
+ if (TEXT_SHAPING_FIELDS.every((field) => isEqual(copy[field], source[field])))
+ 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'
+ // Auto layout hugs the copy's own layers, which may show or size differently, and a layer
+ // that fills its parent takes the size layout gives it there.
+ const laidOut = (axis: 'HORIZONTAL' | 'VERTICAL') => {
+ const sizing = layoutSizing(graph, copy, axis)
+ return sizing === 'FILL' || (sizing === 'HUG' && copy.layoutMode !== 'NONE')
}
+ return { width: laidOut('HORIZONTAL'), height: laidOut('VERTICAL') }
}
/**
diff --git a/packages/scene-graph/src/instances/fields.ts b/packages/scene-graph/src/instances/fields.ts
index 6215618eb..484947188 100644
--- a/packages/scene-graph/src/instances/fields.ts
+++ b/packages/scene-graph/src/instances/fields.ts
@@ -77,7 +77,6 @@ export const INSTANCE_SYNC_PROPS: (keyof SceneNode)[] = [
'gridRowGap',
'gridPosition',
'clipsContent',
- 'counterAxisAlignContent',
'itemReverseZIndex',
'strokesIncludedInLayout',
'layoutGrids',
@@ -121,6 +120,7 @@ export const INSTANCE_FOLLOWED_FIELDS = [
'horizontalConstraint',
'verticalConstraint',
'layoutPositioning',
+ 'counterAxisAlignContent',
'isMask',
'maskType',
'arcData',
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 912f6bfd7..502cddd04 100644
--- a/packages/scene-graph/tests/components/sync-field-contract.test.ts
+++ b/packages/scene-graph/tests/components/sync-field-contract.test.ts
@@ -376,3 +376,56 @@ test('text a property gives a copy when its layer is linked later drops the size
graph.syncInstances(button.id)
expect([copy.text, copy.derivedLayout]).toEqual(['Checkout', null])
})
+
+test('a text copy styled on its own keeps the size it measured, as a badge label in gold-preview', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const badge = graph.createNode('COMPONENT', page, { width: 60, height: 28 })
+ const label = graph.createNode('TEXT', badge.id, {
+ text: 'Badge',
+ fontSize: 12,
+ width: 37,
+ height: 16,
+ textAutoResize: 'WIDTH_AND_HEIGHT'
+ })
+ const instance = expectDefined(graph.createInstance(badge.id, page))
+ const [copy] = graph.getChildren(instance.id)
+ graph.updateNode(copy.id, { fontSize: 14, width: 43, height: 18 })
+ setInstanceOverride(instance.instanceOverrides, instance.id, copy.id, 'fontSize', true)
+
+ graph.updateNode(label.id, { width: 38 })
+ graph.syncInstances(badge.id)
+ expect([copy.fontSize, copy.width, copy.height]).toEqual([14, 43, 18])
+})
+
+test('a copy that fills its parent keeps the size layout gave it', () => {
+ // A stepper's icon column in gold-preview: the component shows a divider under the icon, the
+ // instance hides it, and the column fills the row's height, which hugs its layers.
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const stepper = graph.createNode('COMPONENT', page, {
+ width: 150,
+ height: 44,
+ layoutMode: 'HORIZONTAL',
+ primaryAxisSizing: 'FIXED',
+ counterAxisSizing: 'HUG'
+ })
+ const column = graph.createNode('FRAME', stepper.id, {
+ width: 28,
+ height: 44,
+ layoutMode: 'VERTICAL',
+ layoutAlignSelf: 'STRETCH'
+ })
+ graph.createNode('FRAME', column.id, { width: 28, height: 28 })
+ graph.createNode('RECTANGLE', column.id, { width: 1, height: 11 })
+ const instance = expectDefined(graph.createInstance(stepper.id, page))
+ const [copyColumn] = graph.getChildren(instance.id)
+ const [, copyDivider] = graph.getChildren(copyColumn.id)
+ graph.updateNode(copyDivider.id, { visible: false })
+ setInstanceOverride(instance.instanceOverrides, instance.id, copyDivider.id, 'visible', true)
+ graph.updateNode(copyColumn.id, { height: 28 })
+
+ graph.updateNode(column.id, { itemSpacing: 5 })
+ graph.syncInstances(stepper.id)
+ expect(copyColumn.height).toBe(28)
+})
diff --git a/packages/vue/src/canvas/auto-layout/value-edit.ts b/packages/vue/src/canvas/auto-layout/value-edit.ts
new file mode 100644
index 000000000..754bee03b
--- /dev/null
+++ b/packages/vue/src/canvas/auto-layout/value-edit.ts
@@ -0,0 +1,90 @@
+import { ref } from 'vue'
+
+import type { Editor, NodePreview } from '@open-pencil/core/editor'
+
+import {
+ autoLayoutValueField,
+ resolveAutoLayoutHover,
+ type AutoLayoutValueField
+} from '#vue/shared/input/auto-layout-hover'
+
+/**
+ * A padding or gap value edited on the canvas, as Figma opens one on a double-click: the editor
+ * shows while the edit is open, and the value previews on the frame until it is committed.
+ */
+export function createAutoLayoutValueEdit(editor: Editor) {
+ const autoLayoutValueEdit = ref<{
+ nodeId: string
+ field: AutoLayoutValueField
+ /** The gap a double-click opened the gap's editor on, which it sits over. */
+ gap: number
+ value: number
+ } | null>(null)
+ // The edit's owned preview: undo takes it back in one step, and a selection, page, or
+ // document change cancels it, which closes the editor.
+ let valuePreview: NodePreview | null = null
+ let stopValuePreview: Array<() => void> = []
+
+ function end() {
+ for (const stop of stopValuePreview) stop()
+ stopValuePreview = []
+ valuePreview = null
+ autoLayoutValueEdit.value = null
+ }
+
+ function start(cx: number, cy: number): boolean {
+ const hover = resolveAutoLayoutHover(cx, cy, editor)
+ const field = hover ? autoLayoutValueField(hover) : null
+ const node = hover ? editor.graph.getNode(hover.nodeId) : undefined
+ if (!hover || !field || !node) return false
+ valuePreview = editor.beginNodePreview(
+ field === 'itemSpacing' ? 'Update gap' : 'Update padding'
+ )
+ const close = () => {
+ if (valuePreview?.closed) end()
+ }
+ stopValuePreview = (['selection:changed', 'page:changed', 'graph:replaced'] as const).map(
+ (event) => editor.onEditorEvent(event, close)
+ )
+ // The preview tracks the frame only once a value changes, so its deletion closes the editor here.
+ stopValuePreview.push(
+ editor.onEditorEvent('node:deleted', (id) => {
+ if (id === node.id) valuePreview?.cancel()
+ close()
+ })
+ )
+ autoLayoutValueEdit.value = {
+ nodeId: node.id,
+ field,
+ gap: hover.index ?? 0,
+ value: node[field]
+ }
+ return true
+ }
+
+ function update(value: number) {
+ const edit = autoLayoutValueEdit.value
+ if (!edit || !valuePreview || !Number.isFinite(value)) return
+ const next = Math.max(0, value)
+ autoLayoutValueEdit.value = { ...edit, value: next }
+ valuePreview.update(edit.nodeId, { [edit.field]: next })
+ }
+
+ function commit(value: number) {
+ const edit = autoLayoutValueEdit.value
+ if (edit && valuePreview && Number.isFinite(value)) {
+ valuePreview.update(edit.nodeId, { [edit.field]: Math.max(0, value) })
+ valuePreview.commit()
+ } else {
+ valuePreview?.cancel()
+ }
+ end()
+ }
+
+ function cancel() {
+ valuePreview?.cancel()
+ end()
+ }
+
+ return { edit: autoLayoutValueEdit, start, update, commit, cancel }
+}
diff --git a/packages/vue/src/canvas/useCanvasInput.ts b/packages/vue/src/canvas/useCanvasInput.ts
index ce63e0bb2..e33b1df1a 100644
--- a/packages/vue/src/canvas/useCanvasInput.ts
+++ b/packages/vue/src/canvas/useCanvasInput.ts
@@ -4,6 +4,7 @@ import { onScopeDispose, ref, watch, type Ref } from 'vue'
import type { Editor } from '@open-pencil/core/editor'
import type { SceneNode } from '@open-pencil/scene-graph'
+import { createAutoLayoutValueEdit } from '#vue/canvas/auto-layout/value-edit'
import { createGuideInput, selectedTopLevelGuideFrameId } from '#vue/canvas/guides/input'
import { createCanvasLabelEdit } from '#vue/canvas/labels/edit'
import { handlePenDragMove, updatePenHover } from '#vue/canvas/pen/input'
@@ -56,12 +57,7 @@ export function useCanvasInput(
const canvasLabelEdit = createCanvasLabelEdit(editor)
const cursorOverride = ref<string | null>(null)
/** Whether the primary button is held on a preview control, such as a slider thumb. */
- const autoLayoutPaddingEdit = ref<{
- nodeId: string
- side: 'top' | 'right' | 'bottom' | 'left'
- value: number
- previous: number
- } | null>(null)
+ const valueEdit = createAutoLayoutValueEdit(editor)
const selectedIdsBeforeClickSequence = ref<ReadonlySet<string>>(new Set())
const lastPointer = ref<{ cx: number; cy: number; sx: number; sy: number } | null>(null)
const pointerInside = ref(false)
@@ -168,68 +164,14 @@ export function useCanvasInput(
handleMarqueeMove
} = createCanvasTransformInput(editor, setDrag)
- function paddingValue(node: SceneNode, side: 'top' | 'right' | 'bottom' | 'left') {
- if (side === 'top') return node.paddingTop
- if (side === 'right') return node.paddingRight
- if (side === 'bottom') return node.paddingBottom
- return node.paddingLeft
- }
-
- function paddingKey(side: 'top' | 'right' | 'bottom' | 'left') {
- if (side === 'top') return 'paddingTop' as const
- if (side === 'right') return 'paddingRight' as const
- if (side === 'bottom') return 'paddingBottom' as const
- return 'paddingLeft' as const
- }
-
- function startAutoLayoutPaddingEdit(e: MouseEvent): boolean {
+ function onDblClick(e: MouseEvent) {
+ if (editor.state.play) return
const { cx, cy } = getCoords(e)
- const hover = resolveAutoLayoutHover(cx, cy, editor)
- if (hover?.kind !== 'padding' && hover?.kind !== 'padding-value') return false
- if (!hover.side) return false
- const node = editor.graph.getNode(hover.nodeId)
- if (!node) return false
- const value = paddingValue(node, hover.side)
- autoLayoutPaddingEdit.value = {
- nodeId: node.id,
- side: hover.side,
- value,
- previous: value
- }
- e.preventDefault()
- e.stopPropagation()
- return true
- }
-
- function updateAutoLayoutPaddingEdit(value: number) {
- const edit = autoLayoutPaddingEdit.value
- if (!edit || !Number.isFinite(value)) return
- const next = Math.max(0, value)
- autoLayoutPaddingEdit.value = { ...edit, value: next }
- editor.updateNode(edit.nodeId, { [paddingKey(edit.side)]: next })
- }
-
- function commitAutoLayoutPaddingEdit(value: number) {
- const edit = autoLayoutPaddingEdit.value
- if (!edit || !Number.isFinite(value)) {
- autoLayoutPaddingEdit.value = null
+ if (valueEdit.start(cx, cy)) {
+ e.preventDefault()
+ e.stopPropagation()
return
}
- const next = Math.max(0, value)
- editor.updateNode(edit.nodeId, { [paddingKey(edit.side)]: edit.previous })
- editor.updateNodeWithUndo(edit.nodeId, { [paddingKey(edit.side)]: next }, 'Update padding')
- autoLayoutPaddingEdit.value = null
- }
-
- function cancelAutoLayoutPaddingEdit() {
- const edit = autoLayoutPaddingEdit.value
- if (edit) editor.updateNode(edit.nodeId, { [paddingKey(edit.side)]: edit.previous })
- autoLayoutPaddingEdit.value = null
- }
-
- function onDblClick(e: MouseEvent) {
- if (editor.state.play) return
- if (startAutoLayoutPaddingEdit(e)) return
onTextDblClick(e)
}
@@ -242,10 +184,8 @@ export function useCanvasInput(
return
}
editor.setMeasurementMode('off')
- const paddingEdit = autoLayoutPaddingEdit.value
- if (paddingEdit) {
- commitAutoLayoutPaddingEdit(paddingEdit.value)
- }
+ const openValueEdit = valueEdit.edit.value
+ if (openValueEdit) valueEdit.commit(openValueEdit.value)
if (!editor.state.editingTextId) canvasRef.value?.focus()
editor.setHoveredNode(null)
const { sx, sy, cx, cy } = getCoords(e)
@@ -578,12 +518,12 @@ export function useCanvasInput(
updateCanvasLabelEdit: canvasLabelEdit.update,
commitCanvasLabelEdit: canvasLabelEdit.commit,
cancelCanvasLabelEdit: canvasLabelEdit.cancel,
- autoLayoutPaddingEdit,
- updateAutoLayoutPaddingEdit,
- commitAutoLayoutPaddingEdit,
- cancelAutoLayoutPaddingEdit,
+ autoLayoutValueEdit: valueEdit.edit,
+ updateAutoLayoutValueEdit: valueEdit.update,
+ commitAutoLayoutValueEdit: valueEdit.commit,
+ cancelAutoLayoutValueEdit: valueEdit.cancel,
cleanupInteractions() {
- cancelAutoLayoutPaddingEdit()
+ valueEdit.cancel()
cancelPointerInteraction()
pointerInside.value = false
resetMeasurementModifiers()
diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.ts
index fd60602c4..b46c5799f 100644
--- a/packages/vue/src/index.ts
+++ b/packages/vue/src/index.ts
@@ -23,6 +23,10 @@ export type { PresentationColorSpace } from '#vue/canvas/surface/color-space'
export { useCanvas } from '#vue/canvas/surface/use'
export type { UseCanvasOptions } from '#vue/canvas/surface/use'
export { useCanvasInput } from '#vue/canvas/useCanvasInput'
+export {
+ autoLayoutValueAnchor,
+ type AutoLayoutValueField
+} from '#vue/shared/input/auto-layout-hover'
export { useCanvasIssueMarkers } from '#vue/canvas/issues/use'
export type { CanvasIssueMarkerOptions } from '#vue/canvas/issues/use'
export type { CanvasLabelEdit, CanvasLabelKind } from '#vue/canvas/labels/edit'
diff --git a/packages/vue/src/shared/input/auto-layout-hover.ts b/packages/vue/src/shared/input/auto-layout-hover.ts
index 35e03e36e..361ac8f02 100644
--- a/packages/vue/src/shared/input/auto-layout-hover.ts
+++ b/packages/vue/src/shared/input/auto-layout-hover.ts
@@ -4,7 +4,7 @@ import {
AUTO_LAYOUT_HOVER_TICK_HIT_TOLERANCE
} from '@open-pencil/core/constants'
import type { Editor } from '@open-pencil/core/editor'
-import type { SceneNode } from '@open-pencil/scene-graph'
+import type { SceneNode, Vector } from '@open-pencil/scene-graph'
type AutoLayoutHover = NonNullable<Editor['state']['autoLayoutHover']>
@@ -156,3 +156,59 @@ export function resolveAutoLayoutHover(
resolveChildrenHover(node, children, localX, localY) ?? { nodeId: node.id, kind: 'frame' }
)
}
+
+/** An auto layout frame's value the canvas edits in place: a padding or the gap. */
+export type AutoLayoutValueField =
+ | 'paddingTop'
+ | 'paddingRight'
+ | 'paddingBottom'
+ | 'paddingLeft'
+ | 'itemSpacing'
+
+const PADDING_FIELDS = {
+ top: 'paddingTop',
+ right: 'paddingRight',
+ bottom: 'paddingBottom',
+ left: 'paddingLeft'
+} as const satisfies Record<NonNullable<AutoLayoutHover['side']>, AutoLayoutValueField>
+
+/** The value a hover over a padding or a gap edits, as Figma opens it on a double-click. */
+export function autoLayoutValueField(hover: AutoLayoutHover): AutoLayoutValueField | null {
+ if ((hover.kind === 'padding' || hover.kind === 'padding-value') && hover.side)
+ return PADDING_FIELDS[hover.side]
+ if (hover.kind === 'spacing' || hover.kind === 'spacing-value') return 'itemSpacing'
+ return null
+}
+
+/**
+ * Where the editor for a value sits, in canvas coordinates: the middle of the padding, or of
+ * the gap a double-click opened, as the hover draws its tick.
+ */
+export function autoLayoutValueAnchor(
+ editor: Editor,
+ nodeId: string,
+ field: AutoLayoutValueField,
+ gap = 0
+): Vector | null {
+ const node = editor.graph.getNode(nodeId)
+ if (!node) return null
+ const abs = editor.graph.getAbsolutePosition(node.id)
+ const middle = { x: abs.x + node.width / 2, y: abs.y + node.height / 2 }
+ if (field === 'paddingTop') return { x: middle.x, y: abs.y + node.paddingTop / 2 }
+ if (field === 'paddingBottom')
+ return { x: middle.x, y: abs.y + node.height - node.paddingBottom / 2 }
+ if (field === 'paddingLeft') return { x: abs.x + node.paddingLeft / 2, y: middle.y }
+ if (field === 'paddingRight')
+ return { x: abs.x + node.width - node.paddingRight / 2, y: middle.y }
+ const children = visibleLayoutChildren(node, editor)
+ const prev = children.at(gap)
+ const next = children.at(gap + 1)
+ if (!prev || !next) return middle
+ // Across the flow, the middle of the content box, where the hover draws the gap's tick.
+ if (node.layoutMode === 'HORIZONTAL') {
+ const y = abs.y + (node.paddingTop + node.height - node.paddingBottom) / 2
+ return { x: abs.x + (prev.x + prev.width + next.x) / 2, y }
+ }
+ const x = abs.x + (node.paddingLeft + node.width - node.paddingRight) / 2
+ return { x, y: abs.y + (prev.y + prev.height + next.y) / 2 }
+}
diff --git a/src/app/editor/vector/lifecycle.ts b/src/app/editor/vector/lifecycle.ts
index 2b846f71e..c0dc96d7a 100644
--- a/src/app/editor/vector/lifecycle.ts
+++ b/src/app/editor/vector/lifecycle.ts
@@ -23,6 +23,19 @@ export function createVectorEditLifecycle(editor: Editor, state: VectorEditState
return state.nodeEditState
}
+ // A path whose layer is gone, by undo, a script, or another document, has nothing to edit.
+ const close = () => {
+ state.nodeEditState = null
+ state.snapGuides = []
+ editor.requestRender()
+ }
+ editor.onEditorEvent('node:deleted', (id) => {
+ if (state.nodeEditState?.nodeId === id) close()
+ })
+ editor.onEditorEvent('graph:replaced', () => {
+ if (state.nodeEditState) close()
+ })
+
function commitNodeEditChanges(es: NonNullable<typeof state.nodeEditState>) {
const node = editor.graph.getNode(es.nodeId)
if (node?.type !== 'VECTOR') return
diff --git a/src/components/DesignPanel.vue b/src/components/DesignPanel.vue
index ab965abd6..233029cd2 100644
--- a/src/components/DesignPanel.vue
+++ b/src/components/DesignPanel.vue
@@ -135,7 +135,7 @@ const { panels } = useI18n()
<PanelHeader :component="isComponentType">
<template #icon>
<LayerTypeMenu
- v-if="node.type === 'FRAME' || node.type === 'GROUP'"
+ v-if="node.type === 'FRAME' || node.type === 'GROUP' || node.type === 'SECTION'"
:node="node"
:icon="selectedIcon"
/>
diff --git a/src/components/EditorCanvas.vue b/src/components/EditorCanvas.vue
index 1775be55c..455280755 100644
--- a/src/components/EditorCanvas.vue
+++ b/src/components/EditorCanvas.vue
@@ -8,6 +8,8 @@ import {
PopoverRoot
} from 'reka-ui'
import { computed, onUnmounted, ref, shallowRef, useTemplateRef, watch, type Component } from 'vue'
+import IconLucideAlignHorizontalSpaceBetween from '~icons/lucide/align-horizontal-space-between'
+import IconLucideAlignVerticalSpaceBetween from '~icons/lucide/align-vertical-space-between'
import IconLucidePanelBottom from '~icons/lucide/panel-bottom'
import IconLucidePanelLeft from '~icons/lucide/panel-left'
import IconLucidePanelRight from '~icons/lucide/panel-right'
@@ -23,6 +25,7 @@ import {
} from '@open-pencil/core/constants'
import type { ViewportTransform } from '@open-pencil/core/geometry'
import {
+ autoLayoutValueAnchor,
PlayIslands,
toolCursor,
useCanvas,
@@ -30,7 +33,8 @@ import {
useCanvasInput,
useCanvasIssueMarkers,
useCanvasVirtualReference,
- useTextEdit
+ useTextEdit,
+ type AutoLayoutValueField
} from '@open-pencil/vue'
import { useAIChat } from '@/app/ai/chat/use'
@@ -125,10 +129,10 @@ const {
updateCanvasLabelEdit,
commitCanvasLabelEdit,
cancelCanvasLabelEdit,
- autoLayoutPaddingEdit,
- updateAutoLayoutPaddingEdit,
- commitAutoLayoutPaddingEdit,
- cancelAutoLayoutPaddingEdit,
+ autoLayoutValueEdit,
+ updateAutoLayoutValueEdit,
+ commitAutoLayoutValueEdit,
+ cancelAutoLayoutValueEdit,
cleanupInteractions
} = useCanvasInput(
canvasRef,
@@ -167,12 +171,12 @@ const { detailMarker: hoveredIssueMarker, cursor: issueMarkerCursor } = useCanva
useTextEdit(canvasRef, store, { isEnabled: () => isActivePane.value })
const { isDraggingOver } = useCanvasDrop(canvasRef, store, activatePane)
-const paddingSideIcons = {
- top: IconLucidePanelTop,
- right: IconLucidePanelRight,
- bottom: IconLucidePanelBottom,
- left: IconLucidePanelLeft
-} satisfies Record<'top' | 'right' | 'bottom' | 'left', Component>
+const valueFieldIcons = {
+ paddingTop: IconLucidePanelTop,
+ paddingRight: IconLucidePanelRight,
+ paddingBottom: IconLucidePanelBottom,
+ paddingLeft: IconLucidePanelLeft
+} satisfies Record<Exclude<AutoLayoutValueField, 'itemSpacing'>, Component>
const canvasLabelEditNode = computed(() => {
const edit = canvasLabelEdit.value
@@ -208,23 +212,18 @@ const canvasLabelEditPresentation = computed(() =>
canvasLabelPresentation(store, canvasLabelEditNode.value ?? null, canvasLabelEdit.value?.kind)
)
-const paddingEditorAnchor = computed(() => {
- const edit = autoLayoutPaddingEdit.value
- if (!edit) return null
- const node = store.graph.getNode(edit.nodeId)
- if (!node) return null
- const abs = store.graph.getAbsolutePosition(node.id)
- if (edit.side === 'top') return { x: abs.x + node.width / 2, y: abs.y + node.paddingTop / 2 }
- if (edit.side === 'bottom') {
- return { x: abs.x + node.width / 2, y: abs.y + node.height - node.paddingBottom / 2 }
- }
- if (edit.side === 'left') return { x: abs.x + node.paddingLeft / 2, y: abs.y + node.height / 2 }
- return { x: abs.x + node.width - node.paddingRight / 2, y: abs.y + node.height / 2 }
+const valueEditorAnchor = computed(() => {
+ const edit = autoLayoutValueEdit.value
+ return edit ? autoLayoutValueAnchor(store, edit.nodeId, edit.field, edit.gap) : null
})
-const paddingEditorReference = useCanvasVirtualReference(canvasRef, store, paddingEditorAnchor)
-const paddingEditorIcon = computed(() => {
- const edit = autoLayoutPaddingEdit.value
- return edit ? paddingSideIcons[edit.side] : IconLucidePanelTop
+const valueEditorReference = useCanvasVirtualReference(canvasRef, store, valueEditorAnchor)
+const valueEditorIcon = computed(() => {
+ const edit = autoLayoutValueEdit.value
+ if (!edit) return IconLucidePanelTop
+ if (edit.field !== 'itemSpacing') return valueFieldIcons[edit.field]
+ return store.graph.getNode(edit.nodeId)?.layoutMode === 'VERTICAL'
+ ? IconLucideAlignVerticalSpaceBetween
+ : IconLucideAlignHorizontalSpaceBetween
})
const cursor = computed(() =>
@@ -272,37 +271,37 @@ const cursor = computed(() =>
@commit="commitCanvasLabelEdit"
@cancel="cancelCanvasLabelEdit"
/>
- <PopoverRoot :open="!!autoLayoutPaddingEdit">
+ <PopoverRoot :open="!!autoLayoutValueEdit">
<PopoverPortal>
<PopoverContent
- v-if="autoLayoutPaddingEdit && paddingEditorReference"
- :reference="paddingEditorReference"
+ v-if="autoLayoutValueEdit && valueEditorReference"
+ :reference="valueEditorReference"
side="top"
align="center"
:side-offset="AUTO_LAYOUT_PADDING_EDITOR_OFFSET_Y"
:align-offset="AUTO_LAYOUT_PADDING_EDITOR_OFFSET_X"
:collision-padding="8"
:class="['z-50 w-20 p-1', floatingSurface, motionStyles.floating]"
- data-test-id="auto-layout-padding-editor"
- @keydown.escape.prevent="cancelAutoLayoutPaddingEdit"
+ data-test-id="auto-layout-value-editor"
+ @keydown.escape.prevent="cancelAutoLayoutValueEdit"
@open-auto-focus.prevent
>
<NumberField
- :model-value="autoLayoutPaddingEdit.value"
+ :model-value="autoLayoutValueEdit.value"
:min="0"
:step="1"
- data-test-id="auto-layout-padding-input"
- @update:model-value="updateAutoLayoutPaddingEdit"
- @commit="(value: number) => commitAutoLayoutPaddingEdit(value)"
+ data-test-id="auto-layout-value-input"
+ @update:model-value="updateAutoLayoutValueEdit"
+ @commit="(value: number) => commitAutoLayoutValueEdit(value)"
@editing-change="
(editing: boolean) =>
!editing &&
- autoLayoutPaddingEdit &&
- commitAutoLayoutPaddingEdit(autoLayoutPaddingEdit.value)
+ autoLayoutValueEdit &&
+ commitAutoLayoutValueEdit(autoLayoutValueEdit.value)
"
>
<template #icon>
- <component :is="paddingEditorIcon" class="size-3.5" />
+ <component :is="valueEditorIcon" class="size-3.5" />
</template>
</NumberField>
</PopoverContent>
diff --git a/src/components/properties/LayerTypeMenu.vue b/src/components/properties/LayerTypeMenu.vue
index 2aa020742..7015f852d 100644
--- a/src/components/properties/LayerTypeMenu.vue
+++ b/src/components/properties/LayerTypeMenu.vue
@@ -10,6 +10,7 @@ import type { Component } from 'vue'
import IconCheck from '~icons/lucide/check'
import IconChevronDown from '~icons/lucide/chevron-down'
+import { layerTypeOptions, type LayerType } from '@open-pencil/core/editor'
import type { SceneNode } from '@open-pencil/scene-graph'
import { useI18n, useRetainedPopup } from '@open-pencil/vue'
@@ -18,20 +19,21 @@ 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.
+// Figma's layer type menu: a frame, a group, and a section switch to one another in place.
const { node, icon } = defineProps<{ node: SceneNode; icon: Component | undefined }>()
const store = useEditorStore()
-const { panels } = useI18n()
+const { panels, tools } = useI18n()
const { open: popupOpen, portalActive } = useRetainedPopup()
const types = [
+ { type: 'SECTION', icon: NODE_ICONS.SECTION, label: () => tools.value.section },
{ 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
+// Read when the menu renders, so it reflects where the layer sits now.
+const disabled = (type: LayerType) => !layerTypeOptions(store.graph, node)[type]
const menuCls = useMenuUI({ content: 'min-w-36' })
const itemCls = menuItem({ justify: 'between' })
diff --git a/tests/app/editor/vector/lifecycle.test.ts b/tests/app/editor/vector/lifecycle.test.ts
index c76cd7d48..34cb040a9 100644
--- a/tests/app/editor/vector/lifecycle.test.ts
+++ b/tests/app/editor/vector/lifecycle.test.ts
@@ -42,3 +42,29 @@ test('opens a vector in a component but not its copy in an instance, as Figma do
lifecycle.enterNodeEditMode(vector.id)
expect(state.nodeEditState?.nodeId).toBe(vector.id)
})
+
+test('closes the path when its layer is deleted or the document is replaced', () => {
+ const graph = new SceneGraph()
+ const pageId = expectDefined(graph.getPages()[0]).id
+ const open = (target: SceneGraph) =>
+ target.createNode('VECTOR', expectDefined(target.getPages()[0]).id, {
+ width: 100,
+ height: 50,
+ vectorNetwork: TRIANGLE
+ })
+ const vector = open(graph)
+ const state = { nodeEditState: null } as VectorEditState
+ const editor = createEditor({ graph })
+ const lifecycle = createVectorEditLifecycle(editor, state)
+
+ lifecycle.enterNodeEditMode(vector.id)
+ graph.deleteNode(graph.createNode('RECTANGLE', pageId).id)
+ expect(state.nodeEditState?.nodeId).toBe(vector.id)
+ graph.deleteNode(vector.id)
+ expect(state.nodeEditState).toBeNull()
+
+ const next = new SceneGraph()
+ lifecycle.enterNodeEditMode(open(graph).id)
+ editor.replaceGraph(next)
+ expect(state.nodeEditState).toBeNull()
+})
diff --git a/tests/e2e/canvas/auto-layout-values.spec.ts b/tests/e2e/canvas/auto-layout-values.spec.ts
new file mode 100644
index 000000000..3eefadada
--- /dev/null
+++ b/tests/e2e/canvas/auto-layout-values.spec.ts
@@ -0,0 +1,24 @@
+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'
+import { autoLayoutValuesDriver } from '#tests/helpers/canvas/auto-layout-values/driver'
+
+// The pills Figma desktop 126 shows over a gap and a padding: as wide as the value, centred.
+
+const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')
+
+test('a gap and a padding show their values in pills that fit them', async () => {
+ const scene = autoLayoutValuesDriver(() => editor.page)
+ await scene.build()
+ for (const [name, x] of [
+ ['gap', 37 + 80 + 4],
+ ['padding', 18]
+ ] as const) {
+ const point = scene.point(x, 50)
+ await editor.canvas.hover(point.x, point.y)
+ editor.canvas.assertNoErrors()
+ const buffer = await editor.canvas.screenshotCanvasRegion(700, 400)
+ expect(buffer).toMatchSnapshot(`auto-layout-${name}-value.png`, {
+ maxDiffPixelRatio: 0,
+ threshold: 0
+ })
+ }
+})
diff --git a/tests/e2e/canvas/auto-layout-values.spec.ts-snapshots/auto-layout-gap-value-openpencil-darwin.png b/tests/e2e/canvas/auto-layout-values.spec.ts-snapshots/auto-layout-gap-value-openpencil-darwin.png
new file mode 100644
index 000000000..d104501b7
Binary files /dev/null and b/tests/e2e/canvas/auto-layout-values.spec.ts-snapshots/auto-layout-gap-value-openpencil-darwin.png differ
diff --git a/tests/e2e/canvas/auto-layout-values.spec.ts-snapshots/auto-layout-padding-value-openpencil-darwin.png b/tests/e2e/canvas/auto-layout-values.spec.ts-snapshots/auto-layout-padding-value-openpencil-darwin.png
new file mode 100644
index 000000000..a949fdad3
Binary files /dev/null and b/tests/e2e/canvas/auto-layout-values.spec.ts-snapshots/auto-layout-padding-value-openpencil-darwin.png differ
diff --git a/tests/e2e/editor/auto-layout/padding-editor.spec.ts b/tests/e2e/editor/auto-layout/padding-editor.spec.ts
index 48c4cca01..e7a021ebb 100644
--- a/tests/e2e/editor/auto-layout/padding-editor.spec.ts
+++ b/tests/e2e/editor/auto-layout/padding-editor.spec.ts
@@ -51,6 +51,14 @@ async function setupAutoLayoutFrame(page: Page) {
width: 120,
height: 40
})
+ store.graph.createNode('RECTANGLE', frame.id, {
+ name: 'Second child',
+ x: 180,
+ y: 188,
+ width: 120,
+ height: 40
+ })
+ store.runLayoutForNode(frame.id)
store.select([frame.id])
store.requestRender()
return frame.id
@@ -65,6 +73,13 @@ async function framePaddingTop(page: Page, frameId: string) {
}, frameId)
}
+async function frameGap(page: Page, frameId: string) {
+ return page.evaluate(
+ (id) => window.openPencil?.getStore?.().graph.getNode(id)?.itemSpacing ?? null,
+ frameId
+ )
+}
+
test('double-clicking an auto-layout padding handle opens a scrub editor', async ({ page }) => {
await page.goto('/')
const canvas = new CanvasHelper(page)
@@ -77,10 +92,10 @@ test('double-clicking an auto-layout padding handle opens a scrub editor', async
await canvas.hover(300, 130)
await dblclickCanvas(page, 300, 130)
- const editor = page.getByTestId('auto-layout-padding-editor')
+ const editor = page.getByTestId('auto-layout-value-editor')
await expect(editor).toBeVisible()
- await canvas.dragNumberField(editor.getByTestId('auto-layout-padding-input'), 40)
+ await canvas.dragNumberField(editor.getByTestId('auto-layout-value-input'), 40)
await expect(editor).toHaveCount(0)
const changedPadding = await framePaddingTop(page, frameId)
@@ -103,7 +118,7 @@ test('clicking the canvas closes the auto-layout padding editor', async ({ page
await canvas.hover(300, 130)
await dblclickCanvas(page, 300, 130)
- const editor = page.getByTestId('auto-layout-padding-editor')
+ const editor = page.getByTestId('auto-layout-value-editor')
await expect(editor).toBeVisible()
await clickCanvas(page, 80, 80)
@@ -122,7 +137,7 @@ test('auto-layout padding editor follows canvas pan while open', async ({ page }
await canvas.hover(300, 130)
await dblclickCanvas(page, 300, 130)
- const editor = page.getByTestId('auto-layout-padding-editor')
+ const editor = page.getByTestId('auto-layout-value-editor')
await expect(editor).toBeVisible()
const before = await editor.boundingBox()
if (!before) throw new Error('Padding editor has no bounding box')
@@ -139,3 +154,76 @@ test('auto-layout padding editor follows canvas pan while open', async ({ page }
expect(after.x).toBeGreaterThan(before.x + 20)
canvas.assertNoErrors()
})
+
+test('double-clicking an auto-layout gap edits it like a padding, as in Figma', async ({
+ page
+}) => {
+ await page.goto('/')
+ const canvas = new CanvasHelper(page)
+ await canvas.waitForInit()
+ await canvas.clearCanvas()
+
+ const frameId = await setupAutoLayoutFrame(page)
+ await canvas.waitForRender()
+
+ // The gap between the two children: the frame's padding top, a 40 px child, then 8 px.
+ await canvas.hover(300, 120 + 20 + 40 + 4)
+ await dblclickCanvas(page, 300, 120 + 20 + 40 + 4)
+ const editor = page.getByTestId('auto-layout-value-editor')
+ await expect(editor).toBeVisible()
+ await expect(editor.getByRole('spinbutton')).toHaveAttribute('aria-valuenow', '8')
+
+ await canvas.dragNumberField(editor.getByTestId('auto-layout-value-input'), 40)
+ await expect(editor).toHaveCount(0)
+ expect(await frameGap(page, frameId)).toBeGreaterThan(8)
+
+ await canvas.undo()
+ expect(await frameGap(page, frameId)).toBe(8)
+ canvas.assertNoErrors()
+})
+
+test('selecting another layer closes the value editor and keeps the value it had', async ({
+ page
+}) => {
+ await page.goto('/')
+ const canvas = new CanvasHelper(page)
+ await canvas.waitForInit()
+ await canvas.clearCanvas()
+
+ const frameId = await setupAutoLayoutFrame(page)
+ await canvas.waitForRender()
+
+ await canvas.hover(300, 130)
+ await dblclickCanvas(page, 300, 130)
+ const editor = page.getByTestId('auto-layout-value-editor')
+ await expect(editor).toBeVisible()
+ await canvas.dragNumberField(editor.getByTestId('auto-layout-value-input'), 40)
+ await canvas.hover(300, 130)
+ await dblclickCanvas(page, 300, 130)
+ await expect(editor).toBeVisible()
+ const committed = await framePaddingTop(page, frameId)
+
+ await page.evaluate(() => window.openPencil?.getStore?.().clearSelection())
+ await expect(editor).toHaveCount(0)
+ expect(await framePaddingTop(page, frameId)).toBe(committed)
+ canvas.assertNoErrors()
+})
+
+test('deleting the frame closes its value editor', async ({ page }) => {
+ await page.goto('/')
+ const canvas = new CanvasHelper(page)
+ await canvas.waitForInit()
+ await canvas.clearCanvas()
+
+ const frameId = await setupAutoLayoutFrame(page)
+ await canvas.waitForRender()
+
+ await canvas.hover(300, 130)
+ await dblclickCanvas(page, 300, 130)
+ const editor = page.getByTestId('auto-layout-value-editor')
+ await expect(editor).toBeVisible()
+
+ await page.evaluate((id) => window.openPencil?.getStore?.().graph.deleteNode(id), frameId)
+ await expect(editor).toHaveCount(0)
+ canvas.assertNoErrors()
+})
diff --git a/tests/e2e/properties/layer-type.spec.ts b/tests/e2e/properties/layer-type.spec.ts
index 0f370f7a2..ce3e346ef 100644
--- a/tests/e2e/properties/layer-type.spec.ts
+++ b/tests/e2e/properties/layer-type.spec.ts
@@ -16,3 +16,18 @@ test('the layer type menu turns a frame into a group and back', async ({ page })
await page.getByRole('menuitem', { name: 'Frame', exact: true }).click()
await expect.poll(() => layer.type()).toBe('FRAME')
})
+
+test('the layer type menu turns a frame on the page into a section 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: 'Section', exact: true }).click()
+ await expect.poll(() => layer.type()).toBe('SECTION')
+ await trigger.click()
+ await expect(page.getByRole('menuitem', { name: 'Group', exact: true })).toBeDisabled()
+ await page.getByRole('menuitem', { name: 'Frame', exact: true }).click()
+ await expect.poll(() => layer.type()).toBe('FRAME')
+})
diff --git a/tests/engine/app/vector-edit-transforms.test.ts b/tests/engine/app/vector-edit-transforms.test.ts
index 4c84d4c5d..5e956cefe 100644
--- a/tests/engine/app/vector-edit-transforms.test.ts
+++ b/tests/engine/app/vector-edit-transforms.test.ts
@@ -65,6 +65,7 @@ function setup(frameRotation: number, vectorRotation: number) {
},
select: () => undefined,
requestRender: () => undefined,
+ onEditorEvent: () => () => undefined,
updateNodeWithUndo(id: string, changes: Partial<SceneNode>, label = 'Update') {
undoLabels.push(label)
graph.updateNode(id, changes)
diff --git a/tests/engine/figma/api/auto-layout/extras.test.ts b/tests/engine/figma/api/auto-layout/extras.test.ts
index 8989231ed..c62a9c6a6 100644
--- a/tests/engine/figma/api/auto-layout/extras.test.ts
+++ b/tests/engine/figma/api/auto-layout/extras.test.ts
@@ -3,14 +3,40 @@ import { describe, expect, test } from 'bun:test'
import { createAPI } from '../helpers'
describe('auto-layout extras', () => {
- test('primaryAxisSizingMode maps FIXED/AUTO', () => {
+ test('primaryAxisSizingMode maps FIXED/AUTO, and a new frame hugs along its main axis', () => {
+ // As in Figma desktop 126, a new frame's main axis hugs, which auto layout keeps.
const api = createAPI()
const frame = api.createFrame()
frame.layoutMode = 'VERTICAL'
- expect(frame.primaryAxisSizingMode).toBe('FIXED')
- frame.primaryAxisSizingMode = 'AUTO'
expect(frame.primaryAxisSizingMode).toBe('AUTO')
expect(frame.layoutSizingVertical).toBe('HUG')
+ frame.primaryAxisSizingMode = 'FIXED'
+ expect(frame.primaryAxisSizingMode).toBe('FIXED')
+ expect(frame.layoutSizingVertical).toBe('FIXED')
+ })
+
+ test('a resize fixes hugging axes, and a grid starts fixed on both', () => {
+ // Repeats a Figma desktop 126 script: the frame hugs its layer until it is resized.
+ const api = createAPI()
+ const frame = api.createFrame()
+ const box = api.createRectangle()
+ box.resize(40, 20)
+ frame.appendChild(box)
+ frame.layoutMode = 'VERTICAL'
+ expect([frame.primaryAxisSizingMode, frame.counterAxisSizingMode, frame.height]).toEqual([
+ 'AUTO',
+ 'FIXED',
+ 20
+ ])
+ frame.resize(200, 120)
+ expect([frame.primaryAxisSizingMode, frame.counterAxisSizingMode, frame.height]).toEqual([
+ 'FIXED',
+ 'FIXED',
+ 120
+ ])
+ const grid = api.createFrame()
+ grid.layoutMode = 'GRID'
+ expect([grid.primaryAxisSizingMode, grid.counterAxisSizingMode]).toEqual(['FIXED', 'FIXED'])
})
test('counterAxisSizingMode maps FIXED/AUTO', () => {
diff --git a/tests/engine/tools/modify.test.ts b/tests/engine/tools/modify.test.ts
index 40ad48c88..dd9728f2e 100644
--- a/tests/engine/tools/modify.test.ts
+++ b/tests/engine/tools/modify.test.ts
@@ -149,7 +149,8 @@ describe('set_layout', () => {
const rawBefore = getNodeOrThrow(graph, frame.id)
expect(rawBefore.layoutMode).toBe('NONE')
- expect(rawBefore.primaryAxisSizing).toBe('FIXED')
+ // A new frame hugs along its main axis, as in Figma.
+ expect(rawBefore.primaryAxisSizing).toBe('HUG')
expect(rawBefore.counterAxisSizing).toBe('FIXED')
const tool = getTool('set_layout')
diff --git a/tests/engine/vue/input/auto-layout-hover.test.ts b/tests/engine/vue/input/auto-layout-hover.test.ts
index df4e6b6e8..cb8301370 100644
--- a/tests/engine/vue/input/auto-layout-hover.test.ts
+++ b/tests/engine/vue/input/auto-layout-hover.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, test } from 'bun:test'
import type { Editor } from '@open-pencil/core/editor'
import { createDefaultNode, type SceneNode } from '@open-pencil/scene-graph'
-import { resolveAutoLayoutHover } from '#vue/shared/input/auto-layout-hover'
+import { autoLayoutValueAnchor, resolveAutoLayoutHover } from '#vue/shared/input/auto-layout-hover'
function frame(overrides: Partial<SceneNode> = {}): SceneNode {
return createDefaultNode(() => 'frame', 'FRAME', {
@@ -45,9 +45,9 @@ function child(id: string, y: number, height: number): SceneNode {
})
}
-function editor() {
+function editor(frameOverrides: Partial<SceneNode> = {}) {
const nodes = new Map<string, SceneNode>([
- ['frame', frame()],
+ ['frame', frame(frameOverrides)],
['title', child('title', 20, 32)],
['body', child('body', 60, 48)],
['bar', child('bar', 116, 12)]
@@ -106,4 +106,14 @@ describe('auto-layout hover resolver', () => {
test('falls back to frame hover inside empty selected areas', () => {
expect(resolveAutoLayoutHover(240, 235, editor())).toMatchObject({ kind: 'frame' })
})
+
+ test("opens a gap's editor on the tick the hover draws, in the middle of the content box", () => {
+ const uneven = editor({ paddingLeft: 20, paddingRight: 60 })
+ const anchor = autoLayoutValueAnchor(uneven, 'frame', 'itemSpacing', 0)
+ expect(anchor).toEqual({ x: 220, y: 156 })
+ expect(resolveAutoLayoutHover(220, 156, uneven)).toMatchObject({
+ kind: 'spacing-value',
+ index: 0
+ })
+ })
})
diff --git a/tests/helpers/canvas.ts b/tests/helpers/canvas.ts
index cf08a00c6..22cccd9f2 100644
--- a/tests/helpers/canvas.ts
+++ b/tests/helpers/canvas.ts
@@ -62,6 +62,8 @@ export class CanvasHelper {
}
async clearCanvas() {
+ // Inside path editing, Select All and Backspace act on the path's points, not the layers.
+ await this.pressKey('Escape')
await this.selectAll()
await this.pressKey('Backspace')
await this.waitForRender()
diff --git a/tests/helpers/canvas/auto-layout-values/driver.ts b/tests/helpers/canvas/auto-layout-values/driver.ts
new file mode 100644
index 000000000..9f6ac26df
--- /dev/null
+++ b/tests/helpers/canvas/auto-layout-values/driver.ts
@@ -0,0 +1,32 @@
+import type { Page } from '@playwright/test'
+
+import type * as ValueScene from '#tests/helpers/canvas/auto-layout-values/scene'
+
+/** The view the scene is shown in: canvas points are scene points times the zoom plus the pan. */
+const VIEW = { zoom: 2, pan: 100 }
+
+/** Builds the auto layout value scene, selected, and maps its points to the canvas. */
+export function autoLayoutValuesDriver(page: () => Page) {
+ return {
+ build() {
+ return page().evaluate(async (view) => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const fixtureURL = '/tests/helpers/canvas/auto-layout-values/scene.ts'
+ const scene: typeof ValueScene = await import(fixtureURL)
+ const row = scene.createAutoLayoutValueScene(store.graph, store.state.currentPageId)
+ store.runLayoutForNode(row)
+ store.state.zoom = view.zoom
+ store.state.panX = view.pan
+ store.state.panY = view.pan
+ store.select([row])
+ store.requestRender()
+ }, VIEW)
+ },
+
+ /** The canvas point over a scene point. */
+ point(x: number, y: number) {
+ return { x: VIEW.pan + x * VIEW.zoom, y: VIEW.pan + y * VIEW.zoom }
+ }
+ }
+}
diff --git a/tests/helpers/canvas/auto-layout-values/scene.ts b/tests/helpers/canvas/auto-layout-values/scene.ts
new file mode 100644
index 000000000..a1f8f3aef
--- /dev/null
+++ b/tests/helpers/canvas/auto-layout-values/scene.ts
@@ -0,0 +1,33 @@
+import type { Fill, SceneGraph } from '@open-pencil/scene-graph'
+
+const solid = (r: number, g: number, b: number): Fill[] => [
+ { type: 'SOLID', color: { r, g, b, a: 1 }, opacity: 1, visible: true }
+]
+
+/** A row with an 8 px gap and 37 px side padding, as Figma desktop 126 was hovered over. */
+export function createAutoLayoutValueScene(graph: SceneGraph, pageId: string) {
+ const row = graph.createNode('FRAME', pageId, {
+ name: 'Row',
+ x: 0,
+ y: 0,
+ width: 242,
+ height: 100,
+ layoutMode: 'HORIZONTAL',
+ primaryAxisSizing: 'HUG',
+ counterAxisSizing: 'HUG',
+ itemSpacing: 8,
+ paddingLeft: 37,
+ paddingRight: 37,
+ paddingTop: 20,
+ paddingBottom: 20,
+ fills: solid(1, 1, 1)
+ })
+ for (const name of ['A', 'B'])
+ graph.createNode('RECTANGLE', row.id, {
+ name,
+ width: 80,
+ height: 60,
+ fills: solid(0.85, 0.85, 0.85)
+ })
+ return row.id
+}
diff --git a/tests/helpers/canvas/vector-edit/driver.ts b/tests/helpers/canvas/vector-edit/driver.ts
index 77b4c107c..6074cfa27 100644
--- a/tests/helpers/canvas/vector-edit/driver.ts
+++ b/tests/helpers/canvas/vector-edit/driver.ts
@@ -9,8 +9,6 @@ export function vectorEditDriver(page: () => Page) {
return page().evaluate(async () => {
const store = window.openPencil?.getStore?.()
if (!store) throw new Error('OpenPencil store not initialized')
- // An earlier case may leave its path open.
- store.exitNodeEditMode(false)
const fixtureURL = '/tests/helpers/canvas/vector-edit/scene.ts'
const scene: typeof VectorEditScene = await import(fixtureURL)
const ids = scene.createComponentVectorScene(store.graph, store.state.currentPageId)