AI-native design editor. Open-source Figma alternative.
fix(fig): preserve variable-backed style assignments on save (#1205)
GitttHomie2e50513cd371
diff --git a/changes/1205/breaking.md b/changes/1205/breaking.mdnew file mode 100644index 000000000..dd3d9549b--- /dev/null+++ b/changes/1205/breaking.md@@ -0,0 +1 @@+- `SceneGraph.updateNode` writes fields as given and no longer detaches shared styles. An edit detaches the styles whose fields it changes before writing, with `styleDetachmentChanges` from `@open-pencil/scene-graph/shared-styles`, as the editor and the plugin API do.diff --git a/changes/1205/fixed.md b/changes/1205/fixed.mdnew file mode 100644index 000000000..3ca975fe4--- /dev/null+++ b/changes/1205/fixed.md@@ -0,0 +1,2 @@+- Layers keep their text, fill, and stroke styles when their variable bindings resolve, on `.fig` open and save and when a variable or mode changes.+- Setting a stroke's weight or alignment through the plugin API keeps the layer's stroke style.diff --git a/packages/core/src/editor/connectors/style.ts b/packages/core/src/editor/connectors/style.tsindex 21c317a96..f9842ca34 100644--- a/packages/core/src/editor/connectors/style.ts+++ b/packages/core/src/editor/connectors/style.ts@@ -15,6 +15,7 @@ import {import { figJamColor, type FigJamColorName } from '@open-pencil/scene-graph/figjam'import { recordSubtreeEdit } from '#core/editor/components/slots/history'+import type { NodeActions } from '#core/editor/nodes'import type { EditorContext } from '#core/editor/types'/** A straight connector attaches by its layers' centres, as Figma moves its magnets. */@@ -28,7 +29,7 @@ function straightEnd(endpoint: ConnectorEndpoint | null): ConnectorEndpoint | nu* dash, as FigJam's selection toolbar sets them. Each change records the* connectors' whole subtrees as one step, and the connectors route again.*/-export function createConnectorStyleActions(ctx: EditorContext) {+export function createConnectorStyleActions(ctx: EditorContext, nodes: NodeActions) {function edit(label: string, ids: Iterable<string>, change: (connector: SceneNode) => void) {const connectors = [...ids].flatMap((id) => {const node = ctx.graph.getNode(id)@@ -52,7 +53,7 @@ export function createConnectorStyleActions(ctx: EditorContext) {function setConnectorLineType(ids: Iterable<string>, lineType: ConnectorLineType) {edit('Change connector line', ids, (connector) =>- ctx.graph.updateNode(connector.id, {+ nodes.updateNode(connector.id, {connectorLineType: lineType,...(lineType === 'STRAIGHT' && {connectorStart: straightEnd(connector.connectorStart),@@ -64,7 +65,7 @@ export function createConnectorStyleActions(ctx: EditorContext) {function setConnectorCap(ids: Iterable<string>, end: 'start' | 'end', cap: StrokeCap) {edit(end === 'start' ? 'Change start point' : 'Change end point', ids, (connector) =>- ctx.graph.updateNode(connector.id, {+ nodes.updateNode(connector.id, {[end === 'start' ? 'connectorStartCap' : 'connectorEndCap']: cap}))@@ -73,7 +74,7 @@ export function createConnectorStyleActions(ctx: EditorContext) {function restyleLine(label: string, ids: Iterable<string>, style: Partial<ConnectorLineStyle>) {edit(label, ids, (connector) => {const line = connectorSublayers(ctx.graph, connector)?.line- if (line) ctx.graph.updateNode(line.id, connectorLineStyleFields(line, style))+ if (line) nodes.updateNode(line.id, connectorLineStyleFields(line, style))})}diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.tsindex aa338a742..11c538671 100644--- a/packages/core/src/editor/create.ts+++ b/packages/core/src/editor/create.ts@@ -303,9 +303,9 @@ export function createEditor(options?: EditorOptions) {const designTokens = createDesignTokenActions(ctx, variables, nodes)const vectorize = createVectorizeActions(ctx)const icons = createIconActions(ctx)- const stickies = createStickyActions(ctx)- const shapesWithText = createShapeWithTextActions(ctx)- const generatedText = createGeneratedTextActions(ctx)+ const stickies = createStickyActions(ctx, nodes)+ const shapesWithText = createShapeWithTextActions(ctx, nodes)+ const generatedText = createGeneratedTextActions(ctx, nodes)const statuses = createStatusActions(ctx)const figCompression = createFigCompressionActions(ctx)createConnectorRouting(ctx)@@ -316,7 +316,7 @@ export function createEditor(options?: EditorOptions) {clipboard.deleteNodes)const connectorLines = createConnectorLineActions(ctx, nodes.beginNodePreview)- const connectorStyles = createConnectorStyleActions(ctx)+ const connectorStyles = createConnectorStyleActions(ctx, nodes)const lineEnds = createLineEndActions(ctx, nodes.beginNodePreview)const shaders = createShaderActions(ctx, nodes)const alignment = createAlignmentActions(ctx)diff --git a/packages/core/src/editor/design-tokens.ts b/packages/core/src/editor/design-tokens.tsindex c926e5349..780217f78 100644--- a/packages/core/src/editor/design-tokens.ts+++ b/packages/core/src/editor/design-tokens.ts@@ -10,13 +10,11 @@ import {} from '#core/io/formats/design-tokens/apply'import type { TokenImportPlan } from '#core/io/formats/design-tokens/plan'-import type { createNodeActions } from './nodes'+import type { NodeActions } from './nodes'import type { EditorContext } from './types'import type { createVariableActions } from './variables'type VariableActions = ReturnType<typeof createVariableActions>-type NodeActions = ReturnType<typeof createNodeActions>-export function createDesignTokenActions(ctx: EditorContext,variables: VariableActions,diff --git a/packages/core/src/editor/nodes.ts b/packages/core/src/editor/nodes.tsindex e1cd39382..532406795 100644--- a/packages/core/src/editor/nodes.ts+++ b/packages/core/src/editor/nodes.ts@@ -138,3 +138,6 @@ export function createNodeActions(ctx: EditorContext) {...nudgeActions}}++/** The editor's node writes; an edit made through them leaves the shared styles it changes. */+export type NodeActions = ReturnType<typeof createNodeActions>diff --git a/packages/core/src/editor/shapes/with-text.ts b/packages/core/src/editor/shapes/with-text.tsindex 9608c6daf..54a9084d9 100644--- a/packages/core/src/editor/shapes/with-text.ts+++ b/packages/core/src/editor/shapes/with-text.ts@@ -16,6 +16,7 @@ import { shapeWithTextFrameFields, shapeWithTextLabel } from '@open-pencil/sceneimport type { ShapeWithTextType } from '@open-pencil/scene-graph/shape-with-text'import { recordSubtreeEdit } from '#core/editor/components/slots/history'+import type { NodeActions } from '#core/editor/nodes'import type { EditorContext } from '#core/editor/types'const FILL_OPACITY: Record<FigJamFillMode, number> = { fill: 1, transparent: 0.5, none: 0 }@@ -25,7 +26,7 @@ const FILL_OPACITY: Record<FigJamFillMode, number> = { fill: 1, transparent: 0.5* shapes already placed, as FigJam's selection toolbar sets them. Each change records the* shapes' whole subtrees as one step, since the label changes with the shape.*/-export function createShapeWithTextActions(ctx: EditorContext) {+export function createShapeWithTextActions(ctx: EditorContext, nodes: NodeActions) {function shapesAmong(ids: Iterable<string>): SceneNode[] {return [...ids].flatMap((id) => {const node = ctx.graph.getNode(id)@@ -59,7 +60,7 @@ export function createShapeWithTextActions(ctx: EditorContext) {'Change shape',changing.map((shape) => shape.id),(shape) => {- ctx.graph.updateNode(shape.id, {+ nodes.updateNode(shape.id, {shapeWithTextType: kind,...shapeWithTextFrameFields(kind, shape.width, shape.height)})@@ -70,8 +71,8 @@ export function createShapeWithTextActions(ctx: EditorContext) {function paint(shape: SceneNode, name: FigJamColorName, mode: FigJamFillMode) {const label = shapeWithTextLabel(ctx.graph, shape)const painted = figJamShapePaint(shape, label, name, mode)- ctx.graph.updateNode(shape.id, painted.shape)- if (label) ctx.graph.updateNode(label.id, painted.label)+ nodes.updateNode(shape.id, painted.shape)+ if (label) nodes.updateNode(label.id, painted.label)}/**@@ -92,7 +93,7 @@ export function createShapeWithTextActions(ctx: EditorContext) {const name = figJamColorName(fill?.color)if (name) paint(shape, name, mode)else if (fill) {- ctx.graph.updateNode(shape.id, {+ nodes.updateNode(shape.id, {fills: [{ ...fill, opacity: FILL_OPACITY[mode] }, ...shape.fills.slice(1)]})}@@ -102,14 +103,14 @@ export function createShapeWithTextActions(ctx: EditorContext) {/** Draws the shapes' outlines solid, dashed, or not at all. */function setShapesWithTextLineStyle(ids: Iterable<string>, style: FigJamLineStyle) {editShapes('Change shape line', ids, (shape) =>- ctx.graph.updateNode(shape.id, figJamLineStyleFields(shape, style))+ nodes.updateNode(shape.id, figJamLineStyleFields(shape, style)))}/** Colours the shapes' outlines in palette colour `name`, which later fills leave alone. */function setShapesWithTextLineColor(ids: Iterable<string>, name: FigJamColorName) {editShapes('Change shape line color', ids, (shape) =>- ctx.graph.updateNode(shape.id, figJamLineColorFields(shape, name))+ nodes.updateNode(shape.id, figJamLineColorFields(shape, name)))}@@ -118,10 +119,7 @@ export function createShapeWithTextActions(ctx: EditorContext) {editShapes('Change shape text size', ids, (shape) => {const label = shapeWithTextLabel(ctx.graph, shape)if (label) {- ctx.graph.updateNode(- label.id,- figJamTextSizeFields(size, figJamTypeface(label) ?? 'simple')- )+ nodes.updateNode(label.id, figJamTextSizeFields(size, figJamTypeface(label) ?? 'simple'))}})}diff --git a/packages/core/src/editor/stickies.ts b/packages/core/src/editor/stickies.tsindex dabe8df3e..f69aa1642 100644--- a/packages/core/src/editor/stickies.ts+++ b/packages/core/src/editor/stickies.ts@@ -19,11 +19,13 @@ import { recordSubtreeEdit } from '#core/editor/components/slots/history'import type { EditorContext } from '#core/editor/types'import { pushCreatedSubtreesUndo } from '#core/editor/undo'+import type { NodeActions } from './nodes'+/*** Sticky note commands. A note's colour sits on the note and its text on its sublayers, so each* change records the notes' whole subtrees as one step.*/-export function createStickyActions(ctx: EditorContext) {+export function createStickyActions(ctx: EditorContext, nodes: NodeActions) {/** The colour the sticky tool places notes in: the one picked last, as in FigJam. */let stickyColor: Color = DEFAULT_STICKY_COLOR@@ -75,7 +77,7 @@ export function createStickyActions(ctx: EditorContext) {const fills = fill? [{ ...fill, type: 'SOLID' as const, color: { ...color } }, ...sticky.fills.slice(1)]: [{ type: 'SOLID' as const, color: { ...color }, opacity: 1, visible: true }]- ctx.graph.updateNode(sticky.id, { fills })+ nodes.updateNode(sticky.id, { fills })})}@@ -84,7 +86,7 @@ export function createStickyActions(ctx: EditorContext) {editStickies('Change sticky text size', ids, (sticky) => {const body = stickySublayers(ctx.graph, sticky)?.bodyif (body) {- ctx.graph.updateNode(body.id, figJamTextSizeFields(size, figJamTypeface(body) ?? 'simple'))+ nodes.updateNode(body.id, figJamTextSizeFields(size, figJamTypeface(body) ?? 'simple'))}})}@@ -93,7 +95,7 @@ export function createStickyActions(ctx: EditorContext) {function setStickyAuthorVisible(ids: Iterable<string>, visible: boolean) {editStickies(visible ? 'Show sticky author' : 'Hide sticky author', ids, (sticky) => {const author = stickySublayers(ctx.graph, sticky)?.author- if (author) ctx.graph.updateNode(author.id, { visible })+ if (author) nodes.updateNode(author.id, { visible })})}diff --git a/packages/core/src/editor/text/typeface.ts b/packages/core/src/editor/text/typeface.tsindex 32d521692..fdc5e26eb 100644--- a/packages/core/src/editor/text/typeface.ts+++ b/packages/core/src/editor/text/typeface.ts@@ -7,10 +7,11 @@ import { faceLoadKey } from '@open-pencil/scene-graph/font-style'import { generatedFrameText } from '@open-pencil/scene-graph/generated'import { recordSubtreeEdit } from '#core/editor/components/slots/history'+import type { NodeActions } from '#core/editor/nodes'import type { EditorContext } from '#core/editor/types'/** Typefaces for the text generated frames are named by, such as a sticky note's body or a shape's label. */-export function createGeneratedTextActions(ctx: EditorContext) {+export function createGeneratedTextActions(ctx: EditorContext, nodes: NodeActions) {/*** Sets the text that sticky notes and shapes among `ids` are named by in one of FigJam's* typefaces, once its face is loaded.@@ -30,7 +31,7 @@ export function createGeneratedTextActions(ctx: EditorContext) {() => {for (const frame of frames) {const text = generatedFrameText(ctx.graph, frame)- if (text) ctx.graph.updateNode(text.id, figJamTypefaceFields(typeface, text))+ if (text) nodes.updateNode(text.id, figJamTypefaceFields(typeface, text))}})diff --git a/packages/core/src/figma-api/accessor-utils.ts b/packages/core/src/figma-api/accessor-utils.tsindex 8884510c7..094e7a69e 100644--- a/packages/core/src/figma-api/accessor-utils.ts+++ b/packages/core/src/figma-api/accessor-utils.ts@@ -5,6 +5,7 @@ import { connectorSublayers } from '@open-pencil/scene-graph/connectors'import { fitEnclosingGroups, type GroupFitOptions } from '@open-pencil/scene-graph/group-bounds'import { recordInstanceOverride } from '@open-pencil/scene-graph/instances'import { FITTED_CONTAINER_TYPES } from '@open-pencil/scene-graph/node-defaults'+import { styleDetachmentChanges } from '@open-pencil/scene-graph/shared-styles'import { claimSlotContent, slotScope } from '@open-pencil/scene-graph/slots'import { assertNodeEditable } from '#core/editor/capabilities'@@ -125,16 +126,18 @@ export function updateNode(.map((key) => [key, Reflect.get(changes, key)])) as Partial<SceneNode>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)+ // Auto-sizing text measures its new content, as the editor's updates do.+ Object.assign(applied, textAutoResizeChanges(before, applied))+ // An edit to a style's fields leaves that style, as the editor's updates do.+ const edit = before ? styleDetachmentChanges(before, applied) : applied// 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))+ const changed = Object.keys(edit).filter(+ (key) => !before || !isEqual(Reflect.get(edit, key), Reflect.get(before, key)))- g.updateNode(id, applied)+ g.updateNode(id, edit)recordInstanceOverride(g, id, changed)- if (Object.keys(applied).some((key) => GEOMETRY_FIELDS.has(key))) {+ if (Object.keys(edit).some((key) => GEOMETRY_FIELDS.has(key))) {fitGroupsAround(g, g.getNode(id)?.parentId, hostFitOptions(target, internals))}}diff --git a/packages/core/src/tools/modify/update.ts b/packages/core/src/tools/modify/update.tsindex 277453a6a..d1435020c 100644--- a/packages/core/src/tools/modify/update.ts+++ b/packages/core/src/tools/modify/update.ts@@ -1,5 +1,8 @@import * as v from 'valibot'+import type { SceneNode } from '@open-pencil/scene-graph'+import { styleDetachmentChanges } from '@open-pencil/scene-graph/shared-styles'+import { assertNodeEditable } from '#core/editor/capabilities'import type { FigmaNodeProxy } from '#core/figma-api'import { toolNumber, nodeIdInputSchema, defineTool, nodeNotFound } from '#core/tools/schema'@@ -72,6 +75,12 @@ export const updateNode = defineTool({const node = figma.getNodeById(args.id)if (!node) return nodeNotFound(args.id)assertNodeEditable(figma.graph, args.id)+ // Written to the layer directly, since the plugin setters need a loaded font; an edit to a+ // text style's field leaves the style, as the editor's updates do.+ const editTypography = (changes: Partial<SceneNode>) => {+ const scene = figma.graph.getNode(args.id)+ if (scene) figma.graph.updateNode(args.id, styleDetachmentChanges(scene, changes))+ }const updated: string[] = []if (args.x !== undefined) {node.x = args.x@@ -116,11 +125,11 @@ export const updateNode = defineTool({updated.push('layoutDirection')}if (args.font_size !== undefined) {- figma.graph.updateNode(node.id, { fontSize: args.font_size })+ editTypography({ fontSize: args.font_size })updated.push('fontSize')}if (args.font_weight !== undefined) {- figma.graph.updateNode(node.id, { fontWeight: args.font_weight })+ editTypography({ fontWeight: args.font_weight })updated.push('fontWeight')}return { id: args.id, updated }diff --git a/packages/core/tests/editor/connectors/style.test.ts b/packages/core/tests/editor/connectors/style.test.tsindex e4d2e3387..220fce8cf 100644--- a/packages/core/tests/editor/connectors/style.test.ts+++ b/packages/core/tests/editor/connectors/style.test.ts@@ -3,7 +3,11 @@ import { describe, expect, test } from 'bun:test'import { expectDefined } from '#core-tests/helpers/assert'import { createEditor } from '@open-pencil/core'-import { boundEndpoint, buildConnectorSublayers, connectorSublayers } from '@open-pencil/scene-graph/connectors'+import {+ boundEndpoint,+ buildConnectorSublayers,+ connectorSublayers+} from '@open-pencil/scene-graph/connectors'import { figJamColor } from '@open-pencil/scene-graph/figjam'function setup() {@@ -44,4 +48,19 @@ describe("FigJam's connector line menu", () => {expect(line().strokes[0]?.dashPattern).toEqual([])expect(line().strokeWeight).toBe(8)})++ test('thickness and dashes keep the stroke style, which gives the paint only', () => {+ const { editor, connector, line } = setup()+ editor.graph.updateNode(line().id, { strokeStyleId: 'stroke-style' })+ editor.setConnectorThick([connector.id], true)+ editor.setConnectorDashed([connector.id], true)+ expect(line().strokeStyleId).toBe('stroke-style')+ })++ test('a palette colour leaves the stroke style it replaces', () => {+ const { editor, connector, line } = setup()+ editor.graph.updateNode(line().id, { strokeStyleId: 'stroke-style' })+ editor.setConnectorColor([connector.id], 'red')+ expect(line().strokeStyleId).toBeNull()+ })})diff --git a/packages/core/tests/editor/shapes/with-text.test.ts b/packages/core/tests/editor/shapes/with-text.test.tsindex 056cb8a91..4d052325f 100644--- a/packages/core/tests/editor/shapes/with-text.test.ts+++ b/packages/core/tests/editor/shapes/with-text.test.ts@@ -100,4 +100,13 @@ describe('shapes with text in the editor', () => {editor.setShapesWithTextTextSize([id], 'small')expect(editor.graph.getNode(id)?.height).toBe(176)})++ test('a palette colour leaves the fill and stroke styles it replaces', () => {+ const { editor, pageId } = setup()+ const id = editor.createShape('SHAPE_WITH_TEXT', 0, 0, 176, 176, pageId)+ editor.graph.updateNode(id, { fillStyleId: 'fill-style', strokeStyleId: 'stroke-style' })+ editor.setShapesWithTextColor([id], 'violet')+ const shape = expectDefined(editor.graph.getNode(id))+ expect([shape.fillStyleId, shape.strokeStyleId]).toEqual([null, null])+ })})diff --git a/packages/core/tests/editor/stickies.test.ts b/packages/core/tests/editor/stickies.test.tsindex 759b03d85..e1e5c3fdc 100644--- a/packages/core/tests/editor/stickies.test.ts+++ b/packages/core/tests/editor/stickies.test.ts@@ -57,7 +57,10 @@ describe('sticky notes', () => {const { editor, pageId } = setup()const sticky = editor.createStickyNote(pageId, { x: 0, y: 0 })editor.setStickyTextSize([sticky.id], 'large')- expect(sublayers(editor, sticky).body).toMatchObject({ fontSize: 40, lineHeight: percentLength(150) })+ expect(sublayers(editor, sticky).body).toMatchObject({+ fontSize: 40,+ lineHeight: percentLength(150)+ })editor.setStickyAuthorVisible([sticky.id], false)expect(sublayers(editor, sticky).author.visible).toBe(false)@@ -97,7 +100,10 @@ describe('sticky notes', () => {const sticky = editor.createStickyNote(pageId, { x: 0, y: 0 })editor.graph.updateNode(sublayers(editor, sticky).body.id, { fontFamily: 'Figma Hand' })editor.setStickyTextSize([sticky.id], 'large')- expect(sublayers(editor, sticky).body).toMatchObject({ fontSize: 40, letterSpacing: percentLength(0) })+ expect(sublayers(editor, sticky).body).toMatchObject({+ fontSize: 40,+ letterSpacing: percentLength(0)+ })})test("typing in a note's body renames a note that was never renamed", () => {@@ -114,4 +120,20 @@ describe('sticky notes', () => {editor.undo.undo()expect(editor.graph.getNode(sticky.id)?.autoRename).toBe(true)})++ test('a new colour or text size leaves the shared style it changes, and undo brings it back', () => {+ const { editor, pageId } = setup()+ const sticky = editor.createStickyNote(pageId, { x: 0, y: 0 })+ const { body } = sublayers(editor, sticky)+ editor.graph.updateNode(sticky.id, { fillStyleId: 'fill-style' })+ editor.graph.updateNode(body.id, { textStyleId: 'text-style' })+ editor.setStickyColor([sticky.id], STICKY_COLORS.pink)+ editor.setStickyTextSize([sticky.id], 'large')+ expect(editor.graph.getNode(sticky.id)?.fillStyleId).toBeNull()+ expect(editor.graph.getNode(body.id)?.textStyleId).toBeNull()+ editor.undo.undo()+ editor.undo.undo()+ expect(editor.graph.getNode(sticky.id)?.fillStyleId).toBe('fill-style')+ expect(editor.graph.getNode(body.id)?.textStyleId).toBe('text-style')+ })})diff --git a/packages/core/tests/editor/text/typeface.test.ts b/packages/core/tests/editor/text/typeface.test.tsindex 9b0831c37..7a8587fc1 100644--- a/packages/core/tests/editor/text/typeface.test.ts+++ b/packages/core/tests/editor/text/typeface.test.ts@@ -3,7 +3,11 @@ import { describe, expect, test } from 'bun:test'import { expectDefined } from '#core-tests/helpers/assert'import { createEditor } from '@open-pencil/core'-import { createSticky, shapeWithTextLabel, stickySublayers } from '@open-pencil/scene-graph/generated'+import {+ createSticky,+ shapeWithTextLabel,+ stickySublayers+} from '@open-pencil/scene-graph/generated'function setup() {const editor = createEditor({ loadFont: () => Promise.resolve(null) })@@ -20,4 +24,13 @@ describe('typefaces of generated text', () => {expect(shapeWithTextLabel(editor.graph, shape)?.fontFamily).toBe('Roboto Mono')expect(stickySublayers(editor.graph, sticky)?.body.fontFamily).toBe('Roboto Mono')})++ test('a typeface leaves the text style it replaces', async () => {+ const { editor, pageId } = setup()+ const sticky = createSticky(editor.graph, pageId, {})+ const body = expectDefined(stickySublayers(editor.graph, sticky)).body+ editor.graph.updateNode(body.id, { textStyleId: 'text-style' })+ await editor.setGeneratedTextTypeface([sticky.id], 'technical')+ expect(editor.graph.getNode(body.id)?.textStyleId).toBeNull()+ })})diff --git a/packages/core/tests/figma-api/paints.test.ts b/packages/core/tests/figma-api/paints.test.tsindex cb8e1c7b8..9ccf25ecf 100644--- a/packages/core/tests/figma-api/paints.test.ts+++ b/packages/core/tests/figma-api/paints.test.ts@@ -391,3 +391,22 @@ describe('paint types', () => {])})})++describe('a layer with paint styles', () => {+ const RED = { type: 'SOLID' as const, color: { r: 1, g: 0, b: 0 } }++ test('leaves the fill style when a plugin sets its fills, and keeps the stroke style', () => {+ const { graph, figma } = api()+ const rectangle = figma.createRectangle()+ rectangle.strokes = [RED]+ graph.updateNode(rectangle.id, { fillStyleId: 'style:fill', strokeStyleId: 'style:stroke' })++ // A stroke style holds paints only, so the weight is not one of its fields.+ rectangle.strokeWeight = 3+ rectangle.fills = [RED]+ expect(graph.getNode(rectangle.id)).toMatchObject({+ fillStyleId: null,+ strokeStyleId: 'style:stroke'+ })+ })+})diff --git a/packages/core/tests/io/formats/fig/export/shared-style-export.test.ts b/packages/core/tests/io/formats/fig/export/shared-style-export.test.tsindex d2157c1db..2b22994de 100644--- a/packages/core/tests/io/formats/fig/export/shared-style-export.test.ts+++ b/packages/core/tests/io/formats/fig/export/shared-style-export.test.ts@@ -10,6 +10,49 @@ beforeAll(async () => {await initCodec()})+test('variable-backed text styles survive repeated saves and reopening', async () => {+ let graph = new SceneGraph()+ const page = graph.getPages()[0]+ const collection = graph.createCollection('Typography')+ const size = graph.createVariable('Display size', 'FLOAT', collection.id, 48)+ const tracking = graph.createVariable('Display tracking', 'FLOAT', collection.id, -0.96)+ const definition = graph.createNode('TEXT', page.id, {+ name: 'Display/Large',+ sharedStyleType: 'TEXT',+ internalOnly: true,+ fontSize: 48,+ letterSpacing: { value: -0.96, unit: 'PIXELS' },+ boundVariables: { fontSize: size.id, letterSpacing: tracking.id }+ })+ definition.source.id = 'style:display-large'+ const target = graph.createNode('TEXT', page.id, { name: 'Sample', text: 'Display sample' })+ graph.updateNode(target.id, {+ fontSize: 48,+ letterSpacing: { value: -0.96, unit: 'PIXELS' },+ boundVariables: { fontSize: size.id, letterSpacing: tracking.id },+ textStyleId: definition.source.id+ })++ for (let save = 0; save < 3; save++) {+ const saved = await exportFigFile(graph)+ const parsed = parseFigBuffer(saved.slice().buffer)+ const record = parsed.nodeChanges.find((node) => node.name === 'Sample')+ expect(record?.styleIdForText?.guid).toBeDefined()+ graph = await parseFigFile(saved.slice().buffer)+ const sample = [...graph.nodes.values()].find((node) => node.name === 'Sample')+ expect(sample).toBeDefined()+ expect(+ getSharedStyles(graph, 'text').find((style) => style.id === sample?.textStyleId)?.name+ ).toBe('Display/Large')+ expect(sample?.fontSize).toBe(48)+ expect(sample?.letterSpacing?.unit).toBe('PIXELS')+ expect(sample?.letterSpacing?.value).toBeCloseTo(-0.96)+ expect(Object.keys(sample?.boundVariables ?? {}).sort()).toEqual(['fontSize', 'letterSpacing'])+ // Force a patched write as well as the first full export.+ if (sample) graph.updateNode(sample.id, { text: `Display sample ${save}` })+ }+})+test('exports shared styles once even when present in a normal page subtree', async () => {await initCodec()const graph = new SceneGraph()diff --git a/packages/fig/src/node-change/variable/bindings.ts b/packages/fig/src/node-change/variable/bindings.tsindex 029883230..16699e5f3 100644--- a/packages/fig/src/node-change/variable/bindings.ts+++ b/packages/fig/src/node-change/variable/bindings.ts@@ -10,7 +10,7 @@ import type {TextBindableField,TextBoundVariables} from '@open-pencil/scene-graph'-import { isNumericVariableBindingField } from '@open-pencil/scene-graph/variables'+import { boundNumberValue, isNumericVariableBindingField } from '@open-pencil/scene-graph/variables'import { cloneRecord } from '../clone'import { linearVariableExpression } from './expression'@@ -346,5 +346,7 @@ export function resolvedNumericBindingUpdate(): Partial<SceneNode> | undefined {if (field === 'opacity')return { opacity: Math.max(0, Math.min(1, value * OPACITY_UNIT_PER_PERCENT)) }- return isNumericVariableBindingField(field) ? { [field]: value } : undefined+ return isNumericVariableBindingField(field)+ ? { [field]: boundNumberValue(field, value) }+ : undefined}diff --git a/packages/fig/tests/document/bindings/paint.test.ts b/packages/fig/tests/document/bindings/paint.test.tsindex 64c25ac2e..974766beb 100644--- a/packages/fig/tests/document/bindings/paint.test.ts+++ b/packages/fig/tests/document/bindings/paint.test.ts@@ -45,6 +45,7 @@ test('a bound stroke follows the same rule', () => {a: 0.4})const node = graph.createNode('RECTANGLE', graph.getPages()[0].id, {+ strokeStyleId: 'style:line',strokes: [{type: 'SOLID',@@ -60,4 +61,13 @@ test('a bound stroke follows the same rule', () => {applyDocumentPaintBindings(graph, [node])expect(node.strokes[0].color).toEqual({ r: 0, g: 0, b: 0, a: 1 })expect(node.strokes[0].opacity).toBeCloseTo(0.4)+ expect(node.strokeStyleId).toBe('style:line')+})++test('resolving a bound color preserves the saved fill style assignment', () => {+ const { graph, node } = setup(0.2, 1)+ graph.updateNode(node.id, { fillStyleId: 'style:accent' })+ applyDocumentPaintBindings(graph, [node])+ expect(node.fills[0].opacity).toBeCloseTo(0.2)+ expect(node.fillStyleId).toBe('style:accent')})diff --git a/packages/scene-graph/src/graph.ts b/packages/scene-graph/src/graph.tsindex 267c085b1..be900c883 100644--- a/packages/scene-graph/src/graph.ts+++ b/packages/scene-graph/src/graph.ts@@ -23,7 +23,6 @@ import Matrix from './matrix'import { CONTAINER_TYPES, createDefaultNode } from './node-defaults'import { updateNodePreview, type NodePreviewObserver } from './preview'import type { Color, Rect, Vector } from './primitives'-import { styleDetachmentChanges } from './shared-styles'import { markSourceFieldsEdited } from './source-metadata'import { invalidateTextCaches } from './text/picture'import type {@@ -519,6 +518,10 @@ export class SceneGraph {if (appliedChanges) this.emitter.emit('node:previewUpdated', id, appliedChanges)}+ /**+ * Writes fields as given. Edits detach the shared styles whose fields they change before+ * they get here (`styleDetachmentChanges`); resolving bindings or loading a file does not.+ */updateNode(id: string, changes: Partial<SceneNode>): void {if (this.scopeDepths.preview > 0) {this.updateNodePreview(id, changes)@@ -527,9 +530,7 @@ export class SceneGraph {const node = this.nodes.get(id)if (!node) return- const defined = omitBy(changes, isUndefined)- const detached = omitBy(styleDetachmentChanges(node, defined), isUndefined)- this.applyNodeChanges(node, this.sizedChanges(node, detached))+ this.applyNodeChanges(node, this.sizedChanges(node, omitBy(changes, isUndefined)))}/** A size set from outside layout, with what it also sets on a generated frame. */diff --git a/packages/scene-graph/src/shared-styles.ts b/packages/scene-graph/src/shared-styles.tsindex bbc04d0c2..2dc327075 100644--- a/packages/scene-graph/src/shared-styles.ts+++ b/packages/scene-graph/src/shared-styles.ts@@ -1,10 +1,13 @@+import { isEqual, omit } from 'es-toolkit'+import type { SceneGraph } from './graph'import type {CharacterStyleOverride,SceneNode,SharedStyle,SharedStyleKind,- SharedStyleType+ SharedStyleType,+ Stroke} from './types'const STYLE_REF_KEYS = {@@ -96,6 +99,22 @@ export function getSharedStyles(graph: SceneGraph, kind: SharedStyleKind): Sharereturn styles.sort((left, right) => left.name.localeCompare(right.name))}+/** What a stroke draws along beside its paint: the layer's, not its stroke style's. */+const STROKE_LINE_KEYS = ['weight', 'align', 'cap', 'join', 'dashPattern'] as const++/**+ * Whether new strokes only change how their lines run, keeping every paint. A stroke style gives+ * paints only, so such a write keeps it; any other strokes write leaves it, as setting even the+ * same paints does in Figma (live-verified).+ */+function restylesStrokeLines(current: readonly Stroke[], next: readonly Stroke[]): boolean {+ const paints = (strokes: readonly Stroke[]) =>+ strokes.map((stroke) => omit(stroke, STROKE_LINE_KEYS))+ const lines = (strokes: readonly Stroke[]) =>+ strokes.map((stroke) => STROKE_LINE_KEYS.map((key) => stroke[key]))+ return isEqual(paints(current), paints(next)) && !isEqual(lines(current), lines(next))+}+export function styleDetachmentChanges(node: SceneNode,changes: Partial<SceneNode>@@ -104,7 +123,10 @@ export function styleDetachmentChanges(for (const [kind, fields] of Object.entries(SHARED_STYLE_FIELDS)) {const reference = STYLE_REF_KEYS[kind as SharedStyleKind]if (reference in changes || !node[reference]) continue- if (fields.some((field) => field in changes)) next[reference] = null+ if (!fields.some((field) => field in changes)) continue+ if (kind === 'stroke' && changes.strokes && restylesStrokeLines(node.strokes, changes.strokes))+ continue+ next[reference] = null}// A face named for another family, weight, or slant names none; the new one takes its own name.const changesFace = FACE_KEYS.some((key) => key in changes && changes[key] !== node[key])diff --git a/packages/scene-graph/src/variables/bindings.ts b/packages/scene-graph/src/variables/bindings.tsindex e31809387..c443d9b93 100644--- a/packages/scene-graph/src/variables/bindings.ts+++ b/packages/scene-graph/src/variables/bindings.ts@@ -47,7 +47,7 @@ export function assignVariableBindingUnits(const TEXT_LENGTH_FIELDS: ReadonlySet<string> = new Set(['lineHeight', 'letterSpacing'])/** A bound number as the field stores it. */-function boundValue(field: string, value: number): number | TextLength {+export function boundNumberValue(field: string, value: number): number | TextLength {return TEXT_LENGTH_FIELDS.has(field) ? pixelLength(value) : value}@@ -70,7 +70,7 @@ export function resolvedNumericBindings(const scale = node.variableBindingScales[field] ?? 1const effective = value * scaleif (!Number.isFinite(effective)) continue- const next = boundValue(+ const next = boundNumberValue(field,field === 'opacity' ? Math.max(0, Math.min(1, effective)) : effective)@@ -126,7 +126,7 @@ export function resolvedRunBindings(if (!variableId) continueconst value = graph.resolveNumberVariableForNode(node.id, variableId, fallback)if (value === undefined || !Number.isFinite(value)) continue- const next = boundValue(field, value)+ const next = boundNumberValue(field, value)if (isEqual(style[field], next)) continuestyle = { ...style, [field]: next }}diff --git a/packages/scene-graph/tests/variable/binding/shared-styles.test.ts b/packages/scene-graph/tests/variable/binding/shared-styles.test.tsnew file mode 100644index 000000000..2fbedfded--- /dev/null+++ b/packages/scene-graph/tests/variable/binding/shared-styles.test.ts@@ -0,0 +1,37 @@+import { expect, test } from 'bun:test'++import { SceneGraph } from '@open-pencil/scene-graph'+import { reconcileVariableBindings } from '@open-pencil/scene-graph/variables'++/** A text layer with shared styles whose letter spacing a variable drives. */+function styledText() {+ const graph = new SceneGraph()+ const collection = graph.createCollection('Type')+ const spacing = graph.createVariable('Spacing', 'FLOAT', collection.id, 2)+ const text = graph.createNode('TEXT', graph.getPages()[0].id, {+ text: 'Label',+ textStyleId: 'style:text',+ fillStyleId: 'style:fill'+ })+ graph.bindVariable(text.id, 'letterSpacing', spacing.id)+ return { graph, text }+}++test('resolving bindings keeps the shared styles', () => {+ const { graph, text } = styledText()+ reconcileVariableBindings(graph)+ expect(graph.getNode(text.id)).toMatchObject({+ letterSpacing: { value: 2, unit: 'PIXELS' },+ textStyleId: 'style:text',+ fillStyleId: 'style:fill'+ })+})++test('a graph write keeps the styles, which only an edit leaves', () => {+ const { graph, text } = styledText()+ graph.updateNode(text.id, { letterSpacing: { value: 4, unit: 'PIXELS' } })+ expect(graph.getNode(text.id)).toMatchObject({+ textStyleId: 'style:text',+ fillStyleId: 'style:fill'+ })+})diff --git a/tests/engine/tools/modify.test.ts b/tests/engine/tools/modify.test.tsindex 4caaef7c0..82658da4d 100644--- a/tests/engine/tools/modify.test.ts+++ b/tests/engine/tools/modify.test.ts@@ -120,6 +120,20 @@ describe('update_node', () => {expect(expectDefined(figma.getNodeById(rect.id), 'rectangle node').cornerRadius).toBe(12)})++ test("a font size edit leaves the text's text style and keeps its fill style", () => {+ const { figma } = setupToolTest()+ const text = figma.createText()+ figma.graph.updateNode(text.id, { textStyleId: 'style:text', fillStyleId: 'style:fill' })++ getTool('update_node').execute(figma, { id: text.id, font_size: 20 })++ expect(getNodeOrThrow(figma.graph, text.id)).toMatchObject({+ fontSize: 20,+ textStyleId: null,+ fillStyleId: 'style:fill'+ })+ })})describe('set_layout', () => {