AI-native design editor. Open-source Figma alternative.
fix(fig): correct misplaced and missing imported elements (#1286)
Victor Wads620c01af3e42
diff --git a/changes/1286/added.md b/changes/1286/added.mdnew file mode 100644index 000000000..5a275cff1--- /dev/null+++ b/changes/1286/added.md@@ -0,0 +1 @@+- The image fill picker sets a tile's scale and turns Fill, Fit, and Tile images by 90°.diff --git a/changes/1286/fixed.md b/changes/1286/fixed.mdnew file mode 100644index 000000000..8987b7f6b--- /dev/null+++ b/changes/1286/fixed.md@@ -0,0 +1,4 @@+- Tiled images from Figma draw at their own size and tile scale, and Fill, Fit, and Tile images keep their rotation; switching to Crop starts from the Fill framing, as in Figma.+- An image fill's swatch in the properties panel shows its image instead of black.+- Layers flipped vertically keep the flip when saved as `.fig` or copied to Figma.+- Opening a `.fig` file keeps image crops, rotated lines where Figma draws them, icons shown through a nested component property, content-sized layers at their anchor, rotated Hug panels inside their instances, and the colour of a swapped badge.diff --git a/packages/core/src/canvas/fills.ts b/packages/core/src/canvas/fills.tsindex af7a045cc..a0ddce6f6 100644--- a/packages/core/src/canvas/fills.ts+++ b/packages/core/src/canvas/fills.ts@@ -2,6 +2,7 @@ import type { Canvas, Image, Paint } from 'canvaskit-wasm'import type { SceneNode, SceneGraph, Fill } from '@open-pencil/scene-graph'import { invertGradientTransform } from '@open-pencil/scene-graph/gradient'+import Matrix from '@open-pencil/scene-graph/matrix'import type { Color, Rect, Vector } from '@open-pencil/scene-graph/primitives'import { figmaBlendModeToSkia } from './blend'@@ -381,46 +382,51 @@ export function applyGradientFill(}}+/**+ * Maps `img`'s pixels onto `node` as `fill` places them. `size` is the image's own size when `img`+ * is a downscaled preview, so a tile keeps its size. A crop places the image by its transform;+ * Fill, Fit and Tile ignore it, as Figma does, and turn the image by `imageRotation` first.+ */export function makeImageFillLocalMatrix(- r: SkiaRenderer,fill: Fill,node: SceneNode,imgW: number,- imgH: number+ imgH: number,+ size: { width: number; height: number } = { width: imgW, height: imgH }) {const scaleMode = fill.imageScaleMode ?? 'FILL'- if (scaleMode === 'TILE' && !fill.imageTransform) return r.ck.Matrix.identity()-- if ((scaleMode === 'CROP' || scaleMode === 'TILE') && fill.imageTransform) {+ if (scaleMode === 'CROP' && fill.imageTransform) {const t = fill.imageTransform- const transform = [t.m00, t.m01, t.m02, t.m10, t.m11, t.m12, 0, 0, 1]- const inverse = r.ck.Matrix.invert(transform)- if (inverse) {- return r.ck.Matrix.multiply(- r.ck.Matrix.scaled(node.width, node.height),+ const inverse = Matrix.invert([t.m00, t.m01, t.m02, t.m10, t.m11, t.m12, 0, 0, 1])+ if (inverse)+ return Matrix.multiply(+ Matrix.scaled(node.width, node.height),inverse,- r.ck.Matrix.scaled(1 / imgW, 1 / imgH)+ Matrix.scaled(1 / imgW, 1 / imgH))- }}- if (scaleMode === 'FIT') {- const scale = Math.min(node.width / imgW, node.height / imgH)- return r.ck.Matrix.multiply(- r.ck.Matrix.translated((node.width - imgW * scale) / 2, (node.height - imgH * scale) / 2),- r.ck.Matrix.scaled(scale, scale)- )+ const radians = ((fill.imageRotation ?? 0) * Math.PI) / 180+ const cos = Math.abs(Math.cos(radians))+ const sin = Math.abs(Math.sin(radians))+ const turnedW = size.width * cos + size.height * sin+ const turnedH = size.width * sin + size.height * cos+ const turned = Matrix.multiply(+ Matrix.translated(turnedW / 2, turnedH / 2),+ Matrix.rotated(radians),+ Matrix.translated(-size.width / 2, -size.height / 2),+ Matrix.scaled(size.width / imgW, size.height / imgH)+ )+ if (scaleMode === 'TILE') {+ const scale = fill.scale && fill.scale > 0 ? fill.scale : 1+ return Matrix.multiply(Matrix.scaled(scale, scale), turned)}-- const scale = Math.max(node.width / imgW, node.height / imgH)- const sw = node.width / scale- const sh = node.height / scale- const sx = (imgW - sw) / 2- const sy = (imgH - sh) / 2-- return r.ck.Matrix.multiply(- r.ck.Matrix.scaled(node.width / sw, node.height / sh),- r.ck.Matrix.translated(-sx, -sy)+ const fit = scaleMode === 'FIT'+ const scale = (fit ? Math.min : Math.max)(node.width / turnedW, node.height / turnedH)+ return Matrix.multiply(+ Matrix.translated((node.width - turnedW * scale) / 2, (node.height - turnedH * scale) / 2),+ Matrix.scaled(scale, scale),+ turned)}@@ -439,10 +445,13 @@ function setImageShader(const imgW = img.width()const imgH = img.height()const scaleMode = fill.imageScaleMode ?? 'FILL'- const localMatrix =- scaleMode === 'TILE' && !fill.imageTransform && preview- ? r.ck.Matrix.scaled(preview.originalWidth / imgW, preview.originalHeight / imgH)- : makeImageFillLocalMatrix(r, fill, node, imgW, imgH)+ const localMatrix = makeImageFillLocalMatrix(+ fill,+ node,+ imgW,+ imgH,+ preview && { width: preview.originalWidth, height: preview.originalHeight }+ )const tileMode = scaleMode === 'FIT' ? r.ck.TileMode.Decal : r.ck.TileMode.Clampconst shader =scaleMode === 'TILE'diff --git a/packages/fig/src/instance-overrides/interpret.ts b/packages/fig/src/instance-overrides/interpret.tsindex 9ebc82ef1..5271da342 100644--- a/packages/fig/src/instance-overrides/interpret.ts+++ b/packages/fig/src/instance-overrides/interpret.ts@@ -526,6 +526,11 @@ function interpretRoot(): InstanceOccurrence => {const original = raw.symbolData?.symbolIDconst [, sourceComponentOverrideKey] = componentKeys(original)+ // A swapped root draws the replacement's paint, so the old paint's style link goes with it.+ const placed =+ base && effective && !sameGuid(original, effective) && source.type === 'INSTANCE'+ ? omit(source, ['fillPaints', 'styleIdForFill'])+ : sourceconst occurrence: InstanceOccurrence = {sourceId: id,sourceComponentId: original,@@ -537,7 +542,7 @@ function interpretRoot(properties: {// The component's look carries over; its identity does not....(base && omit(base.properties, COMPONENT_IDENTITY_FIELDS)),- ...source,+ ...placed,...(effective && source.symbolData? { symbolData: { ...source.symbolData, symbolID: effective } }: {}),diff --git a/packages/fig/src/node-change/basics.ts b/packages/fig/src/node-change/basics.tsindex b53f8d723..0ddc14c58 100644--- a/packages/fig/src/node-change/basics.ts+++ b/packages/fig/src/node-change/basics.ts@@ -1,4 +1,4 @@-import type { SceneNode } from '@open-pencil/scene-graph'+import { getNodeLocalMatrix, type SceneNode } from '@open-pencil/scene-graph'import type { Matrix } from '@open-pencil/scene-graph/primitives'export function mapToFigmaType(type: SceneNode['type']): string {@@ -44,24 +44,8 @@ export function mapToFigmaType(type: SceneNode['type']): string {}}+/** Figma's matrix for a layer is the Scene Graph's own placement, pivot and reflections included. */export function computeExportTransform(node: SceneNode): Matrix {- const sx = node.flipX ? -1 : 1- const cos = Math.cos((node.rotation * Math.PI) / 180)- const sin = Math.sin((node.rotation * Math.PI) / 180)-- const m00 = cos * sx- const m01 = -sin * sx- const m10 = sin- const m11 = cos- const centerX = node.width / 2- const centerY = node.height / 2-- return {- m00,- m01,- m02: node.x + centerX - m00 * centerX - m01 * centerY,- m10,- m11,- m12: node.y + centerY - m10 * centerX - m11 * centerY- }+ const [m00, m01, m02, m10, m11, m12] = getNodeLocalMatrix(node)+ return { m00, m01, m02, m10, m11, m12 }}diff --git a/packages/fig/src/node-change/convert.ts b/packages/fig/src/node-change/convert.tsindex f1e664304..465bf6c43 100644--- a/packages/fig/src/node-change/convert.ts+++ b/packages/fig/src/node-change/convert.ts@@ -5,6 +5,7 @@ import {DEFAULT_FONT_FAMILY,DEFAULT_STROKE_MITER_LIMIT,DEFAULT_STROKE_WEIGHT,+ getNodeLocalMatrix,OPEN_PENCIL_PLUGIN_DATA,styleToWeight} from '@open-pencil/scene-graph'@@ -253,27 +254,29 @@ export function convertFigmaTransformProps(let y = nc.transform?.m12 ?? 0let rotation = 0let flipX = false- if (nc.transform) {+ const type = mapNodeType(nc.type)+ // Documents and variables are not placed; every layer type is.+ if (nc.transform && type !== 'DOCUMENT' && type !== 'VARIABLE') {const t = nc.transformconst det = t.m00 * t.m11 - t.m01 * t.m10if (det < 0) flipX = truerotation = Math.atan2(t.m10, flipX ? t.m11 : t.m00) * (180 / Math.PI)- // Scene nodes apply their reflection and rotation around the center. Decompose the Figma- // matrix into that same linear transform, then recover the node translation so recomposing- // it produces the original matrix. Reflected rotations need their angle read from the- // second row; treating them as ordinary rotations reverses connector instances by 180°.- const radians = (rotation * Math.PI) / 180- const cos = Math.cos(radians)- const sin = Math.sin(radians)- const centerX = width / 2- const centerY = height / 2- const m00 = flipX ? -cos : cos- const m01 = flipX ? sin : -sin- const m10 = sin- const m11 = cos- x = t.m02 - centerX + m00 * centerX + m01 * centerY- y = t.m12 - centerY + m10 * centerX + m11 * centerY+ // Reflected rotations need their angle read from the second row; treating them as ordinary+ // rotations reverses connector instances by 180°. The Scene Graph's placement at the origin,+ // with its own pivot and reflection, then gives the translation Figma's matrix adds.+ const placed = getNodeLocalMatrix({+ type,+ x: 0,+ y: 0,+ width,+ height,+ rotation,+ flipX,+ flipY: false+ })+ x = t.m02 - placed[2]+ y = t.m12 - placed[5]}return { x, y, width, height, rotation, flipX, flipY: false }@@ -475,12 +478,8 @@ function visibleContainerDerivedLayout((nc.strokePaints?.some((paint) => paint.visible !== false) ?? false)if (layoutMode === 'NONE' || !hasHugAxis || !hasVisiblePaint) return undefined- return {- x: nc.transform?.m02 ?? 0,- y: nc.transform?.m12 ?? 0,- width: nc.size?.x ?? 100,- height: nc.size?.y ?? 100- }+ const { x, y, width, height } = convertFigmaTransformProps(nc)+ return { x, y, width, height }}function minimumSizeDimension(size: NodeChange['minSize'], axis: 'x' | 'y'): number | null {diff --git a/packages/fig/src/node-change/paint.ts b/packages/fig/src/node-change/paint.tsindex 8ca6d28f7..c569b7df3 100644--- a/packages/fig/src/node-change/paint.ts+++ b/packages/fig/src/node-change/paint.ts@@ -36,8 +36,10 @@ export function fillToKiwiPaint(fill: Fill): Paint {}if (fill.gradientTransform) paint.transform = fill.gradientTransformif (fill.imageHash) paint.image = { hash: hexToBytes(fill.imageHash) }- if (fill.imageScaleMode) paint.imageScaleMode = fill.imageScaleMode+ if (fill.imageScaleMode)+ paint.imageScaleMode = fill.imageScaleMode === 'CROP' ? 'STRETCH' : fill.imageScaleModeif (fill.imageTransform) paint.transform = fill.imageTransform+ if (fill.imageRotation) paint.rotation = fill.imageRotationif (fill.sourceNodeId) paint.sourceNodeId = stringToGuid(fill.sourceNodeId)if (fill.scale) paint.scale = fill.scaleif (fill.spacing) paint.spacing = fill.spacing@@ -124,8 +126,14 @@ function applyImagePaintFields(fill: Fill, p: Paint): void {fill.imageHash = img.hash}}- fill.imageScaleMode = (p.imageScaleMode ?? 'FILL') as ImageScaleMode- if (p.transform) fill.imageTransform = convertGradientTransform(p.transform)+ fill.imageScaleMode = (+ p.imageScaleMode === 'STRETCH' ? 'CROP' : (p.imageScaleMode ?? 'FILL')+ ) as ImageScaleMode+ // Figma writes an identity transform for Fill, Fit and Tile, and ignores what a Tile keeps from+ // an earlier crop; only a crop places the image by it.+ if (p.transform && fill.imageScaleMode === 'CROP')+ fill.imageTransform = convertGradientTransform(p.transform)+ if (p.rotation) fill.imageRotation = p.rotation}function applySchemaPaintFields(fill: Fill, p: Paint): void {diff --git a/packages/fig/tests/document/checkpoint.test.ts b/packages/fig/tests/document/checkpoint.test.tsindex 6f088333d..72fe5733b 100644--- a/packages/fig/tests/document/checkpoint.test.ts+++ b/packages/fig/tests/document/checkpoint.test.ts@@ -4,9 +4,81 @@ import { guid } from '#fig-tests/helpers/guid'import { checkpointComponent, restoreComponentCheckpoint } from '#fig/document/component/checkpoint'import { interpretComponent } from '#fig/instance-overrides/interpret'import { materializeInstance } from '#fig/instance-overrides/materialize-instance'+import { deflateSync } from 'fflate'+import { createFigDocumentSession, writeFigArchive } from '@open-pencil/fig'+import {+ createNodeChangesMessage,+ encodeMessage,+ getSchemaBytes,+ initCodec,+ type NodeChange+} from '@open-pencil/kiwi/fig/codec'import { SceneGraph } from '@open-pencil/scene-graph'+test('checkpoint recovery keeps the effective fill of a swapped instance on a lazy page', async () => {+ await initCodec()+ const paint = (r: number): NonNullable<NodeChange['fillPaints']> => [+ { type: 'SOLID', color: { r, g: 1 - r, b: 0, a: 1 }, visible: true, opacity: 1 }+ ]+ const records: NodeChange[] = [+ { guid: guid(0), type: 'DOCUMENT' },+ { guid: guid(1), type: 'CANVAS', parentIndex: { guid: guid(0), position: '!' } },+ {+ guid: guid(2),+ type: 'SYMBOL',+ parentIndex: { guid: guid(1), position: '!' },+ fillPaints: paint(1)+ },+ {+ guid: guid(3),+ type: 'SYMBOL',+ parentIndex: { guid: guid(1), position: '"' },+ fillPaints: paint(0)+ },+ {+ guid: guid(4),+ type: 'SYMBOL',+ parentIndex: { guid: guid(1), position: '#' },+ componentPropDefs: [+ { id: guid(90), type: 'INSTANCE_SWAP', initialValue: { guidValue: guid(2) } }+ ]+ },+ {+ guid: guid(5),+ type: 'INSTANCE',+ parentIndex: { guid: guid(4), position: '!' },+ fillPaints: paint(1),+ symbolData: { symbolID: guid(2) },+ componentPropRefs: [{ defID: guid(90), componentPropNodeField: 'OVERRIDDEN_SYMBOL_ID' }]+ },+ {+ guid: guid(6),+ type: 'INSTANCE',+ parentIndex: { guid: guid(1), position: '$' },+ symbolData: { symbolID: guid(4) },+ componentPropAssignments: [{ defID: guid(90), value: { guidValue: guid(3) } }]+ }+ ]+ const archive = writeFigArchive({+ schemaDeflated: deflateSync(getSchemaBytes()),+ kiwiData: encodeMessage(createNodeChangesMessage(0, 0, records)),+ thumbnailPNG: new Uint8Array(),+ metaJSON: '{}'+ })+ const bytes = new Uint8Array(archive).buffer+ const initial = createFigDocumentSession(bytes)+ const recovered = createFigDocumentSession(+ bytes,+ {},+ { graph: initial.graph, checkpoint: initial.checkpoint() }+ )+ recovered.loadPage('1:1')+ const root = recovered.graph.getNode(new Map(recovered.checkpoint().sources).get('1:6') ?? '')+ if (!root) throw new Error('Missing recovered instance')+ expect(recovered.graph.getChildren(root.id)[0].fills[0].color.g).toBe(1)+})+function setup() {const occurrence = interpretComponent([diff --git a/packages/fig/tests/instance-overrides/swapped-paint-claims.test.ts b/packages/fig/tests/instance-overrides/swapped-paint-claims.test.tsindex 765e742f0..e11ddaaae 100644--- a/packages/fig/tests/instance-overrides/swapped-paint-claims.test.ts+++ b/packages/fig/tests/instance-overrides/swapped-paint-claims.test.ts@@ -3,9 +3,86 @@ import { expect, test } from 'bun:test'import { expectPathError } from '#fig-tests/helpers/errors'import { guid } from '#fig-tests/helpers/guid'import { interpretInstance } from '#fig/instance-overrides/interpret'+import { symbolDataOf } from '#fig/instance-overrides/types'import type { NodeChange } from '@open-pencil/kiwi/fig/codec'+test('a root swap takes the replacement paint but keeps explicit root paint claims', () => {+ const paint = (r: number, g: number): NonNullable<NodeChange['fillPaints']> => [+ { type: 'SOLID', color: { r, g, b: 0, a: 1 }, visible: true, opacity: 1 }+ ]+ const red = paint(1, 0),+ green = paint(0, 1),+ yellow = paint(1, 1)+ const changes: NodeChange[] = [+ { guid: guid(1), type: 'SYMBOL', fillPaints: red },+ { guid: guid(2), type: 'SYMBOL', fillPaints: green },+ {+ guid: guid(3),+ type: 'SYMBOL',+ componentPropDefs: [+ { id: guid(90), type: 'INSTANCE_SWAP', initialValue: { guidValue: guid(1) } }+ ]+ },+ {+ guid: guid(4),+ type: 'INSTANCE',+ parentIndex: { guid: guid(3), position: '!' },+ fillPaints: red,+ symbolData: { symbolID: guid(1) },+ componentPropRefs: [{ defID: guid(90), componentPropNodeField: 'OVERRIDDEN_SYMBOL_ID' }]+ },+ {+ guid: guid(5),+ type: 'INSTANCE',+ symbolData: { symbolID: guid(3) },+ componentPropAssignments: [{ defID: guid(90), value: { guidValue: guid(2) } }]+ }+ ]+ const nested = () => interpretInstance(changes, '1:5').children[0]+ expect(nested().properties.fillPaints).toEqual(green)+ const source = changes[3],+ outer = changes[4]+ const sourceData = symbolDataOf(source),+ outerData = symbolDataOf(outer)+ if (!sourceData || !outerData) throw new Error('Missing paint owners')+ source.fillPaints = yellow+ expect(nested().properties.fillPaints).toEqual(green)+ source.fillPaints = []+ expect(nested().properties.fillPaints).toEqual(green)+ sourceData.symbolOverrides = [{ guidPath: { guids: [guid(1)] }, fillPaints: [] }]+ expect(nested().properties.fillPaints).toEqual([])+ sourceData.symbolOverrides = [{ guidPath: { guids: [guid(1)] }, fillPaints: yellow }]+ expect(nested().properties.fillPaints).toEqual(yellow)+ outerData.symbolOverrides = [{ guidPath: { guids: [guid(4)] }, fillPaints: [] }]+ expect(nested().properties.fillPaints).toEqual([])+ sourceData.symbolOverrides = []+ outerData.symbolOverrides = []+ source.fillPaints = yellow+ outer.componentPropAssignments = []+ expect(nested().properties.fillPaints).toEqual(yellow)+ changes.push(+ { guid: guid(6), type: 'SYMBOL', fillPaints: [] },+ {+ guid: guid(7),+ type: 'INSTANCE',+ symbolData: { symbolID: guid(3) },+ componentPropAssignments: [{ defID: guid(90), value: { guidValue: guid(2) } }]+ },+ {+ guid: guid(8),+ type: 'INSTANCE',+ symbolData: { symbolID: guid(7) },+ componentPropAssignments: [{ defID: guid(90), value: { guidValue: guid(6) } }]+ }+ )+ expect(interpretInstance(changes, '1:8').children[0].properties.fillPaints).toEqual([])+ changes[7].componentPropAssignments = [{ defID: guid(90), value: { guidValue: guid(1) } }]+ expect(interpretInstance(changes, '1:8').children[0].properties.fillPaints).toEqual(yellow)+ sourceData.symbolOverrides = [{ guidPath: { guids: [guid(1)] }, fillPaints: yellow }]+ expect(interpretInstance(changes, '1:8').children[0].properties.fillPaints).toEqual(yellow)+})+test('binding swap ignores known removed-child paint claims without discarding unswapped source claims', () => {const changes = [{ guid: guid(1), type: 'SYMBOL' },@@ -102,3 +179,40 @@ test('binding swap ignores known removed-child paint claims without discarding u[])})++test('a root swap drops the old fill style link along with the old paint', () => {+ const paint = (g: number): NonNullable<NodeChange['fillPaints']> => [+ { type: 'SOLID', color: { r: 1 - g, g, b: 0, a: 1 }, visible: true, opacity: 1 }+ ]+ const todoStyle = { guid: guid(80) },+ doneStyle = { guid: guid(81) }+ const changes: NodeChange[] = [+ { guid: guid(1), type: 'SYMBOL', fillPaints: paint(0), styleIdForFill: todoStyle },+ { guid: guid(2), type: 'SYMBOL', fillPaints: paint(1), styleIdForFill: doneStyle },+ {+ guid: guid(3),+ type: 'SYMBOL',+ componentPropDefs: [+ { id: guid(90), type: 'INSTANCE_SWAP', initialValue: { guidValue: guid(1) } }+ ]+ },+ {+ guid: guid(4),+ type: 'INSTANCE',+ parentIndex: { guid: guid(3), position: '!' },+ fillPaints: paint(0),+ styleIdForFill: todoStyle,+ symbolData: { symbolID: guid(1) },+ componentPropRefs: [{ defID: guid(90), componentPropNodeField: 'OVERRIDDEN_SYMBOL_ID' }]+ },+ {+ guid: guid(5),+ type: 'INSTANCE',+ symbolData: { symbolID: guid(3) },+ componentPropAssignments: [{ defID: guid(90), value: { guidValue: guid(2) } }]+ }+ ]+ const badge = interpretInstance(changes, '1:5').children[0].properties+ expect(badge.fillPaints).toEqual(paint(1))+ expect(badge.styleIdForFill).toEqual(doneStyle)+})diff --git a/packages/fig/tests/node-change/index.test.ts b/packages/fig/tests/node-change/index.test.tsindex 546a64b67..5f4bb3100 100644--- a/packages/fig/tests/node-change/index.test.ts+++ b/packages/fig/tests/node-change/index.test.ts@@ -1,5 +1,6 @@import { describe, expect, test } from 'bun:test'+import { computeExportTransform } from '#fig/node-change/basics'import {applyStyleRefsToFields,buildStyleOverrideTable,@@ -16,10 +17,88 @@ import {nodeChangeToProps,setVariableColorResolver} from '#fig/node-change/index'+import { fillToKiwiPaint } from '#fig/node-change/paint'+import { getCompiledSchema, initCodec } from '@open-pencil/kiwi/fig/codec'import type { NodeChange, Paint } from '@open-pencil/kiwi/fig/codec'+import { SceneGraph, getWorldMatrix, TransformMatrix } from '@open-pencil/scene-graph'describe('@open-pencil/fig NodeChange policy', () => {+ test('keeps raw LINE endpoints through reflected parents and exports authored origin pivots', () => {+ const graph = new SceneGraph()+ const parent = graph.createNode('FRAME', graph.getPages()[0].id, {+ x: 10,+ y: 20,+ width: 200,+ height: 100,+ rotation: 90+ })+ for (const flip of [false, true]) {+ const raw: NodeChange = {+ type: 'LINE',+ size: { x: 100, y: 0 },+ transform: {+ m00: 0,+ m01: flip ? 1 : -1,+ m02: 200,+ m10: 1,+ m11: 0,+ m12: 300+ }+ }+ const line = graph.createNode('LINE', parent.id, nodeChangeToProps(raw, []))+ const points = TransformMatrix.mapPoints(getWorldMatrix(line, graph), [0, 0, 100, 0])+ for (const [i, expected] of [-140, 170, -240, 170].entries())+ expect(points[i]).toBeCloseTo(expected)+ const exported = computeExportTransform(line)+ for (const key of ['m00', 'm01', 'm02', 'm10', 'm11', 'm12'] as const)+ expect(exported[key]).toBeCloseTo(raw.transform?.[key] ?? 0)+ }+ const authored = graph.createNode('LINE', parent.id, {+ x: 30,+ y: 40,+ width: 80,+ height: 0,+ rotation: -90,+ flipX: true+ })+ const exported = computeExportTransform(authored)+ expect(exported.m02).toBe(110)+ expect(exported.m12).toBe(40)+ expect(exported.m01).toBeCloseTo(-1)+ expect(exported.m10).toBeCloseTo(-1)+ const rectangle = graph.createNode('RECTANGLE', parent.id, {+ x: 30,+ y: 40,+ width: 80,+ height: 20,+ rotation: 90+ })+ expect(computeExportTransform(rectangle)).toMatchObject({ m02: 80, m12: 10 })+ })++ test('exports a vertically flipped layer as the matrix that places it', () => {+ const graph = new SceneGraph()+ const node = graph.createNode('RECTANGLE', graph.getPages()[0].id, {+ x: 30,+ y: 40,+ width: 80,+ height: 20,+ rotation: 30,+ flipY: true+ })+ const exported = computeExportTransform(node)+ const corners = [0, 0, 80, 0, 80, 20, 0, 20]+ const expected = TransformMatrix.mapPoints(getWorldMatrix(node, graph), corners)+ const reimported = graph.createNode(+ 'RECTANGLE',+ graph.getPages()[0].id,+ nodeChangeToProps({ type: 'RECTANGLE', size: { x: 80, y: 20 }, transform: exported }, [])+ )+ const actual = TransformMatrix.mapPoints(getWorldMatrix(reimported, graph), corners)+ for (const [i, value] of expected.entries()) expect(actual[i]).toBeCloseTo(value)+ })+test('converts normalized text values', () => {expect(convertLineHeight({ value: 120, units: 'PERCENT' }, 20)).toBe(24)expect(convertLetterSpacing({ value: 10, units: 'PERCENT' }, 20)).toBe(2)@@ -38,6 +117,45 @@ describe('@open-pencil/fig NodeChange policy', () => {])})+ test('normalizes raw STRETCH to crop while exporting the actual Kiwi enum', async () => {+ await initCodec()+ const transform = { m00: 2, m01: 0, m02: -0.25, m10: 0, m11: 2, m12: 0.125 }+ const raw: Paint = { type: 'IMAGE', imageScaleMode: 'STRETCH', transform }+ const fill = convertFills([raw])[0]+ expect(fill.imageScaleMode).toBe('CROP')+ expect(fill.imageTransform).toEqual(transform)+ const paint = fillToKiwiPaint(fill)+ expect(paint.imageScaleMode).toBe('STRETCH')+ expect(paint.transform).toEqual(transform)+ const codec = getCompiledSchema()+ expect(() => codec.encodePaint({ ...raw, imageScaleMode: 'CROP' })).toThrow()+ expect(codec.encodePaint(paint)).toEqual(codec.encodePaint({ ...paint, ...raw }))+ expect(+ convertFills([{ type: 'IMAGE', imageScaleMode: 'STRETCH' }])[0].imageTransform+ ).toBeUndefined()+ })++ test('reads a Figma tile by its scale and rotation, not the transform Figma keeps from a crop', () => {+ // As Figma writes a Tile switched from a Crop: the old crop stays, and Figma ignores it.+ const crop = { m00: 0.5, m01: 0, m02: 0.25, m10: 0, m11: 0.5, m12: 0.25 }+ const tile = convertFills([+ { type: 'IMAGE', imageScaleMode: 'TILE', transform: crop, scale: 0.5, rotation: 90 }+ ])[0]+ expect(tile).toMatchObject({ imageScaleMode: 'TILE', scale: 0.5, imageRotation: 90 })+ expect(tile.imageTransform).toBeUndefined()+ expect(fillToKiwiPaint(tile)).toMatchObject({+ imageScaleMode: 'TILE',+ scale: 0.5,+ rotation: 90+ })+ const identity = { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }+ const fill = convertFills([+ { type: 'IMAGE', imageScaleMode: 'FILL', transform: identity, rotation: 0 }+ ])[0]+ expect(fill.imageTransform).toBeUndefined()+ expect(fill.imageRotation).toBeUndefined()+ })+test('normalizes imported paints and effects', () => {expect(convertFills([{ type: 'SOLID' }])[0]).toMatchObject({color: { r: 0, g: 0, b: 0, a: 1 },@@ -128,6 +246,34 @@ describe('@open-pencil/fig NodeChange policy', () => {expect(y + centerY - (sin * centerX + cos * centerY)).toBeCloseTo(transform.m12, 5)})+ test('saved Hug geometry uses the decomposed position for rotated and reflected containers', () => {+ const transforms = [+ { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 },+ { m00: 0, m01: -1, m02: 60, m10: 1, m11: 0, m12: -20 },+ { m00: -1, m01: 0, m02: 80, m10: 0, m11: -1, m12: 40 },+ { m00: -1, m01: 0, m02: 80, m10: 0, m11: 1, m12: 0 },+ { m00: 1, m01: 0, m02: 0, m10: 0, m11: -1, m12: 40 }+ ]+ for (const transform of transforms) {+ const props = nodeChangeToProps(+ {+ type: 'FRAME',+ size: { x: 80, y: 40 },+ transform,+ stackMode: 'VERTICAL',+ stackPrimarySizing: 'RESIZE_TO_FIT',+ fillPaints: [{ type: 'SOLID', color: { r: 1, g: 1, b: 1, a: 1 } }]+ },+ []+ )+ expect(props.x).toBeCloseTo(0)+ expect(props.y).toBeCloseTo(0)+ expect(props.derivedLayout?.x).toBeCloseTo(0)+ expect(props.derivedLayout?.y).toBeCloseTo(0)+ expect(props.derivedLayout).toMatchObject({ width: 80, height: 40 })+ }+ })+test('keeps resolved variable alpha in paint opacity', () => {setVariableColorResolver(() => ({ r: 1, g: 0, b: 0, a: 0.4 }))try {diff --git a/packages/kiwi/src/fig/codec.ts b/packages/kiwi/src/fig/codec.tsindex 8f568896c..f1c546b00 100644--- a/packages/kiwi/src/fig/codec.ts+++ b/packages/kiwi/src/fig/codec.ts@@ -133,6 +133,8 @@ export interface Paint {imageThumbnail?: ImageSourceanimatedImage?: ImageSourceimageScaleMode?: string+ /** Degrees an image turns in Fill, Fit, and Tile; a crop's transform holds its own turn. */+ rotation?: numbersourceNodeId?: GUIDscale?: numberspacing?: numberdiff --git a/packages/scene-graph/src/coordinate.ts b/packages/scene-graph/src/coordinate.tsindex 18ce7ce60..7330e1dde 100644--- a/packages/scene-graph/src/coordinate.ts+++ b/packages/scene-graph/src/coordinate.ts@@ -154,12 +154,18 @@ export function getAbsolutePositionFull(node: SceneNode, graph: SceneGraph) {}}/** Lines retain their origin pivot; other shapes rotate around their center. */-export function getNodeRotationOrigin(node: SceneNode): Vector {+export function getNodeRotationOrigin(node: Pick<SceneNode, 'type' | 'width' | 'height'>): Vector {return node.type === 'LINE' ? { x: 0, y: 0 } : { x: node.width / 2, y: node.height / 2 }}+/** What places a layer in its parent: its position, size, reflection, turn, and pivot. */+export type NodePlacement = Pick<+ SceneNode,+ 'type' | 'x' | 'y' | 'width' | 'height' | 'rotation' | 'flipX' | 'flipY'+>+/** Position can be applied separately by renderers before setting up local opacity layers. */-export function getNodeLocalMatrix(n: SceneNode, position: Vector = n) {+export function getNodeLocalMatrix(n: NodePlacement, position: Vector = n) {let matrix = Matrix.translated(position.x, position.y)if (n.flipX || n.flipY) {matrix = Matrix.multiply(diff --git a/packages/scene-graph/src/images.ts b/packages/scene-graph/src/images.tsindex beb9ec353..e40667891 100644--- a/packages/scene-graph/src/images.ts+++ b/packages/scene-graph/src/images.ts@@ -1,6 +1,8 @@import { sha1 } from '@noble/hashes/legacy.js'import { bytesToHex } from '@noble/hashes/utils.js'+import type { Matrix } from './primitives'+/*** The name an image's bytes are stored under: the hex SHA-1 of the bytes, as Figma names images,* so `.fig` files and the Figma clipboard can carry the name as it is. Documents saved before may@@ -24,3 +26,19 @@ export function imageMimeType(data: Uint8Array): ImageMimeType {if (riff && webp) return 'image/webp'return 'image/png'}++/**+ * The crop that shows an image as Fill does: scaled to cover a `width` × `height` layer and+ * centred. Figma starts a crop from it, as the image-space window a crop's transform holds.+ */+export function coverImageTransform(+ width: number,+ height: number,+ imageWidth: number,+ imageHeight: number+): Matrix {+ const scale = Math.max(width / imageWidth, height / imageHeight)+ const m00 = width / scale / imageWidth+ const m11 = height / scale / imageHeight+ return { m00, m01: 0, m02: (1 - m00) / 2, m10: 0, m11, m12: (1 - m11) / 2 }+}diff --git a/packages/scene-graph/src/instances/assignments.ts b/packages/scene-graph/src/instances/assignments.tsnew file mode 100644index 000000000..a07030414--- /dev/null+++ b/packages/scene-graph/src/instances/assignments.ts@@ -0,0 +1,115 @@+// What enclosing instances assign the component properties that drive a copy's layers.+import type { ComponentPropertyReferenceField, SceneGraph, SceneNode } from '../'++/** SLOT_CONTENT is absent because it drives children, which `ownsSlotContent` keeps instead. */+const PROPERTY_REFERENCE_FIELDS: Partial<Record<ComponentPropertyReferenceField, string>> = {+ VISIBLE: 'visible',+ TEXT: 'text',+ INSTANCE_SWAP: 'componentId'+}++/** Instance links are expected to be shallow; the cap only stops a cycle from hanging sync. */+const INSTANCE_CHAIN_LIMIT = 16++/**+ * Whether this instance's component, or the set it is a variant of, is where `propertyId` is+ * defined. Only a set counts: a component nested in an ordinary component defines its own+ * properties, not the outer one's.+ */+function definesProperty(graph: SceneGraph, instance: SceneNode, propertyId: string): boolean {+ // An instance of an instance links through to the component, so follow the chain to it.+ let component = instance.componentId ? graph.nodes.get(instance.componentId) : undefined+ for (let hops = 0; component?.type === 'INSTANCE' && hops < INSTANCE_CHAIN_LIMIT; hops++) {+ component = component.componentId ? graph.nodes.get(component.componentId) : undefined+ }+ const parent = component?.parentId ? graph.nodes.get(component.parentId) : undefined+ const set = parent?.type === 'COMPONENT_SET' ? parent : undefined+ return [component, set]+ .flatMap((node) => node?.componentPropertyDefinitions ?? [])+ .some((definition) => definition.id === propertyId)+}++/**+ * What the nearest enclosing instance assigns `propertyId`, if any does. An instance assigns its+ * children, not itself, so the walk starts at the parent. A property id belongs to the component+ * that defines it, so the walk stops at an instance of that component even when it assigns+ * nothing; otherwise an outer instance's unrelated property of the same id wins.+ */+function enclosingAssignment(+ graph: SceneGraph,+ node: SceneNode,+ propertyId: string+): string | undefined {+ let current = node.parentId ? graph.nodes.get(node.parentId) : undefined+ while (current) {+ if (current.type === 'INSTANCE') {+ if (Object.hasOwn(current.componentPropertyAssignments, propertyId))+ return current.componentPropertyAssignments[propertyId]+ if (definesProperty(graph, current, propertyId)) return undefined+ }+ current = current.parentId ? graph.nodes.get(current.parentId) : undefined+ }+ return undefined+}++function hasEnclosingAssignment(graph: SceneGraph, node: SceneNode, propertyId: string): boolean {+ return enclosingAssignment(graph, node, propertyId) !== undefined+}++/**+ * A component can gain a property-driven layer after an instance of it exists. Pass 4 leaves a+ * driven field alone, so the fresh clone has to take the enclosing instance's assignment here or+ * it keeps the component's default while every other instance layer shows the assigned value.+ */+export function applyEnclosingAssignments(graph: SceneGraph, clone: SceneNode): void {+ for (const reference of clone.componentPropertyReferences) {+ const field = PROPERTY_REFERENCE_FIELDS[reference.field]+ if (!field) continue+ const value = enclosingAssignment(graph, clone, reference.propertyId)+ if (value === undefined) continue+ if (field === 'visible') graph.updateNode(clone.id, { visible: value === 'true' })+ else if (field === 'text') graph.updateNode(clone.id, { text: value })+ else if (field === 'componentId' && clone.type === 'INSTANCE' && graph.nodes.has(value)) {+ graph.swapInstanceComponent(clone.id, value)+ }+ }+ for (const child of graph.getChildren(clone.id)) applyEnclosingAssignments(graph, child)+}++/**+ * Fields a component property drives on this child. The component states the default, but+ * an enclosing instance's assignment decides the value, so synchronising must not copy the+ * default over it — a page loaded later would otherwise reset the instance to the default.+ */+export function propertyDrivenFields(+ graph: SceneGraph,+ instChild: SceneNode,+ compChild: SceneNode+): Set<string> {+ const driven = new Set<string>()+ for (const reference of compChild.componentPropertyReferences) {+ const field = PROPERTY_REFERENCE_FIELDS[reference.field]+ if (field && hasEnclosingAssignment(graph, instChild, reference.propertyId)) driven.add(field)+ }+ return driven+}++/**+ * The text and visibility enclosing assignments give an existing child whose layer a property+ * drives. A layer linked to a property after the instance was made would otherwise keep what it+ * showed before, since synchronising leaves driven fields alone.+ */+export function assignedFieldValues(+ graph: SceneGraph,+ instChild: SceneNode,+ compChild: SceneNode+): Partial<SceneNode> {+ const values: Partial<SceneNode> = {}+ for (const reference of compChild.componentPropertyReferences) {+ const value = enclosingAssignment(graph, instChild, reference.propertyId)+ if (value === undefined) continue+ if (reference.field === 'TEXT' && instChild.type === 'TEXT') values.text = value+ else if (reference.field === 'VISIBLE') values.visible = value === 'true'+ }+ return values+}diff --git a/packages/scene-graph/src/instances/content-size.ts b/packages/scene-graph/src/instances/content-size.tsindex ddce6697e..5ae04e859 100644--- a/packages/scene-graph/src/instances/content-size.ts+++ b/packages/scene-graph/src/instances/content-size.ts@@ -3,6 +3,8 @@ import { isEqual } from 'es-toolkit/predicate'import type { SceneGraph, SceneNode } from '../'import { TEXT_METRIC_FIELDS, TEXT_SHAPING_FIELDS } from '../fields/text'import { layoutSizing } from '../layout/sizing'+import type { Rect } from '../primitives'+import { resizedChildRect } from '../resize'const METRIC_FIELDS: ReadonlySet<string> = new Set(TEXT_METRIC_FIELDS)@@ -42,15 +44,33 @@ function contentSizedAxes(* its count and the layers it shows rather than to the component's placeholder. Layout measures* those axes; the component's size there would be stale.*/+/** Where synchronization placed a copy, and on which axes the copy keeps that place itself. */+export interface SyncedPlacement {+ placed: Rect+ x: boolean+ y: boolean+}+export function keepOwnContentSize(graph: SceneGraph,updates: Partial<SceneNode>,copy: SceneNode,- source: SceneNode+ source: SceneNode,+ placement?: SyncedPlacement): void {const axes = contentSizedAxes(graph, copy, source, updates)if (axes.width) Reflect.deleteProperty(updates, 'width')if (axes.height) Reflect.deleteProperty(updates, 'height')+ if (!placement) return // An instance root keeps its own position.+ const final = { ...copy, ...updates }+ const anchored = resizedChildRect(+ placement.placed,+ final,+ final.horizontalConstraint,+ final.verticalConstraint+ )+ if (placement.x && final.width !== placement.placed.width) updates.x = anchored.x+ if (placement.y && final.height !== placement.placed.height) updates.y = anchored.y}/**diff --git a/packages/scene-graph/src/instances/fields.ts b/packages/scene-graph/src/instances/fields.tsindex 4f99d678a..733c897c6 100644--- a/packages/scene-graph/src/instances/fields.ts+++ b/packages/scene-graph/src/instances/fields.ts@@ -25,6 +25,7 @@ export const INSTANCE_SYNC_TEXT_PROPS = [/** Fields that belong to another one: overriding the owner keeps them too. */export const INSTANCE_SYNC_FIELD_OWNERS: Readonly<Partial<Record<string, string>>> = {+ fillStyleId: 'fills',styleRuns: 'text',textParagraphs: 'text'}diff --git a/packages/scene-graph/src/instances/main-component.ts b/packages/scene-graph/src/instances/main-component.tsindex 1b155fd2b..56840f265 100644--- a/packages/scene-graph/src/instances/main-component.ts+++ b/packages/scene-graph/src/instances/main-component.ts@@ -17,3 +17,41 @@ export function instanceMainComponent(}return current?.type === 'COMPONENT' ? current : undefined}++/** Root paint claims also protect a nested copy when its enclosing component syncs it. */+export function ownsSelfFillField(target: SceneNode, field: string): boolean {+ const own = target.instanceOverrides.self+ if (field === 'fills' || field === 'fillStyleId') return own.has(field) || own.has('fills')+ // A paint the layer set itself owns its bindings too, bound or not.+ return (+ field.startsWith('boundVariables/fills/') &&+ (own.has(field) || own.has('boundVariables') || own.has('fills'))+ )+}++/** A swapped nested root takes its fill from what it shows, not its template's old component. */+export function sourceWithEffectiveFill(+ graph: SceneGraph,+ source: SceneNode,+ target: SceneNode+): SceneNode {+ if (source.type !== 'INSTANCE' || target.type !== 'INSTANCE') return source+ const original = instanceMainComponent(graph, source)+ const effective = instanceMainComponent(graph, target)+ if (!original || !effective || original.id === effective.id) return source+ const fillBindings = <T>(from: Record<string, T>, to: Record<string, T>): Record<string, T> =>+ Object.fromEntries([+ ...Object.entries(from).filter(([key]) => !key.startsWith('fills/')),+ ...Object.entries(to).filter(([key]) => key.startsWith('fills/'))+ ])+ return {+ ...source,+ fills: effective.fills,+ fillStyleId: effective.fillStyleId,+ boundVariables: fillBindings(source.boundVariables, effective.boundVariables),+ variableBindingScales: fillBindings(+ source.variableBindingScales,+ effective.variableBindingScales+ )+ }+}diff --git a/packages/scene-graph/src/instances/sync.ts b/packages/scene-graph/src/instances/sync.tsindex f9cd87cd8..e4fec62f8 100644--- a/packages/scene-graph/src/instances/sync.ts+++ b/packages/scene-graph/src/instances/sync.ts@@ -1,7 +1,7 @@// Child cloning and property synchronization shared by instance creation, swap, and sync.import { isEqual } from 'es-toolkit/predicate'-import type { ComponentPropertyReferenceField, SceneGraph, SceneNode } from '../'+import type { SceneGraph, SceneNode } from '../'import { cloneNodeProps, copyEffects, copyFills, copyStrokes, copyStyleRuns } from '../copy'import type { NodeCloneMode } from '../copy'import {@@ -13,7 +13,8 @@ import {import { scaleNodeChanges } from '../scaling/node'import { ownsSlotContent, slotPropertyId } from '../slots/frames'import { scaleVariableBindingUnits } from '../variables/units'-import { keepOwnContentSize, remeasureChangedText } from './content-size'+import { applyEnclosingAssignments, assignedFieldValues, propertyDrivenFields } from './assignments'+import { keepOwnContentSize, remeasureChangedText, type SyncedPlacement } from './content-size'import {createInstanceSyncContext,hasUnplacedCopiesBelow,@@ -22,6 +23,7 @@ import {type InstanceSyncContext} from './copies'import { INSTANCE_SYNC_FIELD_OWNERS, INSTANCE_SYNC_FIELDS } from './fields'+import { ownsSelfFillField, sourceWithEffectiveFill } from './main-component'import { PLACEMENT_FIELDS, placedByConstraints } from './placement'import { followVectorGeometry } from './vector-geometry'@@ -136,7 +138,7 @@ function copySyncedFields(copy: SceneNode,source: SceneNode,{ compParent, instParent, factor, skip }: SyncedFieldsInput-): void {+): SyncedPlacement {// In an auto layout flow the layout places the copy, as it placed the component's layer.const placedByLayout = instParent.layoutMode !== 'NONE' && source.layoutPositioning !== 'ABSOLUTE'const placed = placedByLayout@@ -153,8 +155,12 @@ function copySyncedFields(if (isEqual(copy[key], from[key])) continuecopyProp(updates, from, key)}+ // New paints bring their style link, unless the copy keeps a style of its own.+ if (updates.fills)+ updates.fillStyleId = skip('fillStyleId') ? copy.fillStyleId : source.fillStyleIdfollowVectorGeometry(updates, copy, source)remeasureChangedText(updates, copy)+ return { placed, x: !placedByLayout && !skip('x'), y: !placedByLayout && !skip('y') }}export function updateSyncedProps(@@ -167,6 +173,7 @@ export function updateSyncedProps(([key, value]) => !isEqual(target[key as keyof SceneNode], value))) as Partial<SceneNode>+ if (changed.fills && updates.fillStyleId !== undefined) changed.fillStyleId = updates.fillStyleIdif (Object.keys(changed).length) graph.updateNode(target.id, changed)}@@ -222,118 +229,6 @@ export function enclosingInstanceOverrideFields(graph: SceneGraph, node: SceneNoreturn fields}-/** SLOT_CONTENT is absent because it drives children, which `ownsSlotContent` keeps instead. */-const PROPERTY_REFERENCE_FIELDS: Partial<Record<ComponentPropertyReferenceField, string>> = {- VISIBLE: 'visible',- TEXT: 'text',- INSTANCE_SWAP: 'componentId'-}--/** Instance links are expected to be shallow; the cap only stops a cycle from hanging sync. */-const INSTANCE_CHAIN_LIMIT = 16--/**- * Whether this instance's component, or the set it is a variant of, is where `propertyId` is- * defined. Only a set counts: a component nested in an ordinary component defines its own- * properties, not the outer one's.- */-function definesProperty(graph: SceneGraph, instance: SceneNode, propertyId: string): boolean {- // An instance of an instance links through to the component, so follow the chain to it.- let component = instance.componentId ? graph.nodes.get(instance.componentId) : undefined- for (let hops = 0; component?.type === 'INSTANCE' && hops < INSTANCE_CHAIN_LIMIT; hops++) {- component = component.componentId ? graph.nodes.get(component.componentId) : undefined- }- const parent = component?.parentId ? graph.nodes.get(component.parentId) : undefined- const set = parent?.type === 'COMPONENT_SET' ? parent : undefined- return [component, set]- .flatMap((node) => node?.componentPropertyDefinitions ?? [])- .some((definition) => definition.id === propertyId)-}--/**- * What the nearest enclosing instance assigns `propertyId`, if any does. A property id belongs- * to the component that defines it, so the walk stops at an instance of that component even- * when it assigns nothing; otherwise an outer instance's unrelated property of the same id wins.- */-function enclosingAssignment(- graph: SceneGraph,- node: SceneNode,- propertyId: string-): string | undefined {- let current: SceneNode | undefined = node- while (current) {- if (current.type === 'INSTANCE') {- if (Object.hasOwn(current.componentPropertyAssignments, propertyId))- return current.componentPropertyAssignments[propertyId]- if (definesProperty(graph, current, propertyId)) return undefined- }- current = current.parentId ? graph.nodes.get(current.parentId) : undefined- }- return undefined-}--function hasEnclosingAssignment(graph: SceneGraph, node: SceneNode, propertyId: string): boolean {- return enclosingAssignment(graph, node, propertyId) !== undefined-}--/**- * A component can gain a property-driven layer after an instance of it exists. Pass 4 leaves a- * driven field alone, so the fresh clone has to take the enclosing instance's assignment here or- * it keeps the component's default while every other instance layer shows the assigned value.- */-function applyEnclosingAssignments(graph: SceneGraph, clone: SceneNode): void {- for (const reference of clone.componentPropertyReferences) {- const field = PROPERTY_REFERENCE_FIELDS[reference.field]- if (!field) continue- const value = enclosingAssignment(graph, clone, reference.propertyId)- if (value === undefined) continue- if (field === 'visible') graph.updateNode(clone.id, { visible: value === 'true' })- else if (field === 'text') graph.updateNode(clone.id, { text: value })- else if (field === 'componentId' && clone.type === 'INSTANCE' && graph.nodes.has(value)) {- graph.swapInstanceComponent(clone.id, value)- }- }- for (const child of graph.getChildren(clone.id)) applyEnclosingAssignments(graph, child)-}--/**- * Fields a component property drives on this child. The component states the default, but- * an enclosing instance's assignment decides the value, so synchronising must not copy the- * default over it — a page loaded later would otherwise reset the instance to the default.- */-function propertyDrivenFields(- graph: SceneGraph,- instChild: SceneNode,- compChild: SceneNode-): Set<string> {- const driven = new Set<string>()- for (const reference of compChild.componentPropertyReferences) {- const field = PROPERTY_REFERENCE_FIELDS[reference.field]- if (field && hasEnclosingAssignment(graph, instChild, reference.propertyId)) driven.add(field)- }- return driven-}--/**- * The text and visibility enclosing assignments give an existing child whose layer a property- * drives. A layer linked to a property after the instance was made would otherwise keep what it- * showed before, since synchronising leaves driven fields alone.- */-function assignedFieldValues(- graph: SceneGraph,- instChild: SceneNode,- compChild: SceneNode-): Partial<SceneNode> {- const values: Partial<SceneNode> = {}- for (const reference of compChild.componentPropertyReferences) {- const value = enclosingAssignment(graph, instChild, reference.propertyId)- if (value === undefined) continue- if (reference.field === 'TEXT' && instChild.type === 'TEXT') values.text = value- else if (reference.field === 'VISIBLE') values.visible = value === 'true'- }- return values-}-function childBindingProtection(graph: SceneGraph,child: SceneNode,@@ -341,7 +236,8 @@ function childBindingProtection() {const fields = enclosingInstanceOverrideFields(graph, child)fields.push(new Set(overrides.descendants.get(child.id)?.keys()))- return bindingProtection(fields)+ const protectedField = bindingProtection(fields)+ return (field: string) => protectedField(field) || ownsSelfFillField(child, field)}function linkMatchedChild(@@ -566,7 +462,8 @@ export function syncChildren(const driven = propertyDrivenFields(graph, instChild, compChild)const componentScale =(compChild.componentScale * instParent.componentScale) / compParent.componentScale- const source = sourceInTargetCoordinates(compChild, componentScale)+ const effectiveSource = sourceWithEffectiveFill(graph, compChild, instChild)+ const source = sourceInTargetCoordinates(effectiveSource, componentScale)// Which properties a layer serves is the component's to say; a slot or exposed layer// created on the component becomes one in every instance.const updates: Partial<SceneNode> = {@@ -574,14 +471,14 @@ export function syncChildren(componentPropertyReferences: structuredClone(compChild.componentPropertyReferences)}syncBindingFields(instChild, source, updates, protectedField)- copySyncedFields(updates, instChild, source, {+ const placement = copySyncedFields(updates, instChild, source, {compParent,instParent,factor: componentScale / compChild.componentScale,skip: (key) => driven.has(key) || isProtectedSyncField(instChild, key, protectedField)})Object.assign(updates, assignedFieldValues(graph, instChild, compChild))- keepOwnContentSize(graph, updates, instChild, source)+ keepOwnContentSize(graph, updates, instChild, source, placement)updateSyncedProps(graph, instChild, updates)if (diff --git a/packages/scene-graph/src/resize.ts b/packages/scene-graph/src/resize.tsindex d81a97ee8..9387fd90e 100644--- a/packages/scene-graph/src/resize.ts+++ b/packages/scene-graph/src/resize.ts@@ -77,6 +77,18 @@ function resizedInPlace(return { position: placed.position, size }}+/** Keep a placed box's constrained edges or center when its content determines its size. */+export function resizedChildRect(+ placed: Rect,+ size: Pick<Rect, 'width' | 'height'>,+ horizontal: ConstraintType,+ vertical: ConstraintType+): Rect {+ const x = resizedInPlace({ position: placed.x, size: placed.width }, size.width, horizontal)+ const y = resizedInPlace({ position: placed.y, size: placed.height }, size.height, vertical)+ return { x: x.position, y: y.position, width: x.size, height: y.size }+}+/*** A locked aspect ratio holds when exactly one axis follows the parent, as in Figma: that axis* sizes the other. With both axes following the parent, or neither, the ratio gives way.diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.tsindex e986b4311..e8a30035a 100644--- a/packages/scene-graph/src/types.ts+++ b/packages/scene-graph/src/types.ts@@ -174,7 +174,10 @@ export interface Fill {gradientTransform?: GradientTransformimageHash?: stringimageScaleMode?: ImageScaleMode+ /** A crop's image-space window; Fill, Fit and Tile ignore it. */imageTransform?: GradientTransform+ /** Clockwise turn of a Fill, Fit or Tile image, in multiples of 90°; a crop holds its own. */+ imageRotation?: numbersourceNodeId?: stringscale?: numberspacing?: numberdiff --git a/packages/scene-graph/tests/components/property/driven-sync.test.ts b/packages/scene-graph/tests/components/property/driven-sync.test.tsindex 0cb95a9ad..bc686d68f 100644--- a/packages/scene-graph/tests/components/property/driven-sync.test.ts+++ b/packages/scene-graph/tests/components/property/driven-sync.test.ts@@ -1,6 +1,6 @@import { expect, test } from 'bun:test'-import { SceneGraph } from '@open-pencil/scene-graph'+import { applyComponentPropertyValue, SceneGraph } from '@open-pencil/scene-graph'function graphWithAssignedLabel() {const graph = new SceneGraph()@@ -60,6 +60,47 @@ test('synchronizing carries other fields of a property-driven layer', () => {expect(graph.getNode(clone.id)?.opacity).toBe(0.5)})+test('a nested instance takes its visibility from its parent, not its own child assignment', () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const definitions = [+ { id: '207:2', name: 'Visible', type: 'BOOLEAN' as const, defaultValue: 'false' }+ ]+ const inner = graph.createNode('COMPONENT', page.id, {+ componentPropertyDefinitions: definitions+ })+ graph.createNode('RECTANGLE', inner.id, {+ visible: false,+ componentPropertyReferences: [{ propertyId: '207:2', field: 'VISIBLE' }]+ })+ const outer = graph.createNode('COMPONENT', page.id, {+ componentPropertyDefinitions: definitions+ })+ const nested = graph.createInstance(inner.id, outer.id, {+ visible: false,+ componentPropertyReferences: [{ propertyId: '207:2', field: 'VISIBLE' }],+ componentPropertyAssignments: { '207:2': 'false' }+ })+ const instance = graph.createInstance(outer.id, page.id, {+ componentPropertyAssignments: { '207:2': 'true' }+ })+ if (!nested || !instance) throw new Error('Missing nested instance')+ const clone = graph.getChildren(instance.id)[0]+ graph.updateNode(clone.id, { visible: true })+ graph.updateNode(nested.id, { opacity: 0.5 })+ for (const visible of [true, false, true]) {+ applyComponentPropertyValue(graph, instance.id, definitions[0], String(visible))+ graph.syncInstances(outer.id)+ expect(graph.getNode(clone.id)?.visible).toBe(visible)+ expect(graph.getNode(clone.id)?.opacity).toBe(0.5)+ expect(graph.getChildren(clone.id)[0].visible).toBe(false)+ }+ applyComponentPropertyValue(graph, clone.id, definitions[0], 'true')+ graph.syncInstances(inner.id)+ expect(graph.getNode(clone.id)?.visible).toBe(true)+ expect(graph.getChildren(clone.id)[0].visible).toBe(true)+})+/** Property IDs are document-authored strings, so one may collide with an Object prototype key. */test('a property id shared with an Object prototype key is not read as an assignment', () => {const graph = new SceneGraph()diff --git a/packages/scene-graph/tests/components/swapped-fill.test.ts b/packages/scene-graph/tests/components/swapped-fill.test.tsnew file mode 100644index 000000000..3f02a6fb0--- /dev/null+++ b/packages/scene-graph/tests/components/swapped-fill.test.ts@@ -0,0 +1,141 @@+import { expect, test } from 'bun:test'++import { SceneGraph, setInstanceOverride, type SceneNode } from '@open-pencil/scene-graph'++import { expectDefined } from '../helpers/assert'++const solid = (r: number, g: number, b: number): SceneNode['fills'] => [+ { type: 'SOLID', color: { r, g, b, a: 1 }, opacity: 1, visible: true }+]++/**+ * A Row component holding a To do badge, and an instance of Row whose badge is swapped to Done,+ * as a status column swaps its badges. `template` prepares the badge inside Row.+ */+function swappedBadge(template?: (graph: SceneGraph, badge: SceneNode) => void) {+ const graph = new SceneGraph()+ const page = graph.getPages()[0].id+ const todo = graph.createNode('COMPONENT', page, {+ fills: solid(1, 0.55, 0),+ fillStyleId: 'style-todo',+ boundVariables: { 'fills/0/color': 'orange' },+ variableBindingScales: { 'fills/0/color': 1 }+ })+ const done = graph.createNode('COMPONENT', page, {+ fills: solid(0.1, 0.75, 0.3),+ fillStyleId: 'style-done',+ boundVariables: { 'fills/0/color': 'green' },+ variableBindingScales: { 'fills/0/color': 2 }+ })+ const row = graph.createNode('COMPONENT', page)+ const badge = expectDefined(+ graph.createInstance(todo.id, row.id, { x: 17, visible: false, boundVariables: { opacity: 'faded' } })+ )+ template?.(graph, badge)+ const outer = expectDefined(graph.createInstance(row.id, page))+ const target = graph.getChildren(outer.id)[0]+ const swap = (component: SceneNode) => {+ graph.updateNode(target.id, { componentId: component.id })+ setInstanceOverride(outer.instanceOverrides, outer.id, target.id, 'componentId', component.id)+ graph.syncInstance(outer.id)+ }+ swap(done)+ return { graph, todo, done, badge, outer, target, swap }+}++test('a swapped badge takes the fill, style and bindings its new component gives, as in Figma', () => {+ const { graph, done, badge, outer, target } = swappedBadge()+ for (let pass = 0; pass < 2; pass++) {+ expect(target.fills).toEqual(done.fills)+ expect(target.fillStyleId).toBe('style-done')+ expect(target.boundVariables).toEqual({ 'fills/0/color': 'green', opacity: 'faded' })+ expect(target.variableBindingScales['fills/0/color']).toBe(2)+ // What the template set on the badge, other than its fill, stays.+ expect(target.x).toBe(badge.x)+ expect(target.visible).toBe(false)+ graph.syncInstance(outer.id)+ }+})++test('an edit to the new component reaches the swapped badge', () => {+ const { graph, done, outer, target } = swappedBadge()+ graph.updateNode(done.id, { fills: [], boundVariables: {} })+ graph.syncInstance(outer.id)+ expect(target.fills).toEqual([])+ expect(target.boundVariables).toEqual({ opacity: 'faded' })+})++test('a fill the template overrides on the badge survives the swap, bound or plain, as in Figma', () => {+ const bound = swappedBadge((graph, badge) => {+ graph.updateNode(badge.id, { boundVariables: { 'fills/0/color': 'purple' } })+ setInstanceOverride(badge.instanceOverrides, badge.id, badge.id, 'boundVariables/fills/0/color', true)+ })+ expect(bound.target.boundVariables['fills/0/color']).toBe('purple')+ const plain = swappedBadge((graph, badge) => {+ graph.updateNode(badge.id, { fills: solid(0.5, 0, 1), boundVariables: {} })+ setInstanceOverride(badge.instanceOverrides, badge.id, badge.id, 'fills', badge.fills)+ setInstanceOverride(badge.instanceOverrides, badge.id, badge.id, 'boundVariables/fills/0/color', true)+ })+ expect(plain.target.fills).toEqual(solid(0.5, 0, 1))+ expect(plain.target.boundVariables['fills/0/color']).toBeUndefined()+})++test('the swapped badge keeps its own fill, binding and style overrides through component edits', () => {+ const { graph, todo, done, outer, target } = swappedBadge()+ graph.updateNode(target.id, {+ fills: todo.fills,+ boundVariables: { 'fills/0/color': 'own', opacity: 'faded' },+ variableBindingScales: { 'fills/0/color': 3 },+ fillStyleId: 'style-own'+ })+ setInstanceOverride(target.instanceOverrides, target.id, target.id, 'fills', target.fills)+ setInstanceOverride(target.instanceOverrides, target.id, target.id, 'boundVariables/fills/0/color', true)+ setInstanceOverride(target.instanceOverrides, target.id, target.id, 'fillStyleId', 'style-own')+ graph.updateNode(done.id, { fills: solid(0, 0, 1), boundVariables: { 'fills/0/color': 'blue' } })+ graph.syncInstance(outer.id)+ expect(target.fills).toEqual(todo.fills)+ expect(target.boundVariables).toEqual({ 'fills/0/color': 'own', opacity: 'faded' })+ expect(target.variableBindingScales['fills/0/color']).toBe(3)+ expect(target.fillStyleId).toBe('style-own')+})++test('its own plain fill override keeps the swapped badge unbound', () => {+ const { graph, outer, target } = swappedBadge()+ graph.updateNode(target.id, { fills: solid(0.5, 0, 1), boundVariables: { opacity: 'faded' } })+ setInstanceOverride(target.instanceOverrides, target.id, target.id, 'fills', target.fills)+ graph.syncInstance(outer.id)+ expect(target.fills).toEqual(solid(0.5, 0, 1))+ expect(target.boundVariables).toEqual({ opacity: 'faded' })+})++test('clearing its own fill binding leaves the swapped badge unbound', () => {+ const { graph, outer, target } = swappedBadge()+ graph.updateNode(target.id, { boundVariables: { opacity: 'faded' }, variableBindingScales: {} })+ setInstanceOverride(target.instanceOverrides, target.id, target.id, 'boundVariables', true)+ graph.syncInstance(outer.id)+ expect(target.boundVariables).toEqual({ opacity: 'faded' })+ expect(target.variableBindingScales['fills/0/color']).toBeUndefined()+})++test('a fill or style the outer instance overrides on the swapped badge wins', () => {+ const { graph, done, outer, target } = swappedBadge()+ graph.updateNode(target.id, { fills: [], fillStyleId: 'style-outer' })+ setInstanceOverride(outer.instanceOverrides, outer.id, target.id, 'fills', [])+ setInstanceOverride(outer.instanceOverrides, outer.id, target.id, 'fillStyleId', 'style-outer')+ for (let pass = 0; pass < 2; pass++) {+ graph.syncInstance(outer.id)+ expect(target.fills).toEqual([])+ expect(target.fillStyleId).toBe('style-outer')+ }+ outer.instanceOverrides.descendants.get(target.id)?.delete('fills')+ graph.syncInstance(outer.id)+ expect(target.fills).toEqual(done.fills)+ expect(target.fillStyleId).toBe('style-outer')+})++test('swapping the badge back gives it the template’s fill again', () => {+ const { badge, todo, target, swap } = swappedBadge()+ swap(todo)+ expect(target.fills).toEqual(badge.fills)+ expect(target.fillStyleId).toBe('style-todo')+})diff --git a/packages/scene-graph/tests/components/sync-field-contract.test.ts b/packages/scene-graph/tests/components/sync-field-contract.test.tsindex 502cddd04..2cc2a8232 100644--- a/packages/scene-graph/tests/components/sync-field-contract.test.ts+++ b/packages/scene-graph/tests/components/sync-field-contract.test.ts@@ -329,6 +329,94 @@ test('a copy that sizes itself to its own content keeps that size through a compexpect(copyText.letterSpacing).toBe(1)})+test('content-sized copies retain their constraint anchor through live component edits', () => {+ for (const constraint of ['MIN', 'CENTER', 'MAX'] as const) {+ const graph = new SceneGraph()+ const component = graph.createNode('COMPONENT', graph.getPages()[0].id, {+ width: 100,+ height: 80+ })+ const source = graph.createNode('FRAME', component.id, {+ x: 40,+ y: 35,+ width: 20,+ height: 10,+ layoutMode: 'HORIZONTAL',+ primaryAxisSizing: 'HUG',+ counterAxisSizing: 'HUG',+ horizontalConstraint: constraint,+ verticalConstraint: constraint+ })+ const instance = expectDefined(graph.createInstance(component.id, graph.getPages()[0].id))+ graph.updateNode(instance.id, { width: 300, height: 160 })+ setInstanceOverride(instance.instanceOverrides, instance.id, instance.id, 'width', true)+ setInstanceOverride(instance.instanceOverrides, instance.id, instance.id, 'height', true)+ const copy = graph.getChildren(instance.id)[0]+ graph.updateNode(copy.id, { width: 10, height: 6 })+ graph.updateNode(source.id, { opacity: 0.5 })+ graph.syncInstances(component.id)+ const expected = { MIN: [40, 35], CENTER: [145, 77], MAX: [250, 119] }[constraint]+ expect([copy.x, copy.y, copy.width, copy.height]).toEqual([...expected, 10, 6])+ expect(copy.opacity).toBe(0.5)+ graph.updateNode(source.id, { x: 45, width: 40 })+ graph.syncInstances(component.id)+ const edited = { MIN: [45, 35], CENTER: [160, 77], MAX: [275, 119] }[constraint]+ expect([copy.x, copy.y]).toEqual(edited)+ graph.updateNode(instance.id, { width: 400 })+ graph.syncInstances(component.id)+ expect(copy.x).toBe(edited[0] + { MIN: 0, CENTER: 50, MAX: 100 }[constraint])+ }+})++test('anchor correction respects equal parent sizes, bound positions and auto-layout placement', () => {+ for (const mode of ['equal', 'protected', 'flow', 'fixed', 'scaled'] as const) {+ const graph = new SceneGraph()+ const page = graph.getPages()[0].id+ const component = graph.createNode('COMPONENT', page, {+ width: 100,+ height: 80,+ layoutMode: mode === 'flow' ? 'HORIZONTAL' : 'NONE'+ })+ const source = graph.createNode('FRAME', component.id, {+ x: 40,+ y: 35,+ width: 20,+ height: 10,+ layoutMode: 'HORIZONTAL',+ primaryAxisSizing: mode === 'fixed' ? 'FIXED' : 'HUG',+ counterAxisSizing: mode === 'fixed' ? 'FIXED' : 'HUG',+ horizontalConstraint: 'CENTER',+ verticalConstraint: 'CENTER'+ })+ const instance = expectDefined(graph.createInstance(component.id, page))+ const copy = graph.getChildren(instance.id)[0]+ graph.updateNode(copy.id, { x: 40, y: 35, width: 10, height: 6 })+ if (mode === 'protected') {+ graph.updateNode(copy.id, { boundVariables: { x: 'local-x', y: 'local-y' } })+ setInstanceOverride(instance.instanceOverrides, instance.id, copy.id, 'boundVariables', true)+ }+ if (mode === 'scaled') {+ graph.updateNode(instance.id, { componentScale: 2 })+ graph.updateNode(copy.id, { x: 80, y: 70, componentScale: 2 })+ }+ graph.updateNode(source.id, { opacity: 0.5 })+ graph.syncInstances(component.id)+ const expected = {+ fixed: [40, 35, 20, 10],+ scaled: [95, 77, 10, 6],+ equal: [45, 37, 10, 6],+ protected: [40, 35, 10, 6],+ flow: [40, 35, 10, 6]+ }[mode]+ expect([copy.x, copy.y, copy.width, copy.height]).toEqual(expected)+ if (mode === 'equal') {+ graph.updateNode(source.id, { horizontalConstraint: 'MAX', verticalConstraint: 'MIN' })+ graph.syncInstances(component.id)+ expect([copy.x, copy.y]).toEqual([50, 35])+ }+ }+})+test('a copy takes the component’s size once the component stops hugging its layers', () => {const graph = new SceneGraph()const page = graph.getPages()[0].iddiff --git a/packages/scene-graph/tests/images.test.ts b/packages/scene-graph/tests/images.test.tsindex d2bd441b8..f3d2c5083 100644--- a/packages/scene-graph/tests/images.test.ts+++ b/packages/scene-graph/tests/images.test.ts@@ -1,6 +1,6 @@import { describe, expect, test } from 'bun:test'-import { computeImageHash, imageMimeType } from '@open-pencil/scene-graph'+import { computeImageHash, coverImageTransform, imageMimeType } from '@open-pencil/scene-graph'describe('computeImageHash', () => {test('names bytes by their SHA-1, as Figma names images', () => {@@ -26,3 +26,18 @@ describe('imageMimeType', () => {expect(imageMimeType(new Uint8Array())).toBe('image/png')})})++describe('coverImageTransform', () => {+ test('crops the image to cover the layer, centred, as Figma starts a crop', () => {+ // Measured in Figma: a 412 × 364 image cropped on a 160 × 120 layer.+ const crop = coverImageTransform(160, 120, 412, 364)+ expect(crop.m00).toBeCloseTo(1)+ expect(crop.m02).toBeCloseTo(0)+ expect(crop.m11).toBeCloseTo(0.848901093006134)+ expect(crop.m12).toBeCloseTo(0.07554945349693298)+ const tall = coverImageTransform(100, 300, 200, 200)+ expect([tall.m00, tall.m02, tall.m11, tall.m12].map((v) => Math.round(v * 1000))).toEqual([+ 333, 333, 1000, 0+ ])+ })+})diff --git a/packages/vue/src/i18n/locales/de/panels.json b/packages/vue/src/i18n/locales/de/panels.jsonindex 064203726..2127d19e1 100644--- a/packages/vue/src/i18n/locales/de/panels.json+++ b/packages/vue/src/i18n/locales/de/panels.json@@ -133,6 +133,7 @@"ignoreAutoLayout": "Auto-Layout ignorieren","flipVertical": "Vertikal spiegeln","rotate90": "90° drehen",+ "imageTileScale": "Kachelgröße","mixedFillsHelp": "Klicke auf +, um gemischte Füllungen zu ersetzen","mixedStrokesHelp": "Klicke auf +, um gemischte Konturen zu ersetzen","mixedEffectsHelp": "Klicke auf +, um gemischte Effekte zu ersetzen",diff --git a/packages/vue/src/i18n/locales/es/panels.json b/packages/vue/src/i18n/locales/es/panels.jsonindex 69bf184a7..d6bb3a9f9 100644--- a/packages/vue/src/i18n/locales/es/panels.json+++ b/packages/vue/src/i18n/locales/es/panels.json@@ -148,6 +148,7 @@"ignoreAutoLayout": "Ignorar diseño automático","flipVertical": "Voltear verticalmente","rotate90": "Girar 90°",+ "imageTileScale": "Escala del mosaico","mixedFillsHelp": "Haz clic en + para reemplazar rellenos mixtos","mixedStrokesHelp": "Haz clic en + para reemplazar trazos mixtos","mixedEffectsHelp": "Haz clic en + para reemplazar efectos mixtos",diff --git a/packages/vue/src/i18n/locales/fr/panels.json b/packages/vue/src/i18n/locales/fr/panels.jsonindex 7d02c195f..17857675a 100644--- a/packages/vue/src/i18n/locales/fr/panels.json+++ b/packages/vue/src/i18n/locales/fr/panels.json@@ -133,6 +133,7 @@"ignoreAutoLayout": "Ignorer la mise en page automatique","flipVertical": "Retourner verticalement","rotate90": "Pivoter de 90°",+ "imageTileScale": "Échelle des tuiles","mixedFillsHelp": "Cliquez sur + pour remplacer les remplissages mixtes","mixedStrokesHelp": "Cliquez sur + pour remplacer les contours mixtes","mixedEffectsHelp": "Cliquez sur + pour remplacer les effets mixtes",diff --git a/packages/vue/src/i18n/locales/it/panels.json b/packages/vue/src/i18n/locales/it/panels.jsonindex db4f6654a..e2fdd882b 100644--- a/packages/vue/src/i18n/locales/it/panels.json+++ b/packages/vue/src/i18n/locales/it/panels.json@@ -133,6 +133,7 @@"ignoreAutoLayout": "Ignora layout automatico","flipVertical": "Rifletti verticalmente","rotate90": "Ruota di 90°",+ "imageTileScale": "Scala delle tessere","mixedFillsHelp": "Fai clic su + per sostituire i riempimenti misti","mixedStrokesHelp": "Fai clic su + per sostituire i contorni misti","mixedEffectsHelp": "Fai clic su + per sostituire gli effetti misti",diff --git a/packages/vue/src/i18n/locales/ja/panels.json b/packages/vue/src/i18n/locales/ja/panels.jsonindex 2eda4f35a..64cf89b20 100644--- a/packages/vue/src/i18n/locales/ja/panels.json+++ b/packages/vue/src/i18n/locales/ja/panels.json@@ -148,6 +148,7 @@"ignoreAutoLayout": "オートレイアウトを無視","flipVertical": "垂直方向に反転","rotate90": "90°回転",+ "imageTileScale": "タイルの拡大率","mixedFillsHelp": "+ をクリックして混合塗りを置換","mixedStrokesHelp": "+ をクリックして混合線を置換","mixedEffectsHelp": "+ をクリックして混合エフェクトを置換",diff --git a/packages/vue/src/i18n/locales/pl/panels.json b/packages/vue/src/i18n/locales/pl/panels.jsonindex af1d439a9..0bc5dcbb2 100644--- a/packages/vue/src/i18n/locales/pl/panels.json+++ b/packages/vue/src/i18n/locales/pl/panels.json@@ -133,6 +133,7 @@"ignoreAutoLayout": "Ignoruj auto layout","flipVertical": "Odbij pionowo","rotate90": "Obróć o 90°",+ "imageTileScale": "Skala kafelków","mixedFillsHelp": "Kliknij +, aby zastąpić mieszane wypełnienia","mixedStrokesHelp": "Kliknij +, aby zastąpić mieszane obrysy","mixedEffectsHelp": "Kliknij +, aby zastąpić mieszane efekty",diff --git a/packages/vue/src/i18n/locales/ru/panels.json b/packages/vue/src/i18n/locales/ru/panels.jsonindex e09b89b2a..7ba640856 100644--- a/packages/vue/src/i18n/locales/ru/panels.json+++ b/packages/vue/src/i18n/locales/ru/panels.json@@ -106,6 +106,7 @@"ignoreAutoLayout": "Игнорировать автолейаут","flipVertical": "Отразить по вертикали","rotate90": "Повернуть на 90°",+ "imageTileScale": "Масштаб плитки","mixedFillsHelp": "Нажмите +, чтобы заменить смешанные заливки","mixedStrokesHelp": "Нажмите +, чтобы заменить смешанные обводки","mixedEffectsHelp": "Нажмите +, чтобы заменить смешанные эффекты",diff --git a/packages/vue/src/i18n/locales/zh-cn/panels.json b/packages/vue/src/i18n/locales/zh-cn/panels.jsonindex d694a229a..4becb5111 100644--- a/packages/vue/src/i18n/locales/zh-cn/panels.json+++ b/packages/vue/src/i18n/locales/zh-cn/panels.json@@ -106,6 +106,7 @@"ignoreAutoLayout": "忽略自动布局","flipVertical": "垂直翻转","rotate90": "旋转 90°",+ "imageTileScale": "平铺缩放","mixedFillsHelp": "点击 + 替换混合填充","mixedStrokesHelp": "点击 + 替换混合描边","mixedEffectsHelp": "点击 + 替换混合效果",diff --git a/packages/vue/src/i18n/messages/panels.ts b/packages/vue/src/i18n/messages/panels.tsindex d16be9b56..dbbfb23b3 100644--- a/packages/vue/src/i18n/messages/panels.ts+++ b/packages/vue/src/i18n/messages/panels.ts@@ -433,6 +433,7 @@ export const panelMessageDefaults = {ignoreAutoLayout: 'Ignore auto layout',flipVertical: 'Flip vertical',rotate90: 'Rotate 90°',+ imageTileScale: 'Tile scale',mixedFillsHelp: 'Click + to replace mixed fills',mixedStrokesHelp: 'Click + to replace mixed strokes',mixedEffectsHelp: 'Click + to replace mixed effects',diff --git a/src/components/fill-picker/FillPicker.vue b/src/components/fill-picker/FillPicker.vueindex 55e356803..3e915b72b 100644--- a/src/components/fill-picker/FillPicker.vue+++ b/src/components/fill-picker/FillPicker.vue@@ -2,6 +2,7 @@import { PopoverContent, PopoverPortal, PopoverRoot, PopoverTrigger } from 'reka-ui'import type { FocusOutsideEvent, PointerDownOutsideEvent } from 'reka-ui'import { tv } from 'tailwind-variants'+import { computed } from 'vue'import type { Fill, ShaderPaint, ShaderPreset } from '@open-pencil/scene-graph'import {@@ -22,6 +23,8 @@ import Tip from '@/components/ui/overlay/Tip.vue'import FillSwatch from '@/components/ui/paint/FillSwatch.vue'import fillPickerTheme from '@/theme/fill-picker'+import { useImageFill } from './useImageFill'+const fillPicker = tv(fillPickerTheme)function tabClass(active: boolean) {@@ -33,7 +36,8 @@ const {okhcl = null,swatchBackground,keepOpen,- shader = null+ shader = null,+ layerSize = null} = defineProps<{fill: Fill/** The shader the paint draws, when it is a shader's frame; the picker then edits the shader. */@@ -44,7 +48,14 @@ const {label?: string/** Whether a press outside the picker should leave it open, such as on a gradient handle. */keepOpen?: (event: PointerEvent) => boolean+ /** The one layer the paint is on, which an image crop starts by covering. */+ layerSize?: { width: number; height: number } | null}>()+/** An image fill's swatch shows its image, covering the swatch as Fill would. */+const image = useImageFill(() => (fill.type === 'IMAGE' ? fill.imageHash : undefined))+const imageBackground = computed(() =>+ image.url.value ? `center / cover no-repeat url("${image.url.value}")` : undefined+)const activeStop = defineModel<number>('activeStop')const emit = defineEmits<{update: [fill: Fill]@@ -91,7 +102,7 @@ function cancelFromEscape(event: KeyboardEvent) {<FillSwatch :fill="fill" class="size-full" v-slot="swatch"><spanclass="pointer-events-none absolute inset-0"- :style="{ background: swatchBackground ?? swatch.background }"+ :style="{ background: swatchBackground ?? imageBackground ?? swatch.background }"/></FillSwatch></button>@@ -177,6 +188,7 @@ function cancelFromEscape(event: KeyboardEvent) {<ImageFillPickerv-else-if="root.category === 'IMAGE'":fill="root.fill"+ :layer-size="layerSize"@update="emit('update', $event)"/></PopoverContent>diff --git a/src/components/fill-picker/ImageFillPicker.vue b/src/components/fill-picker/ImageFillPicker.vueindex d22ff911d..113724cfe 100644--- a/src/components/fill-picker/ImageFillPicker.vue+++ b/src/components/fill-picker/ImageFillPicker.vue@@ -1,13 +1,19 @@<script setup lang="ts">-import { useFileDialog, useObjectUrl } from '@vueuse/core'-import { computed, shallowRef, watch } from 'vue'+import { useFileDialog } from '@vueuse/core'+import { computed } from 'vue'import type { Fill, ImageScaleMode } from '@open-pencil/scene-graph'+import { coverImageTransform } from '@open-pencil/scene-graph/images'+import { useI18n } from '@open-pencil/vue'import { useEditorStore } from '@/app/editor/active-store'+import NumberField from '@/components/inputs/NumberField.vue'import AppButton from '@/components/ui/button/AppButton.vue'+import IconButton from '@/components/ui/button/IconButton.vue'import AppSelect from '@/components/ui/select/AppSelect.vue'+import { useImageFill } from './useImageFill'+const IMAGE_SCALE_MODES: { value: ImageScaleMode; label: string }[] = [{ value: 'FILL', label: 'Fill' },{ value: 'FIT', label: 'Fit' },@@ -15,26 +21,19 @@ const IMAGE_SCALE_MODES: { value: ImageScaleMode; label: string }[] = [{ value: 'TILE', label: 'Tile' }]-const { fill } = defineProps<{ fill: Fill }>()+const { fill, layerSize = null } = defineProps<{+ fill: Fill+ /** The layer the fill is on, which a new crop starts by covering, as Fill does. */+ layerSize?: { width: number; height: number } | null+}>()const emit = defineEmits<{ update: [fill: Fill] }>()const store = useEditorStore()+const { panels } = useI18n()-const imageBlob = shallowRef<Blob | null>(null)-const imagePreviewURL = useObjectUrl(imageBlob)--watch(- () => fill.imageHash,- (hash) => {- if (!hash) {- imageBlob.value = null- return- }- const data = store.getImage(hash)- imageBlob.value = data ? new Blob([data]) : null- },- { immediate: true }-)+const { url: imagePreviewURL, size: imageSize } = useImageFill(() => fill.imageHash, {+ measure: true+})const { open: pickImage, onChange: onFileChange } = useFileDialog({accept: 'image/png,image/jpeg,image/webp',@@ -54,10 +53,35 @@ onFileChange(async (files) => {})})+/**+ * Figma keeps a crop through other modes, which ignore it, but a new crop starts over from the+ * Fill framing; without the layer's or image's size the renderer frames it as Fill does.+ */+function cropStart(): Fill['imageTransform'] {+ const image = imageSize.value+ if (!layerSize || !image) return undefined+ return coverImageTransform(layerSize.width, layerSize.height, image.width, image.height)+}+const scaleMode = computed({get: () => fill.imageScaleMode ?? ('FILL' as ImageScaleMode),- set: (mode: ImageScaleMode) => emit('update', { ...fill, imageScaleMode: mode })+ set: (mode: ImageScaleMode) => {+ if (mode === scaleMode.value) return+ const next: Fill = { ...fill, imageScaleMode: mode }+ if (mode === 'CROP') next.imageTransform = cropStart()+ emit('update', next)+ }})++/** A tile's size as a percentage of the image's own. */+const tileScale = computed(() => Math.round((fill.scale && fill.scale > 0 ? fill.scale : 1) * 100))+function setTileScale(percent: number) {+ if (percent > 0) emit('update', { ...fill, scale: percent / 100 })+}++function rotate() {+ emit('update', { ...fill, imageRotation: ((fill.imageRotation ?? 0) + 90) % 360 })+}</script><template>@@ -77,10 +101,33 @@ const scaleMode = computed({<template #leading><icon-lucide-image class="size-3" /></template>{{ fill.imageHash ? 'Replace' : 'Choose image' }}</AppButton>- <AppSelect- :model-value="scaleMode"- :options="IMAGE_SCALE_MODES"- @update:model-value="(m) => (scaleMode = m as ImageScaleMode)"- />+ <div class="flex items-center gap-1.5">+ <AppSelect+ :ui="{ trigger: 'min-w-0 flex-1' }"+ :model-value="scaleMode"+ :options="IMAGE_SCALE_MODES"+ @update:model-value="(m) => (scaleMode = m as ImageScaleMode)"+ />+ <div v-if="scaleMode === 'TILE'" class="w-16 flex-none">+ <NumberField+ :model-value="tileScale"+ :min="1"+ suffix="%"+ :aria-label="panels.imageTileScale"+ data-test-id="fill-picker-tile-scale"+ @update:model-value="setTileScale"+ @commit="setTileScale"+ />+ </div>+ <!-- A crop holds its own turn in its transform, so only the other modes turn the image. -->+ <IconButton+ v-if="scaleMode !== 'CROP'"+ :label="panels.rotate90"+ data-test-id="fill-picker-rotate-image"+ @click="rotate"+ >+ <icon-lucide-rotate-cw class="size-3.5" />+ </IconButton>+ </div></div></template>diff --git a/src/components/fill-picker/useImageFill.ts b/src/components/fill-picker/useImageFill.tsnew file mode 100644index 000000000..48704ef2b--- /dev/null+++ b/src/components/fill-picker/useImageFill.ts@@ -0,0 +1,44 @@+import { useObjectUrl } from '@vueuse/core'+import { shallowRef, watch, type MaybeRefOrGetter, toValue } from 'vue'++import { useEditorStore } from '@/app/editor/active-store'++/**+ * The stored image an image fill names, as a URL to show. `measure` also decodes it for its size+ * in pixels, which only the picker needs; a swatch in every paint row stays a URL.+ */+export function useImageFill(+ hash: MaybeRefOrGetter<string | undefined>,+ { measure = false }: { measure?: boolean } = {}+) {+ const store = useEditorStore()+ const blob = shallowRef<Blob | null>(null)+ const url = useObjectUrl(blob)+ const size = shallowRef<{ width: number; height: number } | null>(null)++ watch(+ () => toValue(hash),+ (name) => {+ const data = name ? store.getImage(name) : undefined+ // A copy owns a plain ArrayBuffer, which a Blob takes where shared memory is not allowed.+ blob.value = data ? new Blob([data.slice()]) : null+ },+ { immediate: true }+ )+ if (measure)+ watch(+ blob,+ async (current) => {+ size.value = null+ if (!current) return+ // Bytes the browser cannot decode leave the size unknown, as before it loads.+ const bitmap = await createImageBitmap(current).catch(() => null)+ if (!bitmap) return+ if (blob.value === current) size.value = { width: bitmap.width, height: bitmap.height }+ bitmap.close()+ },+ { immediate: true }+ )++ return { url, size }+}diff --git a/src/components/properties/FillSection.vue b/src/components/properties/FillSection.vueindex 4821402f1..ea07c47fa 100644--- a/src/components/properties/FillSection.vue+++ b/src/components/properties/FillSection.vue@@ -157,6 +157,7 @@ function updateSolidColor(:fill="displayFill(fill, binding.resolvedValue)":okhcl="createFillOkhclAdapter(okhcl, activeNode, index)":shader="fillShader(activeNode, fill)"+ :layer-size="selectedNodeIds.length === 1 ? activeNode : null":keep-open="gradients.pressesHandle":active-stop="gradients.stop(gradients.target(selectedNodeIds, 'fills', index))"@update:active-stop="diff --git a/src/components/properties/stroke/StrokeSection.vue b/src/components/properties/stroke/StrokeSection.vueindex 0ece12144..372ede82b 100644--- a/src/components/properties/stroke/StrokeSection.vue+++ b/src/components/properties/stroke/StrokeSection.vue@@ -168,6 +168,7 @@ function onToggleSides(nodes: readonly SceneNode[]) {:label="panels.stroke":fill="displayStroke(stroke, binding.resolvedValue)":okhcl="createStrokeOkhclAdapter(okhcl, activeNode, index)"+ :layer-size="selectedNodeIds.length === 1 ? activeNode : null":keep-open="gradients.pressesHandle":active-stop="gradients.stop(gradients.target(selectedNodeIds, 'strokes', index))"@update:active-stop="diff --git a/tests/e2e/canvas/fill-modes-visual.spec.ts b/tests/e2e/canvas/fill-modes-visual.spec.tsindex 4d653d7c8..7c47397bd 100644--- a/tests/e2e/canvas/fill-modes-visual.spec.ts+++ b/tests/e2e/canvas/fill-modes-visual.spec.ts@@ -1,6 +1,7 @@import { readFile } from 'node:fs/promises'-import { shaderPresetKey } from '@open-pencil/scene-graph'+import type * as FigNodeChange from '@open-pencil/fig/node-change'+import { shaderPresetKey, type Fill } from '@open-pencil/scene-graph'import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'import { readScenePixels } from '#tests/helpers/canvas/pixels'@@ -64,6 +65,8 @@ test('FIT avatar preserves the full clipboard fixture image', async () => {test('gradients and image fill modes', async () => {await editor.page.evaluate(async () => {+ const figURL = '/@id/@open-pencil/fig/node-change'+ const { convertFills, nodeChangeToProps }: typeof FigNodeChange = await import(figURL)const store = window.openPencil?.getStore?.()if (!store) throw new Error('OpenPencil store not initialized')const pageId = store.state.currentPageId@@ -157,15 +160,69 @@ test('gradients and image fill modes', async () => {]})- const scaleModes = ['FILL', 'FIT', 'TILE', 'CROP'] as const+ const scaleModes = ['FILL', 'FIT', 'TILE', 'CROP', 'STRETCH'] as constfor (const [index, imageScaleMode] of scaleModes.entries()) {store.graph.createNode('RECTANGLE', pageId, {name: `${imageScaleMode} image visual`,- x: 84 + index * 116,+ x: imageScaleMode === 'STRETCH' ? 660 : 84 + index * 116,y: 184,width: 92,height: 72,cornerRadius: 14,+ fills:+ imageScaleMode === 'STRETCH'+ ? convertFills([+ {+ type: 'IMAGE',+ image: { hash: imageHash },+ imageScaleMode,+ transform: { m00: 2, m01: 0, m02: -0.25, m10: 0, m11: 2, m12: 0.125 }+ }+ ])+ : [+ {+ type: 'IMAGE',+ color: { r: 0, g: 0, b: 0, a: 1 },+ visible: true,+ opacity: 1,+ imageHash,+ imageScaleMode,+ imageTransform:+ imageScaleMode === 'CROP'+ ? { m00: 0.5, m01: 0, m02: 0.25, m10: 0, m11: 0.5, m12: 0.25 }+ : undefined+ }+ ],+ strokes: [+ {+ type: 'SOLID',+ color: { r: 1, g: 1, b: 1, a: 0.9 },+ weight: 2,+ visible: true,+ opacity: 1,+ align: 'INSIDE'+ }+ ]+ })+ }++ // Figma tiles by scale and turns Fill, Fit and Tile images; a Tile ignores a crop it kept.+ const placements: Partial<Fill>[] = [+ { imageScaleMode: 'TILE', scale: 0.5 },+ { imageScaleMode: 'TILE', imageRotation: 90 },+ { imageScaleMode: 'FILL', imageRotation: 90 },+ {+ imageScaleMode: 'TILE',+ imageTransform: { m00: 0.5, m01: 0, m02: 0.25, m10: 0, m11: 0.5, m12: 0.25 }+ }+ ]+ for (const [index, placement] of placements.entries()) {+ store.graph.createNode('RECTANGLE', pageId, {+ name: `Image placement ${index}`,+ x: 84 + index * 116,+ y: 320,+ width: 92,+ height: 72,fills: [{type: 'IMAGE',@@ -173,26 +230,42 @@ test('gradients and image fill modes', async () => {visible: true,opacity: 1,imageHash,- imageScaleMode,- imageTransform:- imageScaleMode === 'CROP'- ? { m00: 0.5, m01: 0, m02: 0.25, m10: 0, m11: 0.5, m12: 0.25 }- : undefined+ ...placement}- ],+ ]+ })+ }++ for (const [index, rotation] of [90, -90].entries()) {+ const line = nodeChangeToProps(+ {+ type: 'LINE',+ size: { x: 70, y: 0 },+ transform: {+ m00: 0,+ m01: rotation === 90 ? -1 : 1,+ m02: 730 + index * 20,+ m10: rotation === 90 ? 1 : -1,+ m11: 0,+ m12: rotation === 90 ? 100 : 170+ }+ },+ []+ )+ store.graph.createNode('LINE', pageId, {+ ...line,strokes: [{type: 'SOLID',- color: { r: 1, g: 1, b: 1, a: 0.9 },- weight: 2,- visible: true,+ color: { r: 0.1, g: 0.2, b: 0.6, a: 1 },+ weight: 3,+ align: 'CENTER',opacity: 1,- align: 'INSIDE'+ visible: true}]})}-store.clearSelection()store.requestRender()})@@ -206,6 +279,24 @@ test('gradients and image fill modes', async () => {expect(Math.min(r, g, b)).toBeLessThan(200)}await editor.canvas.waitForRender()+ const [cropPixel, ...linePixels] = await readScenePixels(editor.page, [+ { x: 706, y: 235 },+ { x: 730, y: 130 },+ { x: 750, y: 130 }+ ])+ expect(cropPixel.slice(0, 3)).toEqual([17, 24, 39])+ for (const [r, g, b] of linePixels) {+ expect(Math.abs(r - 26)).toBeLessThanOrEqual(4)+ expect(Math.abs(g - 51)).toBeLessThanOrEqual(4)+ expect(Math.abs(b - 153)).toBeLessThanOrEqual(4)+ }+ const [turnedFill, keptCrop] = await readScenePixels(editor.page, [+ { x: 316 + 70, y: 320 + 20 },+ { x: 432 + 20, y: 320 + 10 }+ ])+ // The red top-left quarter turns to the top right, and a kept crop leaves the tile at full size.+ expect(turnedFill.slice(0, 3)).toEqual([239, 68, 68])+ expect(keptCrop.slice(0, 3)).toEqual([239, 68, 68])await expectCanvas('gradients-and-image-fill-modes')})diff --git a/tests/e2e/canvas/fill-modes-visual.spec.ts-snapshots/gradients-and-image-fill-modes-openpencil-darwin.png b/tests/e2e/canvas/fill-modes-visual.spec.ts-snapshots/gradients-and-image-fill-modes-openpencil-darwin.pngindex 38e2f8390..c537e018c 100644Binary files a/tests/e2e/canvas/fill-modes-visual.spec.ts-snapshots/gradients-and-image-fill-modes-openpencil-darwin.png and b/tests/e2e/canvas/fill-modes-visual.spec.ts-snapshots/gradients-and-image-fill-modes-openpencil-darwin.png differdiff --git a/tests/e2e/canvas/instance-scale-visual.spec.ts b/tests/e2e/canvas/instance-scale-visual.spec.tsindex bfc02a1e0..1b67dfc00 100644--- a/tests/e2e/canvas/instance-scale-visual.spec.ts+++ b/tests/e2e/canvas/instance-scale-visual.spec.ts@@ -1,19 +1,27 @@import { pick } from 'es-toolkit/object'+import { deflateSync } from 'fflate'import { toUint8Array } from 'js-base64'import { computeAllLayouts, computeLayout } from '@open-pencil/core/layout'-import { materializeDocument } from '@open-pencil/fig'-import type { NodeChange } from '@open-pencil/kiwi/fig/codec'+import { materializeDocument, writeFigArchive } from '@open-pencil/fig'+import {+ createNodeChangesMessage,+ encodeMessage,+ getSchemaBytes,+ initCodec,+ type NodeChange+} from '@open-pencil/kiwi/fig/codec'import {reconcileVariableBindings,rescaleNodeTree,type SceneNode,- type SceneGraph+ SceneGraph} from '@open-pencil/scene-graph'import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'import bindingFixture from '#tests/fixtures/nested-binding-ownership-records.json' with { type: 'json' }import fixture from '#tests/fixtures/nested-layout-scale.json' with { type: 'json' }+import { readScenePixels } from '#tests/helpers/canvas/pixels'import { absoluteConstraintRecords } from '#tests/helpers/fig/absolute-constraints'import { inheritedNestedBindingRecords } from '#tests/helpers/fig/nested-binding'@@ -78,6 +86,226 @@ async function renderTrees(trees: RenderNode[]) {}, trees)}+test('nested visibility assignments keep the outer icon visible after synchronization', async () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const definitions = [+ { id: 'visible', name: 'Visible', type: 'BOOLEAN' as const, defaultValue: 'false' }+ ]+ const inner = graph.createNode('COMPONENT', page.id, {+ width: 40,+ height: 40,+ componentPropertyDefinitions: definitions,+ fills: [{ type: 'SOLID', color: { r: 0.1, g: 0.7, b: 0.3, a: 1 }, visible: true, opacity: 1 }]+ })+ graph.createNode('RECTANGLE', inner.id, {+ width: 40,+ height: 40,+ visible: false,+ fills: [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, visible: true, opacity: 1 }],+ componentPropertyReferences: [{ propertyId: 'visible', field: 'VISIBLE' }]+ })+ const outer = graph.createNode('COMPONENT', page.id, {+ width: 40,+ height: 40,+ componentPropertyDefinitions: definitions+ })+ graph.createInstance(inner.id, outer.id, {+ componentPropertyReferences: [{ propertyId: 'visible', field: 'VISIBLE' }],+ componentPropertyAssignments: { visible: 'false' }+ })+ const instance = graph.createInstance(outer.id, page.id, {+ componentPropertyAssignments: { visible: 'true' }+ })+ if (!instance) throw new Error('Missing nested instance')+ graph.syncInstances(outer.id)+ const icon = graph.getChildren(instance.id)[0]+ expect(icon.visible).toBe(true)+ expect(graph.getChildren(icon.id)[0].visible).toBe(false)+ await renderTrees([renderTree(graph, instance.id)])+ await editor.canvas.waitForRender()+ const [[r, g, b]] = await readScenePixels(editor.page, [{ x: 240, y: 240 }])+ expect(g).toBeGreaterThan(Math.max(r, b))+ expect(await editor.canvas.screenshotCanvasRegion()).toMatchSnapshot(+ 'nested-visibility-scope.png'+ )+})++test('a content-sized copy keeps its center while component edits still propagate', async () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0].id+ const component = graph.createNode('COMPONENT', page, {+ width: 100,+ height: 80,+ fills: [{ type: 'SOLID', color: { r: 0.9, g: 0.9, b: 0.9, a: 1 }, visible: true, opacity: 1 }]+ })+ const source = graph.createNode('FRAME', component.id, {+ x: 10,+ y: 20,+ width: 80,+ height: 40,+ layoutMode: 'HORIZONTAL',+ primaryAxisSizing: 'HUG',+ counterAxisSizing: 'HUG',+ horizontalConstraint: 'CENTER',+ verticalConstraint: 'CENTER',+ fills: [{ type: 'SOLID', color: { r: 0.1, g: 0.7, b: 0.3, a: 1 }, visible: true, opacity: 1 }]+ })+ const instance = graph.createInstance(component.id, page)+ if (!instance) throw new Error('Missing content-sized instance')+ const copy = graph.getChildren(instance.id)[0]+ graph.updateNode(copy.id, { x: 10, y: 20, width: 40, height: 20 })+ graph.updateNode(source.id, { opacity: 0.75 })+ graph.syncInstances(component.id)+ expect([copy.x, copy.y, copy.width, copy.height]).toEqual([30, 30, 40, 20])+ expect(copy.opacity).toBe(0.75)+ await renderTrees([renderTree(graph, instance.id)])+ await editor.canvas.waitForRender()+ const [[r, g, b]] = await readScenePixels(editor.page, [{ x: 420, y: 360 }])+ expect(g).toBeGreaterThan(Math.max(r, b))+ expect(await editor.canvas.screenshotCanvasRegion()).toMatchSnapshot('content-size-anchor.png')+})++test('layout keeps a rotated imported Hug panel inside its instance', async () => {+ const guid = (localID: number) => ({ sessionID: 1, localID })+ const { graph, sources } = materializeDocument(+ [+ { guid: guid(0), type: 'DOCUMENT' },+ { guid: guid(1), type: 'CANVAS', parentIndex: { guid: guid(0), position: '!' } },+ {+ guid: guid(2),+ type: 'SYMBOL',+ parentIndex: { guid: guid(1), position: '!' },+ size: { x: 100, y: 80 },+ stackMode: 'VERTICAL',+ stackPrimarySizing: 'FIXED',+ stackCounterSizing: 'FIXED'+ },+ {+ guid: guid(3),+ type: 'FRAME',+ parentIndex: { guid: guid(2), position: '!' },+ size: { x: 80, y: 40 },+ stackMode: 'VERTICAL',+ stackPrimarySizing: 'RESIZE_TO_FIT',+ transform: { m00: -1, m01: 0, m02: 80, m10: 0, m11: -1, m12: 40 },+ fillPaints: [{ type: 'SOLID', color: { r: 0.1, g: 0.7, b: 0.3, a: 1 } }]+ },+ {+ guid: guid(4),+ type: 'INSTANCE',+ parentIndex: { guid: guid(1), position: '"' },+ size: { x: 100, y: 80 },+ symbolData: { symbolID: guid(2) }+ }+ ] as NodeChange[],+ [],+ { derivedBounds: true }+ )+ const instance = sources.get('1:4')+ if (!instance) throw new Error('Missing rotated panel instance')+ computeAllLayouts(graph)+ const panel = graph.getChildren(instance)[0]+ expect(panel.x).toBeCloseTo(0)+ expect(panel.y).toBeCloseTo(0)+ expect(panel.rotation).toBe(180)+ await renderTrees([renderTree(graph, instance)])+ await editor.canvas.waitForRender()+ const [[r, g, b]] = await readScenePixels(editor.page, [{ x: 240, y: 240 }])+ expect(g).toBeGreaterThan(Math.max(r, b))+ expect(await editor.canvas.screenshotCanvasRegion()).toMatchSnapshot('rotated-imported-hug.png')+})++test('a bound root swap renders its replacement paint rather than its old cache', async () => {+ const guid = (localID: number) => ({ sessionID: 1, localID })+ const paint = (r: number, g: number): NonNullable<NodeChange['fillPaints']> => [+ { type: 'SOLID', color: { r, g, b: 0, a: 1 }, opacity: 1, visible: true }+ ]+ const records: NodeChange[] = [+ { guid: guid(0), type: 'DOCUMENT' },+ { guid: guid(1), type: 'CANVAS', parentIndex: { guid: guid(0), position: '!' } },+ {+ guid: guid(2),+ type: 'SYMBOL',+ parentIndex: { guid: guid(1), position: '!' },+ size: { x: 40, y: 40 },+ fillPaints: paint(1, 0)+ },+ {+ guid: guid(3),+ type: 'SYMBOL',+ parentIndex: { guid: guid(1), position: '"' },+ size: { x: 40, y: 40 },+ fillPaints: paint(0, 1)+ },+ {+ guid: guid(4),+ type: 'SYMBOL',+ parentIndex: { guid: guid(1), position: '#' },+ size: { x: 40, y: 40 },+ componentPropDefs: [+ { id: guid(90), type: 'INSTANCE_SWAP', initialValue: { guidValue: guid(2) } }+ ]+ },+ {+ guid: guid(5),+ type: 'INSTANCE',+ parentIndex: { guid: guid(4), position: '!' },+ size: { x: 40, y: 40 },+ fillPaints: paint(1, 0),+ symbolData: { symbolID: guid(2) },+ componentPropRefs: [{ defID: guid(90), componentPropNodeField: 'OVERRIDDEN_SYMBOL_ID' }]+ },+ {+ guid: guid(6),+ type: 'INSTANCE',+ parentIndex: { guid: guid(1), position: '!' },+ size: { x: 40, y: 40 },+ symbolData: { symbolID: guid(4) },+ componentPropAssignments: [{ defID: guid(90), value: { guidValue: guid(3) } }]+ }+ ]+ const { graph, sources } = materializeDocument(records, [], { derivedBounds: true })+ const instance = sources.get('1:6')+ if (!instance) throw new Error('Missing paint-swap instance')+ expect(graph.getChildren(instance)[0].fills[0].color.g).toBe(1)+ await renderTrees([renderTree(graph, instance)])+ await editor.canvas.waitForRender()+ const [[r, g, b]] = await readScenePixels(editor.page, [{ x: 240, y: 240 }])+ expect(g).toBeGreaterThan(Math.max(r, b))+ expect(await editor.canvas.screenshotCanvasRegion()).toMatchSnapshot('bound-swap-root-paint.png')+ await initCodec()+ const bytes = writeFigArchive({+ schemaDeflated: deflateSync(getSchemaBytes()),+ kiwiData: encodeMessage(createNodeChangesMessage(0, 0, records)),+ thumbnailPNG: new Uint8Array(),+ metaJSON: '{}'+ })+ const workerPaint = await editor.page.evaluate(+ async (saved) => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('Editor unavailable')+ await store.openFigFile(new File([new Uint8Array(saved)], 'Bound-swap.fig'))+ const root = store.graph+ .getChildren(store.state.currentPageId)+ .find(+ (node) =>+ node.type === 'INSTANCE' && node.componentPropertyAssignments['1:90'] !== undefined+ )+ if (!root) throw new Error('Imported bound instance unavailable')+ return store.graph.getChildren(root.id)[0].fills[0].color+ },+ [...bytes]+ )+ expect(workerPaint.g).toBe(1)+ await editor.page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('Editor unavailable')+ store.pan(-store.state.panX, -store.state.panY)+ store.setZoomAroundPoint(1, 0, 0)+ })+})+test('absolute constraints survive occurrence resizing', async () => {const { graph, sources } = materializeDocument(absoluteConstraintRecords())const id = sources.get('1:4')diff --git a/tests/e2e/canvas/instance-scale-visual.spec.ts-snapshots/bound-swap-root-paint-openpencil-darwin.png b/tests/e2e/canvas/instance-scale-visual.spec.ts-snapshots/bound-swap-root-paint-openpencil-darwin.pngnew file mode 100644index 000000000..935fe4625Binary files /dev/null and b/tests/e2e/canvas/instance-scale-visual.spec.ts-snapshots/bound-swap-root-paint-openpencil-darwin.png differdiff --git a/tests/e2e/canvas/instance-scale-visual.spec.ts-snapshots/content-size-anchor-openpencil-darwin.png b/tests/e2e/canvas/instance-scale-visual.spec.ts-snapshots/content-size-anchor-openpencil-darwin.pngnew file mode 100644index 000000000..be1d0621bBinary files /dev/null and b/tests/e2e/canvas/instance-scale-visual.spec.ts-snapshots/content-size-anchor-openpencil-darwin.png differdiff --git a/tests/e2e/canvas/instance-scale-visual.spec.ts-snapshots/nested-visibility-scope-openpencil-darwin.png b/tests/e2e/canvas/instance-scale-visual.spec.ts-snapshots/nested-visibility-scope-openpencil-darwin.pngnew file mode 100644index 000000000..92b6a30ddBinary files /dev/null and b/tests/e2e/canvas/instance-scale-visual.spec.ts-snapshots/nested-visibility-scope-openpencil-darwin.png differdiff --git a/tests/e2e/canvas/instance-scale-visual.spec.ts-snapshots/rotated-imported-hug-openpencil-darwin.png b/tests/e2e/canvas/instance-scale-visual.spec.ts-snapshots/rotated-imported-hug-openpencil-darwin.pngnew file mode 100644index 000000000..8ebd73431Binary files /dev/null and b/tests/e2e/canvas/instance-scale-visual.spec.ts-snapshots/rotated-imported-hug-openpencil-darwin.png differdiff --git a/tests/engine/render/canvas/image-fill.test.ts b/tests/engine/render/canvas/image-fill.test.tsindex 6ea0b0c5d..45cd3ad74 100644--- a/tests/engine/render/canvas/image-fill.test.ts+++ b/tests/engine/render/canvas/image-fill.test.ts@@ -1,25 +1,10 @@-import { describe, expect, mock, test } from 'bun:test'+import { describe, expect, test } from 'bun:test'import type { Fill, SceneNode } from '@open-pencil/scene-graph'+import Matrix from '@open-pencil/scene-graph/matrix'import { makeImageFillLocalMatrix, patternTileLayout } from '#core/canvas/fills'-import { asRenderer } from './helpers'--function createRenderer() {- return asRenderer({- ck: {- Matrix: {- identity: mock(() => ['identity']),- invert: mock((matrix) => ['invert', matrix]),- multiply: mock((...matrices) => ['multiply', ...matrices]),- scaled: mock((x, y) => ['scaled', x, y]),- translated: mock((x, y) => ['translated', x, y])- }- }- })-}-const node = {width: 120,height: 80@@ -68,6 +53,20 @@ describe('canvas pattern fills', () => {})})+/** Where image pixels land on the 120 × 80 layer. */+function place(fill: Partial<Fill>, imageWidth: number, imageHeight: number, points: number[]) {+ const image: Fill = {+ type: 'IMAGE',+ color: { r: 0, g: 0, b: 0, a: 1 },+ opacity: 1,+ visible: true,+ ...fill+ }+ const matrix = makeImageFillLocalMatrix(image, node, imageWidth, imageHeight)+ // Adding zero turns -0 into 0, which reads the same on the layer.+ return Matrix.mapPoints(matrix, points).map((value) => Math.round(value * 1000) / 1000 + 0)+}+describe('canvas image fills', () => {test.each([{ width: 100, height: 100, scale: 0.8, x: 20, y: 0 },@@ -76,46 +75,36 @@ describe('canvas image fills', () => {])('centers FIT images without stretching ($width × $height)',({ width, height, scale, x, y }) => {- const renderer = createRenderer()- const fill = { type: 'IMAGE', imageScaleMode: 'FIT' } as Fill- expect<unknown>(makeImageFillLocalMatrix(renderer, fill, node, width, height)).toEqual([- 'multiply',- ['translated', x, y],- ['scaled', scale, scale]+ expect(place({ imageScaleMode: 'FIT' }, width, height, [0, 0, width, height])).toEqual([+ x,+ y,+ x + width * scale,+ y + height * scale])})- test('keeps untransformed tile fills in image pixel space', () => {- const renderer = createRenderer()- const fill = { type: 'IMAGE', imageScaleMode: 'TILE' } as Fill-- const matrix = makeImageFillLocalMatrix(renderer, fill, node, 24, 16)-- expect<unknown>(matrix).toEqual(['identity'])- expect(renderer.ck.Matrix.identity).toHaveBeenCalled()- expect(renderer.ck.Matrix.scaled).not.toHaveBeenCalled()+ test('draws a tile at the image’s own size from the top left, times its scale', () => {+ expect(place({ imageScaleMode: 'TILE' }, 24, 16, [0, 0, 24, 16])).toEqual([0, 0, 24, 16])+ expect(place({ imageScaleMode: 'TILE', scale: 0.5 }, 24, 16, [24, 16])).toEqual([12, 8])})- test('uses the full imported affine transform for patterned image fills', () => {- const renderer = createRenderer()- const transform = { m00: 0.5, m01: 0.1, m02: 0.25, m10: -0.2, m11: 0.25, m12: 0.5 }- const fill = {- type: 'IMAGE',- imageScaleMode: 'TILE',- imageTransform: transform- } as Fill-- const matrix = makeImageFillLocalMatrix(renderer, fill, node, 40, 40)+ test('ignores the crop a tile keeps from before, as Figma does', () => {+ const imageTransform = { m00: 0.5, m01: 0, m02: 0.25, m10: 0, m11: 0.5, m12: 0.25 }+ expect(place({ imageScaleMode: 'TILE', imageTransform }, 24, 16, [24, 16])).toEqual([24, 16])+ })- expect(renderer.ck.Matrix.invert).toHaveBeenCalledWith([- 0.5, 0.1, 0.25, -0.2, 0.25, 0.5, 0, 0, 1+ test('shows the window of the image a crop holds across the whole layer', () => {+ const imageTransform = { m00: 0.5, m01: 0, m02: 0.25, m10: 0, m11: 0.5, m12: 0.25 }+ expect(place({ imageScaleMode: 'CROP', imageTransform }, 40, 40, [10, 10, 30, 30])).toEqual([+ 0, 0, 120, 80])- expect<unknown>(matrix).toEqual([- 'multiply',- ['scaled', 120, 80],- ['invert', [0.5, 0.1, 0.25, -0.2, 0.25, 0.5, 0, 0, 1]],- ['scaled', 0.025, 0.025]+ })++ test('turns a Fill image clockwise before covering the layer', () => {+ // A 40 × 60 image turned a quarter is 60 × 40, the layer's shape at half its size.+ expect(place({ imageScaleMode: 'FILL', imageRotation: 90 }, 40, 60, [0, 0, 40, 0])).toEqual([+ 120, 0, 120, 80])})})