Skip to content

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

fix(fig): draw a rescaled instance's vector at the instance size after reopening (#1268)

Niraj Sangani66e315ab1d74
diff --git a/changes/1268/fixed.md b/changes/1268/fixed.md
new file mode 100644
index 000000000..34809e710
--- /dev/null
+++ b/changes/1268/fixed.md
@@ -0,0 +1 @@
+- A rescaled instance of a component with a vector shape draws that shape at the instance size after the file is reopened, instead of at the component's size.
diff --git a/packages/core/tests/io/formats/fig/export/rescaled-vector-instance.test.ts b/packages/core/tests/io/formats/fig/export/rescaled-vector-instance.test.ts
new file mode 100644
index 000000000..c3f25f849
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/export/rescaled-vector-instance.test.ts
@@ -0,0 +1,172 @@
+import { expect, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+
+import { createEditor } from '@open-pencil/core/editor'
+import { FigmaAPI } from '@open-pencil/core/figma-api'
+import { exportFigFile } from '@open-pencil/core/io/formats/fig'
+import { renderNodesToSVG } from '@open-pencil/core/io/formats/svg'
+import { materializeDocument, parseFigBuffer } from '@open-pencil/fig'
+import { derivedSymbolDataOf } from '@open-pencil/fig/instance-overrides'
+import { encodePathCommandsBlob } from '@open-pencil/fig/node-change'
+import { initCodec } from '@open-pencil/kiwi/fig/codec'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+const RED = { r: 1, g: 0, b: 0, a: 1 }
+
+const SQUARE = [
+ [0, 0],
+ [20, 0],
+ [20, 20],
+ [0, 20]
+] as const
+const DIAMOND = [
+ [10, 0],
+ [20, 10],
+ [10, 20],
+ [0, 10]
+] as const
+
+/** A closed outline through `points`; the encoder flips y, as glyph outlines are y-up. */
+function outlineBlob(points: readonly (readonly [number, number])[]): Uint8Array {
+ return encodePathCommandsBlob([
+ ...points.map(([x, y], index) => ({ type: index === 0 ? ('M' as const) : ('L' as const), x, y: -y })),
+ { type: 'Z' as const }
+ ])
+}
+
+interface Variant {
+ regionFills: boolean
+ painted: boolean
+ geometryOnly: boolean
+ strokeOutline: boolean
+ // The file also saved the instance's own fill outline, already at the placed size.
+ savedDerived?: boolean
+}
+
+async function rescaledInstance({
+ regionFills,
+ painted,
+ geometryOnly,
+ strokeOutline,
+ savedDerived
+}: Variant) {
+ const graph = new SceneGraph()
+ createEditor({ graph })
+ const api = new FigmaAPI(graph)
+ const component = api.createComponent()
+ component.resize(24, 24)
+ const vector = api.createVector()
+ component.appendChild(vector)
+ vector.x = 2
+ vector.y = 2
+ vector.resize(20, 20)
+ await vector.setVectorNetworkAsync({
+ vertices: [
+ { x: 0, y: 0 },
+ { x: 20, y: 0 },
+ { x: 20, y: 20 },
+ { x: 0, y: 20 }
+ ],
+ segments: [0, 1, 2, 3].map((i) => ({ start: i, end: (i + 1) % 4 })),
+ regions: [
+ { windingRule: 'NONZERO', loops: [[0, 1, 2, 3]], ...(regionFills ? { fills: [] } : {}) }
+ ]
+ } as never)
+ // The fill outline a file saves with the component, at its size. Set on the layer itself: the
+ // Plugin API's fills setter would also clear the regions' own paints.
+ graph.updateNode(vector.id, {
+ fillGeometry: [{ windingRule: 'NONZERO', commandsBlob: outlineBlob(SQUARE) }],
+ ...(painted ? { fills: [{ type: 'SOLID', color: RED, opacity: 1, visible: true }] } : {})
+ })
+ // A vector the file saved as outlines only has no path of its own to redraw from.
+ if (geometryOnly) graph.updateNode(vector.id, { vectorNetwork: null })
+ if (strokeOutline) {
+ // Outlines of a stroke the file saved, drawn at the component's size. They are a diamond, not
+ // the fill's square, so the stroke has coordinates of its own to check.
+ const strokeGeometry = [{ windingRule: 'NONZERO' as const, commandsBlob: outlineBlob(DIAMOND) }]
+ graph.updateNode(vector.id, {
+ strokes: [
+ {
+ type: 'SOLID',
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ opacity: 1,
+ visible: true,
+ weight: 2,
+ align: 'CENTER'
+ }
+ ],
+ strokeGeometry
+ })
+ }
+ const instance = component.createInstance()
+ instance.rescale(16 / 24)
+
+ await initCodec()
+ const bytes = await exportFigFile(graph)
+ const parsed = parseFigBuffer(bytes.slice().buffer as ArrayBuffer)
+ if (savedDerived) {
+ // Outlines the file saved for the instance: a triangle at the placed size, which must be
+ // taken as it is and not scaled down a second time like the component's inherited ones.
+ // The encoder flips y, as glyph outlines are y-up, so y is given negated.
+ const savedBlob = parsed.blobs.push(
+ encodePathCommandsBlob([
+ { type: 'M', x: 0, y: 0 },
+ { type: 'L', x: 10, y: 0 },
+ { type: 'L', x: 10, y: -10 },
+ { type: 'Z' }
+ ])
+ )
+ const instanceChange = expectDefined(parsed.nodeChanges.find((nc) => nc.type === 'INSTANCE'))
+ const vectorChange = expectDefined(parsed.nodeChanges.find((nc) => nc.type === 'VECTOR'))
+ const entry = expectDefined(
+ derivedSymbolDataOf(instanceChange).find(
+ (e) => e.guidPath?.guids?.[0]?.localID === vectorChange.guid?.localID
+ )
+ )
+ entry.fillGeometry = [{ windingRule: 'NONZERO', commandsBlob: savedBlob - 1 }]
+ }
+ const reopened = materializeDocument(parsed.nodeChanges, parsed.blobs, { derivedBounds: true })
+ const reopenedInstance = expectDefined(
+ [...reopened.graph.nodes.values()].find((node) => node.type === 'INSTANCE')
+ )
+ const page = expectDefined(reopened.graph.getPages()[0])
+ return expectDefined(renderNodesToSVG(reopened.graph, page.id, [reopenedInstance.id]))
+}
+
+const variants: Variant[] = [
+ { regionFills: false, painted: false, geometryOnly: false, strokeOutline: false },
+ { regionFills: true, painted: false, geometryOnly: false, strokeOutline: false },
+ { regionFills: true, painted: true, geometryOnly: false, strokeOutline: false },
+ { regionFills: true, painted: true, geometryOnly: true, strokeOutline: false },
+ { regionFills: true, painted: true, geometryOnly: false, strokeOutline: true },
+ {
+ regionFills: true,
+ painted: true,
+ geometryOnly: false,
+ strokeOutline: false,
+ savedDerived: true
+ }
+]
+
+for (const variant of variants) {
+ test(`a rescaled instance keeps its vector at the instance size after reopening (${JSON.stringify(variant)})`, async () => {
+ const svg = await rescaledInstance(variant)
+ if (variant.savedDerived) {
+ // The saved outline replaces the inherited one and keeps its own size: not 20 (the
+ // component's), not 13.33 (the inherited one scaled), and not 6.67 (scaled twice).
+ expect(svg).toContain('L10 0L10 10')
+ expect(svg).not.toContain('L20 0')
+ expect(svg).not.toContain('L13.33 0')
+ expect(svg).not.toContain('L6.67 0')
+ return
+ }
+ expect(svg).toContain('L13.33 0L13.33 13.33')
+ expect(svg).not.toContain('L20 0')
+ if (variant.strokeOutline) {
+ // The stroke's own outline, a diamond, is scaled by itself and not taken from the fill.
+ expect(svg).toContain('L13.33 6.67')
+ expect(svg).not.toContain('L20 10')
+ }
+ })
+}
diff --git a/packages/core/tests/io/formats/fig/instance/inherited-outline-scale.test.ts b/packages/core/tests/io/formats/fig/instance/inherited-outline-scale.test.ts
new file mode 100644
index 000000000..738905a47
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/instance/inherited-outline-scale.test.ts
@@ -0,0 +1,65 @@
+import { expect, test } from 'bun:test'
+
+import { guid } from '#core-tests/helpers/fig/guid'
+
+import { interpretInstance, materializeInstance } from '@open-pencil/fig/instance-overrides'
+import { encodePathCommandsBlob } from '@open-pencil/fig/node-change'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { SceneGraph } from '@open-pencil/scene-graph'
+import { geometryBlobBounds } from '@open-pencil/scene-graph/geometry'
+
+// A 20 x 20 outline, as the component saved it (the encoder flips y).
+const OUTLINE = encodePathCommandsBlob([
+ { type: 'M', x: 0, y: 0 },
+ { type: 'L', x: 20, y: 0 },
+ { type: 'L', x: 20, y: -20 },
+ { type: 'L', x: 0, y: -20 },
+ { type: 'Z' }
+])
+
+/** The outline's width after the instance, placed at `placed` and scaled by `uniform`, is read back. */
+function reopenedOutlineWidth(uniform: number, placed: number, constraint: string): number {
+ const changes = [
+ { guid: guid(1), type: 'SYMBOL', size: { x: 24, y: 24 } },
+ {
+ guid: guid(2),
+ type: 'VECTOR',
+ parentIndex: { guid: guid(1), position: '!' },
+ size: { x: 20, y: 20 },
+ transform: { m00: 1, m01: 0, m02: 2, m10: 0, m11: 1, m12: 2 },
+ horizontalConstraint: constraint,
+ verticalConstraint: constraint,
+ fillGeometry: [{ commandsBlob: 0, windingRule: 'NONZERO' }]
+ },
+ {
+ guid: guid(3),
+ type: 'INSTANCE',
+ size: { x: placed, y: placed },
+ symbolData: { symbolID: guid(1), uniformScaleFactor: uniform }
+ }
+ ] as NodeChange[]
+ const occurrence = interpretInstance(changes, '1:3')
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const component = graph.createNode('COMPONENT', page.id)
+ const result = materializeInstance(graph, page.id, occurrence, new Map([['1:1', component.id]]), {
+ blobs: [OUTLINE]
+ })
+ const vector = graph.getChildren(result.root.id)[0]
+ const bounds = geometryBlobBounds(vector.fillGeometry)
+ expect(bounds).not.toBeNull()
+ return bounds?.width ?? 0
+}
+
+test('an outline follows the instance scale', () => {
+ expect(reopenedOutlineWidth(2, 48, 'MIN')).toBeCloseTo(40)
+})
+
+test('an outline follows a constraint that scales the vector back to its component size', () => {
+ // Placed at 2x, then resized to the component's own width: SCALE halves the vector again.
+ expect(reopenedOutlineWidth(2, 24, 'SCALE')).toBeCloseTo(20)
+})
+
+test('an outline follows a constraint resize of an instance that is not scaled', () => {
+ expect(reopenedOutlineWidth(1, 36, 'SCALE')).toBeCloseTo(30)
+})
diff --git a/packages/fig/src/instance-overrides/derived-symbol-data.ts b/packages/fig/src/instance-overrides/derived-symbol-data.ts
index 3a42a5494..0a8f1ba26 100644
--- a/packages/fig/src/instance-overrides/derived-symbol-data.ts
+++ b/packages/fig/src/instance-overrides/derived-symbol-data.ts
@@ -15,7 +15,13 @@ export function applyDerivedEntry(target: InstanceOccurrence, entry: DerivedSymb
if (entry.transform) props.transform = structuredClone(entry.transform)
// These are Kiwi geometry records with blob indexes, not SceneGraph geometry arrays.
const { fillGeometry, strokeGeometry, vectorData } = entry
- if (fillGeometry) props.fillGeometry = structuredClone(fillGeometry)
- if (strokeGeometry) props.strokeGeometry = structuredClone(strokeGeometry)
+ if (fillGeometry) {
+ props.fillGeometry = structuredClone(fillGeometry)
+ if (target.inheritedOutlineScale) target.inheritedOutlineScale.fill = { x: 1, y: 1 }
+ }
+ if (strokeGeometry) {
+ props.strokeGeometry = structuredClone(strokeGeometry)
+ if (target.inheritedOutlineScale) target.inheritedOutlineScale.stroke = { x: 1, y: 1 }
+ }
if (vectorData) props.vectorData = structuredClone(vectorData)
}
diff --git a/packages/fig/src/instance-overrides/materialize-instance.ts b/packages/fig/src/instance-overrides/materialize-instance.ts
index 38f7b98e6..b93913cfd 100644
--- a/packages/fig/src/instance-overrides/materialize-instance.ts
+++ b/packages/fig/src/instance-overrides/materialize-instance.ts
@@ -2,6 +2,7 @@ import { isEqual } from 'es-toolkit/predicate'
import type { Paint } from '@open-pencil/kiwi/fig/codec'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import { scaleGeometryPaths } from '@open-pencil/scene-graph/copy'
import {
bindingOverrideField,
setInstanceOverride
@@ -80,6 +81,25 @@ export interface MaterializedInstance {
* Component IDs must refer to existing COMPONENT nodes in the destination graph.
* Occurrence provenance stays in the returned map, not in fabricated FIG metadata.
*/
+/** Outlines inherited from a component are drawn at its size; scale them to the instance's. */
+function scaleInheritedOutlines(
+ converted: ReturnType<typeof nodeChangeToProps>,
+ occurrence: InstanceOccurrence
+): void {
+ const scale = occurrence.inheritedOutlineScale
+ if (!scale) return
+ if (converted.fillGeometry) {
+ converted.fillGeometry = scaleGeometryPaths(converted.fillGeometry, scale.fill.x, scale.fill.y)
+ }
+ if (converted.strokeGeometry) {
+ converted.strokeGeometry = scaleGeometryPaths(
+ converted.strokeGeometry,
+ scale.stroke.x,
+ scale.stroke.y
+ )
+ }
+}
+
/** What an occurrence tree needs beyond the graph it is written into. */
export interface MaterializeInstanceOptions {
blobs?: Uint8Array[]
@@ -116,6 +136,7 @@ export function materializeInstance(
const validate = (current: InstanceOccurrence): void => {
if (prepared.has(current)) throw new Error('Repeated or cyclic instance occurrence')
const converted = nodeChangeToProps(current.properties, blobs, 'occurrence')
+ scaleInheritedOutlines(converted, current)
if (converted.nodeType === 'TEXT' && current.derivedSize) {
converted.derivedLayout = { width: current.derivedSize.x, height: current.derivedSize.y }
}
diff --git a/packages/fig/src/instance-overrides/occurrence/types.ts b/packages/fig/src/instance-overrides/occurrence/types.ts
index 871945ae5..e4e8118cb 100644
--- a/packages/fig/src/instance-overrides/occurrence/types.ts
+++ b/packages/fig/src/instance-overrides/occurrence/types.ts
@@ -27,6 +27,11 @@ export interface InstanceOccurrence {
propertyClaims: InstancePropertyClaim[]
bindingClaims: BoundPropertyClaim[]
derivedSize?: Vector
+ /**
+ * How much larger than the component, per axis, the outlines this occurrence inherits are
+ * drawn. Saved derived outlines are already at the placed size and replace the inherited ones.
+ */
+ inheritedOutlineScale?: { fill: Vector; stroke: Vector }
/** Cumulative scale for unresolved layout-distance variable values. */
layoutScale?: number
/** Per-field declaration-space multipliers, composed as owners expand. */
diff --git a/packages/fig/src/instance-overrides/resize.ts b/packages/fig/src/instance-overrides/resize.ts
index d8e1fa9e7..dc9b1537d 100644
--- a/packages/fig/src/instance-overrides/resize.ts
+++ b/packages/fig/src/instance-overrides/resize.ts
@@ -2,6 +2,7 @@ import type { Vector } from '@open-pencil/kiwi/fig'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import type { InstanceOccurrence } from './occurrence/types'
+import { growInheritedOutlineScale } from './scale/outline'
import { uniformScaleOf } from './types'
export function applyPlacedConstraints(
@@ -65,6 +66,8 @@ export function resizeFreeformOccurrence(
)
const size = { x: x.size, y: y.size }
resizeFreeformOccurrence(child, props.size, size)
+ if (props.type === 'VECTOR' && props.size.x > 0 && props.size.y > 0)
+ growInheritedOutlineScale(child, size.x / props.size.x, size.y / props.size.y)
props.size = size
props.transform = { ...transform, m02: x.position, m12: y.position }
}
diff --git a/packages/fig/src/instance-overrides/scale/layout.ts b/packages/fig/src/instance-overrides/scale/layout.ts
index b818fecf1..c76de61b3 100644
--- a/packages/fig/src/instance-overrides/scale/layout.ts
+++ b/packages/fig/src/instance-overrides/scale/layout.ts
@@ -4,6 +4,7 @@ import { LAYOUT_DISTANCE_FIELDS } from '../fields'
import { occurrences } from '../occurrence/path'
import type { InstanceOccurrence } from '../occurrence/types'
import { uniformScaleOf } from '../types'
+import { growInheritedOutlineScale } from './outline'
import { scaleTextLayout } from './text'
// Distances only: sizing modes, grow factors, and alignment are dimensionless.
@@ -77,6 +78,9 @@ export function applyInstanceLayoutScale(root: InstanceOccurrence, source: NodeC
const value = props[field]
if (typeof value === 'number') props[field] = value * factor
}
+ // Outlines saved with the component are at its size; they follow the instance's scale
+ // unless the saved derived ones, applied after this, replace them.
+ if (props.type === 'VECTOR') growInheritedOutlineScale(node, factor, factor)
if (props.size) props.size = { x: props.size.x * factor, y: props.size.y * factor }
if (props.transform)
props.transform = {
diff --git a/packages/fig/src/instance-overrides/scale/outline.ts b/packages/fig/src/instance-overrides/scale/outline.ts
new file mode 100644
index 000000000..e397cbd0c
--- /dev/null
+++ b/packages/fig/src/instance-overrides/scale/outline.ts
@@ -0,0 +1,22 @@
+import type { InstanceOccurrence } from '../occurrence/types'
+
+/**
+ * A vector's inherited outlines follow every resize its occurrence goes through, per axis: the
+ * instance's uniform scale and then any constraint resize. Saved derived outlines, applied
+ * after both, are already at the placed size and replace them.
+ */
+export function growInheritedOutlineScale(
+ occurrence: InstanceOccurrence,
+ x: number,
+ y: number
+): void {
+ if (x === 1 && y === 1) return
+ const inherited = occurrence.inheritedOutlineScale ?? {
+ fill: { x: 1, y: 1 },
+ stroke: { x: 1, y: 1 }
+ }
+ occurrence.inheritedOutlineScale = {
+ fill: { x: inherited.fill.x * x, y: inherited.fill.y * y },
+ stroke: { x: inherited.stroke.x * x, y: inherited.stroke.y * y }
+ }
+}