AI-native design editor. Open-source Figma alternative.
fix(fig): keep filled frames and copied text sized as in OpenPencil when exported to Figma (#956)
Danila Poyarkov099e5d7a15d7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bd74b1834..5ac6ef106 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -132,7 +132,8 @@- `figma.combineAsVariants` derives variant properties from components named as Figma names variants, such as `State=On, Size=Large`, as Combine as variants in the editor now does too; before, only slash-separated names gave the set any properties.- HTML and Tailwind export place layers of frames without auto layout at their coordinates instead of stacking them, leave the size of hugging auto layout frames and auto-sizing text to their content, and round ellipses.- Show the blinking caret in a new, empty text layer before the first character is typed.-- Text saved to `.fig` or copied to Figma keeps its layout in Figma: it wraps at the layer's width with its alignment and line height, and keeps ligatures and contextual forms such as Inter's arrows, where Figma previously drew every saved OpenPencil text layer on one unwrapped line (#914).+- Frames and instances that fill their auto layout parent keep filling it when saved to `.fig` or copied to Figma, instead of shrinking to their content there, as a filled title row or full-width button did.+- Text saved to `.fig` or copied to Figma keeps its layout in Figma: it wraps at the layer's width with its alignment and line height, and keeps ligatures and contextual forms such as Inter's arrows, where Figma previously drew every saved OpenPencil text layer on one unwrapped line (#914). Text copied to Figma also keeps growing with its content, instead of keeping the width OpenPencil measured, which clipped or wrapped labels Figma draws wider.- Release a document's memory when its tab closes. Every closed tab kept its scene, canvas, and editor panels alive until reload, so memory grew with each document opened and closed. Menus and shortcuts now also follow the active document, so Undo and Redo are offered according to its history rather than the first document opened.- Put a deleted variable back in its place in its collection when the deletion is undone, instead of at the end.- Start Pi chats with OpenPencil's MCP tools when the Harness companion runs on Node 22.15 or later; the companion now installs the dependency Pi's MCP adapter needs and loads its TypeScript sources. A reopened Pi session starts fresh instead of failing to resume its in-memory sandbox, and npm output from Pi no longer mixes into the companion's protocol.diff --git a/packages/core/src/clipboard.ts b/packages/core/src/clipboard.tsindex 637677150..755f4640d 100644--- a/packages/core/src/clipboard.ts+++ b/packages/core/src/clipboard.ts@@ -177,8 +177,6 @@ async function writeFigmaClipboardHTML(if (change.type !== 'TEXT' || !change.guid) continueconst source = sourceByGuid.get(`${change.guid.sessionID}:${change.guid.localID}`)if (!source) continue- change.textAutoResize = 'NONE'- change.textUserLayoutVersion = 5change.lineHeight = {value: source.lineHeight ?? 100,units: source.lineHeight ? 'PIXELS' : 'PERCENT'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.tsnew file mode 100644index 000000000..0d6bd7c66--- /dev/null+++ b/packages/core/tests/io/formats/fig/export/filled-sizing-export.test.ts@@ -0,0 +1,151 @@+import { beforeAll, describe, expect, test } from 'bun:test'++import { guid } from '#core-tests/helpers/fig/guid'+import * as v from 'valibot'++import { exportFigFile } from '@open-pencil/core/io'+import { initCodec } from '@open-pencil/core/kiwi'+import { materializeDocument, parseFigBuffer } from '@open-pencil/fig'+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'+import { SceneGraph, setInstanceOverride } from '@open-pencil/scene-graph'++// Figma stores fill on the child and keeps that axis fixed in the frame's own sizing; a hugging+// value there wins over the fill, so a filled row or button opened in Figma shrank to its content.++beforeAll(async () => {+ await initCodec()+})++async function exported(graph: SceneGraph) {+ const bytes = await exportFigFile(graph)+ const changes = parseFigBuffer(bytes.buffer as ArrayBuffer).nodeChanges+ return (name: string) => {+ const change = changes.find((node) => node.name === name)+ if (!change) throw new Error(`Missing ${name}`)+ return change+ }+}++describe('own sizing of frames that fill their parent', () => {+ test('a stretched row and a growing column are fixed along the axis they fill', async () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0].id+ const card = graph.createNode('FRAME', page, {+ name: 'Card',+ layoutMode: 'VERTICAL',+ width: 320,+ height: 200+ })+ graph.createNode('FRAME', card.id, {+ name: 'Title row',+ layoutMode: 'HORIZONTAL',+ primaryAxisSizing: 'HUG',+ counterAxisSizing: 'HUG',+ layoutAlignSelf: 'STRETCH'+ })+ const strip = graph.createNode('FRAME', card.id, {+ name: 'Strip',+ layoutMode: 'HORIZONTAL',+ primaryAxisSizing: 'FIXED',+ counterAxisSizing: 'HUG'+ })+ graph.createNode('FRAME', strip.id, {+ name: 'Column',+ layoutMode: 'VERTICAL',+ primaryAxisSizing: 'HUG',+ counterAxisSizing: 'HUG',+ layoutGrow: 1+ })++ const change = await exported(graph)+ expect(change('Title row')).toMatchObject({+ stackPrimarySizing: 'FIXED',+ stackCounterSizing: 'RESIZE_TO_FIT',+ stackChildAlignSelf: 'STRETCH'+ })+ expect(change('Column')).toMatchObject({+ stackPrimarySizing: 'RESIZE_TO_FIT',+ stackCounterSizing: 'FIXED',+ stackChildPrimaryGrow: 1+ })+ })++ test('an imported layer keeps its stored sizing until its layout is edited', async () => {+ const changes: NodeChange[] = [+ { guid: guid(1), type: 'DOCUMENT' },+ { guid: guid(2), type: 'CANVAS', parentIndex: { guid: guid(1), position: '!' } },+ {+ guid: guid(3),+ type: 'FRAME',+ name: 'Card',+ parentIndex: { guid: guid(2), position: '!' },+ stackMode: 'VERTICAL',+ stackPrimarySizing: 'FIXED',+ stackCounterSizing: 'FIXED',+ size: { x: 320, y: 200 }+ },+ {+ guid: guid(4),+ type: 'FRAME',+ name: 'Row',+ parentIndex: { guid: guid(3), position: '!' },+ stackMode: 'HORIZONTAL',+ stackPrimarySizing: 'RESIZE_TO_FIT',+ stackCounterSizing: 'RESIZE_TO_FIT',+ stackChildAlignSelf: 'STRETCH',+ size: { x: 320, y: 20 }+ }+ ]+ const { graph, sources } = materializeDocument(changes)+ expect((await exported(graph))('Row').stackPrimarySizing).toBe('RESIZE_TO_FIT')++ const row = sources.get('1:4')+ if (!row) throw new Error('Missing row')+ graph.updateNode(row, { primaryAxisSizing: 'HUG' })+ expect((await exported(graph))('Row').stackPrimarySizing).toBe('FIXED')+ })++ test('an instance stretched across its parent overrides its sizing as fixed', async () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0].id+ const button = graph.createNode('COMPONENT', page, {+ name: 'Button',+ layoutMode: 'HORIZONTAL',+ primaryAxisSizing: 'FIXED',+ counterAxisSizing: 'FIXED',+ width: 272,+ height: 48+ })+ const card = graph.createNode('FRAME', page, {+ name: 'Card',+ layoutMode: 'VERTICAL',+ x: 400,+ width: 320,+ height: 200+ })+ const instance = graph.createInstance(button.id, card.id)+ if (!instance) throw new Error('Instance not created')+ graph.updateNode(instance.id, {+ name: 'Get started',+ primaryAxisSizing: 'HUG',+ layoutAlignSelf: 'STRETCH'+ })+ // The instance hugs as an override of its component, as editing it in the canvas records.+ setInstanceOverride(+ instance.instanceOverrides,+ instance.id,+ instance.id,+ 'primaryAxisSizing',+ 'HUG'+ )++ const change = (await exported(graph))('Get started')+ // Figma applies an instance's sizing override over its own fields, so the override decides.+ const overrides = v.parse(+ v.optional(v.array(v.looseObject({ stackPrimarySizing: v.optional(v.string()) })), []),+ Reflect.get(change.symbolData ?? {}, 'symbolOverrides')+ )+ const sizing = overrides.find((override) => override.stackPrimarySizing !== undefined)+ expect(sizing?.stackPrimarySizing).toBe('FIXED')+ })+})diff --git a/packages/fig/src/node-change/export/fill-sizing.ts b/packages/fig/src/node-change/export/fill-sizing.tsnew file mode 100644index 000000000..24376778a--- /dev/null+++ b/packages/fig/src/node-change/export/fill-sizing.ts@@ -0,0 +1,19 @@+import { layoutSizing, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'++export type OwnSizingField = 'stackPrimarySizing' | 'stackCounterSizing'++/**+ * Whether a frame fills its parent along the axis one of its own sizing fields governs. Figma+ * stores fill on the child and keeps that axis fixed in the frame's own sizing: a hugging value+ * there wins over the fill, so a filled row or button would shrink to its content.+ */+export function fillsOwnSizingAxis(+ graph: SceneGraph,+ node: SceneNode,+ field: OwnSizingField+): boolean {+ if (node.layoutMode !== 'HORIZONTAL' && node.layoutMode !== 'VERTICAL') return false+ const counter = node.layoutMode === 'HORIZONTAL' ? 'VERTICAL' : 'HORIZONTAL'+ const axis = field === 'stackPrimarySizing' ? node.layoutMode : counter+ return layoutSizing(graph, node, axis) === 'FILL'+}diff --git a/packages/fig/src/node-change/export/override-claims.ts b/packages/fig/src/node-change/export/override-claims.tsindex 6212030b6..aad6d4f85 100644--- a/packages/fig/src/node-change/export/override-claims.ts+++ b/packages/fig/src/node-change/export/override-claims.ts@@ -1,7 +1,12 @@import { SCENE_OVERRIDE_FIELDS } from '#fig/instance-overrides/fields'import { stringToGuid } from '@open-pencil/kiwi/fig/guid'-import { forEachInstanceOverride, ownsSlotContent, type SceneNode } from '@open-pencil/scene-graph'+import {+ forEachInstanceOverride,+ ownsSlotContent,+ type SceneGraph,+ type SceneNode+} from '@open-pencil/scene-graph'import type { GUID, Vector } from '@open-pencil/scene-graph/primitives'import { instanceExportAddress } from '../instance/geometry'@@ -17,6 +22,7 @@ import {type SceneNodeToKiwiContext,type StyleReference} from './context'+import { fillsOwnSizingAxis } from './fill-sizing'import { nodeWithResolvedBindings } from './resolved-bindings'function exportedTextStyleReference(context: SceneNodeToKiwiContext, id: string): StyleReference {@@ -43,11 +49,21 @@ function exportedSwapOverride(return component ? { guidPath: { guids: path }, overriddenSymbolID: component } : undefined}-/** Layout modes are dimensionless; sizing modes map to Figma's implicit-size vocabulary. */-function layoutModeClaim(raw: string, value: unknown): Record<string, unknown> | undefined {+/**+ * Layout modes are dimensionless; sizing modes map to Figma's implicit-size vocabulary, and an+ * axis the layer fills stays fixed, since Figma applies the override over the fill.+ */+function layoutModeClaim(+ raw: string,+ value: unknown,+ graph: SceneGraph,+ target: SceneNode+): Record<string, unknown> | undefined {if (typeof value !== 'string' && typeof value !== 'number') return undefined- if (raw === 'stackPrimarySizing' || raw === 'stackCounterSizing')- return { [raw]: value === 'HUG' ? 'RESIZE_TO_FIT_WITH_IMPLICIT_SIZE' : 'FIXED' }+ if (raw === 'stackPrimarySizing' || raw === 'stackCounterSizing') {+ const hugs = value === 'HUG' && !fillsOwnSizingAxis(graph, target, raw)+ return { [raw]: hugs ? 'RESIZE_TO_FIT_WITH_IMPLICIT_SIZE' : 'FIXED' }+ }return { [raw]: value }}@@ -102,7 +118,7 @@ function registryClaim(case 'layout-distance':return layoutDistanceClaim(raw, target[field], instance)case 'layout-mode':- return layoutModeClaim(raw, target[field])+ return layoutModeClaim(raw, target[field], context.graph, target)default:return undefined}diff --git a/packages/fig/src/node-change/serialize.ts b/packages/fig/src/node-change/serialize.tsindex ec284f03b..066bdc7c6 100644--- a/packages/fig/src/node-change/serialize.ts+++ b/packages/fig/src/node-change/serialize.ts@@ -9,6 +9,7 @@ import { fractionalPosition } from '@open-pencil/scene-graph/order-keys'import { effectiveFigmaRawNodeFields } from '../source-metadata'import { computeExportTransform, mapToFigmaType } from './basics'import { buildNodeDerivedTextData } from './derived-text/build'+import { fillsOwnSizingAxis } from './export/fill-sizing'import { EMPTY_EXPORT_RUNTIME, type FigNodeChangeExportRuntime } from './export/runtime'import { applyFontFeaturesToKiwi } from './font/features'import { weightToFigmaStyle } from './font/style'@@ -218,6 +219,28 @@ function exportSizing(value: SceneNode['primaryAxisSizing']) {return value === 'HUG' ? 'RESIZE_TO_FIT' : 'FIXED'}+/** Layout fields whose edits decide whether a frame's own sizing still matches its fill. */+const OWN_SIZING_FIELDS: ReadonlySet<string> = new Set([+ 'layoutMode',+ 'primaryAxisSizing',+ 'counterAxisSizing',+ 'layoutGrow',+ 'layoutAlignSelf',+ 'layoutPositioning'+])++/**+ * Writes a frame's own sizing as fixed along an axis it fills, the way Figma stores fill (see+ * `fillsOwnSizingAxis`). Unedited imported layers keep their stored sizing, since Figma's own+ * files also hold hugging axes on stretched children.+ */+function fixFilledOwnSizing(node: SceneNode, nc: KiwiNodeChange, graph: SceneGraph): void {+ const imported = Boolean(node.source.fig.layout)+ if (imported && !node.source.editedFields.some((field) => OWN_SIZING_FIELDS.has(field))) return+ if (fillsOwnSizingAxis(graph, node, 'stackPrimarySizing')) nc.stackPrimarySizing = 'FIXED'+ if (fillsOwnSizingAxis(graph, node, 'stackCounterSizing')) nc.stackCounterSizing = 'FIXED'+}+function applyEditedLayoutFields(node: SceneNode, nc: KiwiNodeChange): void {const values: Partial<Record<keyof SceneNode, Partial<KiwiNodeChange>>> = {layoutMode: { stackMode: normalizeStackMode(node.layoutMode) },@@ -295,6 +318,7 @@ function serializeLayoutProps(node: SceneNode, nc: KiwiNodeChange, graph: SceneGif (figLayout.stackReverseZIndex) nc.stackReverseZIndex = trueserializeInheritedCounterAxisStretch(node, nc, graph)applyEditedLayoutFields(node, nc)+ fixFilledOwnSizing(node, nc, graph)return}if (node.layoutMode !== 'NONE' && node.layoutMode !== 'GRID') {@@ -320,6 +344,7 @@ function serializeLayoutProps(node: SceneNode, nc: KiwiNodeChange, graph: SceneG} else {serializeInheritedCounterAxisStretch(node, nc, graph)}+ fixFilledOwnSizing(node, nc, graph)}function serializeGeometry(node: SceneNode, nc: KiwiNodeChange, blobs: Uint8Array[]): void {diff --git a/tests/engine/clipboard/figma/html.test.ts b/tests/engine/clipboard/figma/html.test.tsindex 32891f66f..6a44657c7 100644--- a/tests/engine/clipboard/figma/html.test.ts+++ b/tests/engine/clipboard/figma/html.test.ts@@ -15,10 +15,9 @@ import { expectDefined } from '#tests/helpers/assert'function expectFigmaEditableTextDefaults(textNode: NonNullable<Awaited<ReturnType<typeof parseFigmaClipboard>>>['nodes'][number]) {- expect(textNode.textUserLayoutVersion).toBe(5)+ expect(textNode.textUserLayoutVersion).toBe(4)expect(textNode.textExplicitLayoutVersion).toBe(1)expect(textNode.textBidiVersion).toBe(1)- expect(textNode.textAutoResize).toBe('NONE')expect(textNode.lineHeight).toEqual({ value: 100, units: 'PERCENT' })expect(textNode.letterSpacing).toEqual({ value: 0, units: 'PIXELS' })expect(textNode.fontVariantCommonLigatures).toBe(true)@@ -97,6 +96,35 @@ describe('buildFigmaClipboardHTML', () => {}})+ it('keeps how text resizes, so Figma reflows it in its own font', async () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const create = (name: string, textAutoResize: 'WIDTH_AND_HEIGHT' | 'HEIGHT' | 'NONE') =>+ graph.createNode('TEXT', page.id, {+ name,+ width: 120,+ height: 24,+ text: 'Get started',+ fontFamily: 'Inter',+ fontSize: 16,+ textAutoResize+ })+ const nodes = [+ create('Label', 'WIDTH_AND_HEIGHT'),+ create('Body', 'HEIGHT'),+ create('Box', 'NONE')+ ]++ const html = await buildFigmaClipboardHTML(nodes, graph)+ const parsed = await parseFigmaClipboard(expectDefined(html, 'Figma clipboard html'))+ const autoResize = Object.fromEntries(+ (parsed?.nodes ?? [])+ .filter((node) => node.type === 'TEXT')+ .map((node) => [node.name, node.textAutoResize])+ )+ expect(autoResize).toEqual({ Label: 'WIDTH_AND_HEIGHT', Body: 'HEIGHT', Box: 'NONE' })+ })+it('encodes text nodes with style runs', async () => {const graph = new SceneGraph()const page = graph.getPages()[0]@@ -156,8 +184,8 @@ describe('buildFigmaClipboardHTML', () => {const textNode = parsed?.nodes.find((node) => node.type === 'TEXT')const baseline = textNode?.derivedTextData?.baselines?.[0]- expect(textNode?.textUserLayoutVersion).toBe(5)- expect(textNode?.textAutoResize).toBe('NONE')+ // The text keeps its auto-resize, so Figma reflows it in its own font instead of fixing the box.+ expect(textNode?.textAutoResize).toBe('HEIGHT')const glyphs = textNode?.derivedTextData?.glyphs ?? []expect(glyphs).toHaveLength('Analytics Overview'.length)expect(glyphs.every((glyph) => glyph.commandsBlob === undefined)).toBe(true)