Skip to content

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

fix(core): show imported page backgrounds and stop fixed text collapsing

Danila Poyarkovb7126322eb69
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1ece8f51c..4353b1dd3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -39,6 +39,9 @@
- Draw collaborators' names on their cursors with proper letter spacing and fallback fonts, and end long names with an ellipsis.
- Keep line breaks in multi-line text when exporting OpenPencil JSX, so `get_jsx` output and `openpencil export -f jsx` render back to the same text instead of joining the lines with spaces.
- Announce unavailable commands in the command palette as disabled to screen readers.
+- Show an imported Figma page's background, and keep a background you change when you switch pages or save the document.
+- Keep fixed-size text from collapsing and clipping beside smaller siblings in a Hug auto-layout container.
+- Keep the text and icon an instance was given when a page loads on its own, instead of resynchronising it back to the component's defaults.
- Keep the ordering keys a `.fig` gave its layers when saving one again, instead of renumbering every sibling, and give every layer on a canvas its own key. Shared styles, variables and the canvas's own layers were numbered in separate passes that each restarted, so Figma saw siblings claiming the same position and ordered them arbitrarily.
- Clear a `.fig` fill or stroke's colour-variable binding when you unbind it, instead of exporting the variable the layer was imported with and rebinding it on reopen. An emptied binding record is no longer written into the file either.
- Keep an AI reply running in the chat panel, with its Stop button, when you switch pages, instead of detaching the panel from the reply in progress.
diff --git a/packages/core/src/editor/component-sync.ts b/packages/core/src/editor/component-sync.ts
index ac69effe8..ff893f68e 100644
--- a/packages/core/src/editor/component-sync.ts
+++ b/packages/core/src/editor/component-sync.ts
@@ -110,7 +110,9 @@ export function createComponentSyncScheduler(
}
function scheduleComponentSync(nodeId: string) {
- if (isFlushingComponentSync) return
+ // Import/materialization has already resolved component overrides. These updates
+ // are not authored component edits and must not reset instances to their defaults.
+ if (isFlushingComponentSync || getGraph().isApplyingImportedState) return
if (!pendingComponentSync) {
pendingComponentSync = new Set()
queueMicrotask(flushComponentSync)
diff --git a/packages/core/src/editor/page-viewports.ts b/packages/core/src/editor/page-viewports.ts
index 59a46e16e..9589a143e 100644
--- a/packages/core/src/editor/page-viewports.ts
+++ b/packages/core/src/editor/page-viewports.ts
@@ -1,42 +1,32 @@
-import type { Color } from '@open-pencil/scene-graph/primitives'
-
-import { CANVAS_BG_COLOR } from '#core/constants'
+import { getPageColor } from '#core/figma-api/page-backgrounds'
+import type { ViewportTransform } from '#core/geometry/types'
import type { EditorContext } from './types'
-interface PageViewport {
- panX: number
- panY: number
- zoom: number
- pageColor: Color
-}
-
export function createPageViewportStore(ctx: EditorContext) {
- const pageViewports = new Map<string, PageViewport>()
+ const pageViewports = new Map<string, ViewportTransform>()
function saveCurrentPageViewport() {
pageViewports.set(ctx.state.currentPageId, {
panX: ctx.state.panX,
panY: ctx.state.panY,
- zoom: ctx.state.zoom,
- pageColor: { ...ctx.state.pageColor }
+ zoom: ctx.state.zoom
})
}
function restorePageViewport(pageId: string) {
+ ctx.state.pageColor = getPageColor(ctx.graph.getNode(pageId))
const viewport = pageViewports.get(pageId)
if (viewport) {
ctx.state.panX = viewport.panX
ctx.state.panY = viewport.panY
ctx.state.zoom = viewport.zoom
- ctx.state.pageColor = { ...viewport.pageColor }
return
}
ctx.state.panX = 0
ctx.state.panY = 0
ctx.state.zoom = 1
- ctx.state.pageColor = { ...CANVAS_BG_COLOR }
}
function deletePageViewport(pageId: string) {
diff --git a/packages/core/src/editor/pages.ts b/packages/core/src/editor/pages.ts
index 010808e8c..cda2d14b8 100644
--- a/packages/core/src/editor/pages.ts
+++ b/packages/core/src/editor/pages.ts
@@ -2,6 +2,7 @@ import { limitAsync } from 'es-toolkit/promise'
import type { Color } from '@open-pencil/scene-graph/primitives'
+import { getPageColor, setPageBackgrounds } from '#core/figma-api/page-backgrounds'
import {
canUseFigPopulationWorker,
createFigPopulationWorker
@@ -41,6 +42,14 @@ function throwIfAborted(signal?: AbortSignal): void {
const MAX_CONCURRENT_FONT_LOADS = 4
export function createPageActions(ctx: EditorContext) {
const pageViewportStore = createPageViewportStore(ctx)
+ function syncPageColor() {
+ ctx.state.pageColor = getPageColor(ctx.graph.getNode(ctx.state.currentPageId))
+ }
+ syncPageColor()
+ ctx.onEditorEvent('graph:replaced', syncPageColor)
+ ctx.onEditorEvent('node:updated', (id, changes) => {
+ if (id === ctx.state.currentPageId && changes.source) syncPageColor()
+ })
let populationWorkerInstance: ReturnType<typeof createFigPopulationWorker> | undefined
let populationWorkerGeneration = 0
let pageSwitchGeneration = 0
@@ -241,7 +250,12 @@ export function createPageActions(ctx: EditorContext) {
}
function setPageColor(color: Color) {
- ctx.state.pageColor = color
+ const page = ctx.graph.getNode(ctx.state.currentPageId)
+ if (!page) return
+ setPageBackgrounds(ctx.graph, page, [
+ { type: 'SOLID', color: { ...color }, opacity: 1, visible: true, blendMode: 'NORMAL' }
+ ])
+ syncPageColor()
ctx.requestRender()
}
diff --git a/packages/core/src/figma-api/page-backgrounds.ts b/packages/core/src/figma-api/page-backgrounds.ts
index 938f8bdf2..ecdc6dc01 100644
--- a/packages/core/src/figma-api/page-backgrounds.ts
+++ b/packages/core/src/figma-api/page-backgrounds.ts
@@ -30,6 +30,14 @@ export function getPageBackgrounds(page: SceneNode): readonly Fill[] {
return Object.freeze(copyFills(fills))
}
+/** Project the supported visible solid page paint into editor view state. */
+export function getPageColor(page: SceneNode | undefined): Color {
+ const paint =
+ page && getPageBackgrounds(page).find((fill) => fill.visible && fill.type === 'SOLID')
+ if (!paint) return { ...CANVAS_BG_COLOR }
+ return { ...paint.color, a: paint.color.a * paint.opacity }
+}
+
export function setPageBackgrounds(
graph: SceneGraph,
page: SceneNode,
diff --git a/packages/core/src/io/formats/fig/export.ts b/packages/core/src/io/formats/fig/export.ts
index 7312af971..23e18ec05 100644
--- a/packages/core/src/io/formats/fig/export.ts
+++ b/packages/core/src/io/formats/fig/export.ts
@@ -132,8 +132,6 @@ function assignComponentPropertyGuids(
}
function applyImportedCanvasFields(page: FigExportPage, canvasNc: KiwiNodeChange): void {
- if (!page.source.id) return
- if (!('pageType' in page.source.fig.rawNodeFields)) delete canvasNc.pageType
if ('backgroundColor' in page.source.fig.rawNodeFields) {
canvasNc.backgroundColor = structuredClone(page.source.fig.rawNodeFields.backgroundColor)
}
@@ -142,6 +140,8 @@ function applyImportedCanvasFields(page: FigExportPage, canvasNc: KiwiNodeChange
page.source.fig.rawNodeFields.backgroundPaints
) as NodeChange['backgroundPaints']
}
+ if (!page.source.id) return
+ if (!('pageType' in page.source.fig.rawNodeFields)) delete canvasNc.pageType
if (page.guides.length > 0) {
const normalized = exportCanvasGuides(page.guides)
const raw = page.source.fig.rawNodeFields.guides
diff --git a/packages/core/src/kiwi/fig/population/delta.ts b/packages/core/src/kiwi/fig/population/delta.ts
index a64feabd5..7359ae6b1 100644
--- a/packages/core/src/kiwi/fig/population/delta.ts
+++ b/packages/core/src/kiwi/fig/population/delta.ts
@@ -122,7 +122,7 @@ export function buildFigPopulationDelta(
}
export function applyFigPopulationDelta(graph: SceneGraph, delta: FigPopulationDelta): void {
- graph.preserveSourceMetadataDuring(() => {
+ graph.applyImportedStateDuring(() => {
for (const [, node] of delta.created) {
graph.createNodeWithId(node.id, node.type, node.parentId, node)
}
diff --git a/packages/core/src/layout.ts b/packages/core/src/layout.ts
index e1155d653..1fbf5ae6c 100644
--- a/packages/core/src/layout.ts
+++ b/packages/core/src/layout.ts
@@ -29,6 +29,7 @@ import { estimateTextSize, getTextMeasurer } from './layout/text-measurement'
import {
applyMinMaxConstraints,
configureAbsoluteChild,
+ configureNonTextLeaf,
createYogaNode,
freeYogaTree,
mapAlign,
@@ -449,6 +450,12 @@ function configureChildAsLeaf(
configureTextLeafWithoutMeasurer(yogaChild, child, parent, fixedDerivedMainAxis)
} else {
configureNonTextLeaf(yogaChild, child, isRow, stretchCross)
+ // Fixed text still contributes its box to a HUG cross axis. Without
+ // an intrinsic minimum, stretch collapses the text to its siblings.
+ if (isText && stretchCross && parent.counterAxisSizing === 'HUG') {
+ if (isRow) yogaChild.setMinHeight(child.height)
+ else yogaChild.setMinWidth(child.width)
+ }
}
const selfAlign = mapAlignSelf(child.layoutAlignSelf)
@@ -529,32 +536,6 @@ function configureTextLeaf(
}
}
-function configureNonTextLeaf(
- yogaChild: YogaNode,
- child: SceneNode,
- isRow: boolean,
- stretchCross: boolean
-): void {
- const w = child.width
- const h = child.height
-
- if (child.layoutGrow > 0) {
- yogaChild.setFlexGrow(child.layoutGrow)
- if (!stretchCross) {
- if (isRow) yogaChild.setHeight(h)
- else yogaChild.setWidth(w)
- }
- } else {
- if (isRow) {
- yogaChild.setWidth(w)
- if (!stretchCross) yogaChild.setHeight(h)
- } else {
- yogaChild.setHeight(h)
- if (!stretchCross) yogaChild.setWidth(w)
- }
- }
-}
-
function setMainAxisSizing(
yogaNode: YogaNode,
axis: 'width' | 'height',
diff --git a/packages/core/src/layout/yoga-helpers.ts b/packages/core/src/layout/yoga-helpers.ts
index 7d6fa5e0f..980877bcb 100644
--- a/packages/core/src/layout/yoga-helpers.ts
+++ b/packages/core/src/layout/yoga-helpers.ts
@@ -24,6 +24,32 @@ export function configureAbsoluteChild(yogaChild: YogaNode, child: SceneNode): v
yogaChild.setHeight(child.height)
}
+export function configureNonTextLeaf(
+ yogaChild: YogaNode,
+ child: SceneNode,
+ isRow: boolean,
+ stretchCross: boolean
+): void {
+ const w = child.width
+ const h = child.height
+
+ if (child.layoutGrow > 0) {
+ yogaChild.setFlexGrow(child.layoutGrow)
+ if (!stretchCross) {
+ if (isRow) yogaChild.setHeight(h)
+ else yogaChild.setWidth(w)
+ }
+ } else {
+ if (isRow) {
+ yogaChild.setWidth(w)
+ if (!stretchCross) yogaChild.setHeight(h)
+ } else {
+ yogaChild.setHeight(h)
+ if (!stretchCross) yogaChild.setWidth(w)
+ }
+ }
+}
+
export function applyMinMaxConstraints(yogaNode: YogaNode, node: SceneNode): void {
if (node.minWidth != null) yogaNode.setMinWidth(node.minWidth)
if (node.maxWidth != null) yogaNode.setMaxWidth(node.maxWidth)
diff --git a/packages/core/tests/editor/page-backgrounds.test.ts b/packages/core/tests/editor/page-backgrounds.test.ts
new file mode 100644
index 000000000..facca00f9
--- /dev/null
+++ b/packages/core/tests/editor/page-backgrounds.test.ts
@@ -0,0 +1,96 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core/editor'
+import { FigmaAPI } from '@open-pencil/core/figma-api'
+import { exportFigFile, parseFigFile } from '@open-pencil/core/io'
+import { SceneGraph } from '@open-pencil/scene-graph'
+import type { Color } from '@open-pencil/scene-graph'
+
+// Exact float32 backgroundColor from the reported finance FIG canvas 0:4.
+const navy: Color = {
+ r: 0.027450980618596077,
+ g: 0.13725490868091583,
+ b: 0.3529411852359772,
+ a: 1
+}
+const red: Color = { r: 1, g: 0, b: 0, a: 1 }
+
+function importedGraph() {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ page.source.fig.rawNodeFields.backgroundColor = { ...navy }
+ return graph
+}
+
+describe('editor page backgrounds', () => {
+ test('initializes and replaces graphs using imported canvas backgroundColor', () => {
+ const editor = createEditor({ graph: importedGraph() })
+ try {
+ expect(editor.state.pageColor).toEqual(navy)
+ editor.replaceGraph(new SceneGraph())
+ expect(editor.state.pageColor).toEqual({ r: 0.96, g: 0.96, b: 0.96, a: 1 })
+ editor.replaceGraph(importedGraph())
+ expect(editor.state.pageColor).toEqual(navy)
+ } finally {
+ editor.dispose()
+ }
+ })
+
+ test('switches using graph paint state rather than stale viewport colors', async () => {
+ const graph = importedGraph()
+ const first = graph.getPages()[0]
+ const second = graph.addPage('Second')
+ const editor = createEditor({ graph })
+ const api = new FigmaAPI(graph)
+ try {
+ editor.state.panX = 42
+ await editor.switchPage(second.id)
+ editor.setPageColor(red)
+ api.currentPage.backgrounds = [
+ { type: 'SOLID', color: { ...navy, a: 0.5 }, opacity: 0.5, visible: true }
+ ]
+ expect(editor.state.pageColor).toEqual(red)
+ await editor.switchPage(first.id)
+ expect(editor.state.panX).toBe(42)
+ expect(editor.state.pageColor).toEqual({ ...navy, a: 0.25 })
+ api.currentPage.backgrounds = []
+ expect(editor.state.pageColor).toEqual({ r: 0.96, g: 0.96, b: 0.96, a: 1 })
+ api.currentPage.backgrounds = [{ type: 'SOLID', color: red, opacity: 1, visible: false }]
+ expect(editor.state.pageColor).toEqual({ r: 0.96, g: 0.96, b: 0.96, a: 1 })
+ } finally {
+ editor.dispose()
+ }
+ })
+
+ test('imports legacy canvas color from FIG bytes without inventing background paints', async () => {
+ const bytes = await exportFigFile(importedGraph())
+ const graph = await parseFigFile(bytes.buffer as ArrayBuffer)
+ const editor = createEditor({ graph })
+ try {
+ expect(graph.getPages()[0].source.fig.rawNodeFields.backgroundPaints).toBeUndefined()
+ expect(editor.state.pageColor).toEqual(navy)
+ expect(new FigmaAPI(graph).currentPage.backgrounds[0]?.color).toEqual(navy)
+ } finally {
+ editor.dispose()
+ }
+ })
+
+ test('editor edits update API paints and survive FIG export/import', async () => {
+ const editor = createEditor({ graph: importedGraph() })
+ try {
+ const color = { ...red, a: 0.5 }
+ editor.setPageColor(color)
+ color.r = 0
+ expect(editor.state.pageColor).toEqual({ ...red, a: 0.5 })
+ const api = new FigmaAPI(editor.graph)
+ expect(api.currentPage.backgrounds[0]?.color).toEqual({ ...red, a: 0.5 })
+ const bytes = await exportFigFile(editor.graph)
+ const reloaded = await parseFigFile(bytes.buffer as ArrayBuffer)
+ editor.replaceGraph(reloaded)
+ expect(editor.state.pageColor).toEqual({ ...red, a: 0.5 })
+ expect(new FigmaAPI(reloaded).currentPage.backgrounds[0]?.color).toEqual({ ...red, a: 0.5 })
+ } finally {
+ editor.dispose()
+ }
+ })
+})
diff --git a/packages/core/tests/layout/auto-layout/text/fixed-stretch.test.ts b/packages/core/tests/layout/auto-layout/text/fixed-stretch.test.ts
new file mode 100644
index 000000000..c38bc5b64
--- /dev/null
+++ b/packages/core/tests/layout/auto-layout/text/fixed-stretch.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, test } from 'bun:test'
+
+import { computeAllLayouts, SceneGraph } from '@open-pencil/core'
+
+// Reduced from BIZUP's classification label rows: a 10px marker and a
+// fixed-size 16px text box that fills both axes in a cross-axis HUG row.
+describe('fixed text intrinsic cross-axis size', () => {
+ for (const layoutMode of ['HORIZONTAL', 'VERTICAL'] as const) {
+ test(`${layoutMode} HUG includes a stretched fixed text box`, () => {
+ const graph = new SceneGraph()
+ const row = layoutMode === 'HORIZONTAL'
+ const frame = graph.createNode('FRAME', graph.getPages()[0].id, {
+ layoutMode,
+ width: row ? 332 : 16,
+ height: row ? 16 : 332,
+ primaryAxisSizing: 'FIXED',
+ counterAxisSizing: 'HUG',
+ counterAxisAlign: 'CENTER',
+ itemSpacing: 8
+ })
+ const marker = graph.createNode('RECTANGLE', frame.id, { width: 10, height: 10 })
+ const text = graph.createNode('TEXT', frame.id, {
+ text: 'Classificação Silver',
+ width: row ? 314 : 16,
+ height: row ? 16 : 314,
+ textAutoResize: 'NONE',
+ layoutGrow: 1,
+ layoutAlignSelf: 'STRETCH'
+ })
+
+ computeAllLayouts(graph)
+ computeAllLayouts(graph)
+
+ expect(row ? frame.height : frame.width).toBe(16)
+ expect(row ? text.height : text.width).toBe(16)
+ expect(row ? text.width : text.height).toBe(314)
+ expect(row ? marker.y : marker.x).toBe(3)
+
+ // A definite parent cross size still controls stretch, not the old box.
+ graph.updateNode(frame.id, {
+ counterAxisSizing: 'FIXED',
+ ...(row ? { height: 12 } : { width: 12 })
+ })
+ computeAllLayouts(graph)
+ expect(row ? text.height : text.width).toBe(12)
+ })
+ }
+})
diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.ts
index 125147313..614e9e52c 100644
--- a/packages/scene-graph/src/index.ts
+++ b/packages/scene-graph/src/index.ts
@@ -126,6 +126,7 @@ export class SceneGraph {
private previewMutationDepth = 0
private previewObservers: NodePreviewObserver[] = []
private sourceMetadataPreservationDepth = 0
+ private importedStateApplicationDepth = 0
private layoutMutationDepth = 0
positionPreviewVersion = 0
instanceIndex = new Map<string, Set<string>>()
@@ -421,6 +422,23 @@ export class SceneGraph {
this.sourceMetadataPreservationDepth--
}
}
+ get isPreservingSourceMetadata(): boolean {
+ return this.sourceMetadataPreservationDepth > 0
+ }
+
+ applyImportedStateDuring(fn: () => void): void {
+ this.importedStateApplicationDepth++
+ try {
+ this.preserveSourceMetadataDuring(fn)
+ } finally {
+ this.importedStateApplicationDepth--
+ }
+ }
+
+ get isApplyingImportedState(): boolean {
+ return this.importedStateApplicationDepth > 0
+ }
+
withLayoutMutations(fn: () => void): void {
this.layoutMutationDepth++
try {
diff --git a/tests/engine/io/fig/import/population-delta.test.ts b/tests/engine/io/fig/import/population-delta.test.ts
index 30b6b80fc..9bf4d6374 100644
--- a/tests/engine/io/fig/import/population-delta.test.ts
+++ b/tests/engine/io/fig/import/population-delta.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, test } from 'bun:test'
import { SceneGraph } from '@open-pencil/scene-graph'
+import { createEditor } from '#core/editor/create'
import {
applyFigPopulationDelta,
buildFigPopulationDelta,
@@ -9,6 +10,35 @@ import {
} from '#core/kiwi/fig/population/delta'
describe('FIG population deltas', () => {
+ test('does not resynchronize resolved imported text as a component edit', async () => {
+ const source = new SceneGraph()
+ const page = source.getPages()[0]
+ const component = source.createNode('COMPONENT', page.id)
+ const label = source.createNode('TEXT', component.id, { text: 'Área' })
+ const instance = source.createNode('INSTANCE', page.id, { componentId: component.id })
+ const target = new SceneGraph()
+ target.rootId = source.rootId
+ target.nodes = structuredClone(source.nodes)
+ const editor = createEditor({ graph: target })
+ const journal = installFigMutationJournal(source)
+ source.populateInstanceChildren(instance.id, component.id, 'fig-import')
+ const clone = source.getChildren(instance.id)[0]
+ source.updateNode(clone.id, { text: 'Cadastro' })
+ source.updateNode(label.id, { width: 120 })
+ journal.stop()
+ try {
+ applyFigPopulationDelta(target, buildFigPopulationDelta(source, journal, [page.id]))
+ await Promise.resolve()
+ expect(target.getNode(clone.id)?.text).toBe('Cadastro')
+ // Ordinary component edits still synchronize after the population scope exits.
+ target.updateNode(label.id, { text: 'Edited' })
+ await Promise.resolve()
+ expect(target.getNode(clone.id)?.text).toBe('Edited')
+ } finally {
+ editor.dispose()
+ }
+ })
+
test('captures created, updated, and deleted nodes', () => {
const graph = new SceneGraph()
const page = graph.getPages()[0]