Skip to content

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

fix(pen): draw paths and icons at their laid-out size (#1481)

Sergi Gonzalez893b9491f87c
diff --git a/changes/1481/fixed.md b/changes/1481/fixed.md
new file mode 100644
index 000000000..9fe674e8c
--- /dev/null
+++ b/changes/1481/fixed.md
@@ -0,0 +1 @@
+- `.pen` paths and icons that fill or fit their container draw at their laid-out size instead of at 100 px.
diff --git a/packages/core/tests/io/formats/pen/layout.test.ts b/packages/core/tests/io/formats/pen/layout.test.ts
index 05cbd0889..a5d0cc1f7 100644
--- a/packages/core/tests/io/formats/pen/layout.test.ts
+++ b/packages/core/tests/io/formats/pen/layout.test.ts
@@ -1,14 +1,19 @@
import { describe, expect, test } from 'bun:test'
import { layoutAuthoredNodes } from '@open-pencil/core/layout'
-import { parsePenFile, type PenDocument, type PenNode } from '@open-pencil/pen'
+import { parsePenFile, type PenDocument, type PenIconSource, type PenNode } from '@open-pencil/pen'
import { getNodeLocalMatrix } from '@open-pencil/scene-graph/coordinate'
import Matrix from '@open-pencil/scene-graph/matrix'
-function parseLayoutDocument(children: PenNode[]) {
- const document: PenDocument = { version: '2.17', children }
+function parseLayoutDocument(
+ children: PenNode[],
+ icons?: PenIconSource,
+ fields: Partial<PenDocument> = {}
+) {
+ const document: PenDocument = { version: '2.17', ...fields, children }
// As Core's .pen reader lays out what it reads.
return parsePenFile(JSON.stringify(document), {
+ icons,
layout: (graph) =>
layoutAuthoredNodes(
graph,
@@ -265,7 +270,17 @@ describe('parsePenFile — turned layers sized by layout', () => {
layout: 'none',
width: 400,
height: 300,
- children: [{ id: 'label', type: 'text', x: 100, y: 200, rotation: 90, content: 'Revenue', fontSize: 14 }]
+ children: [
+ {
+ id: 'label',
+ type: 'text',
+ x: 100,
+ y: 200,
+ rotation: 90,
+ content: 'Revenue',
+ fontSize: 14
+ }
+ ]
}
])
const label = graph.getNode('label')
@@ -298,3 +313,168 @@ describe('parsePenFile — space around', () => {
expect(['a', 'b', 'c'].map((id) => graph.getNode(id)?.x)).toEqual([35, 135, 235])
})
})
+
+describe('parsePenFile — paths sized by layout', () => {
+ test('draws a filling path at its laid-out size in a component and a resized instance', () => {
+ const graph = parseLayoutDocument([
+ {
+ id: 'mark',
+ type: 'frame',
+ reusable: true,
+ width: 64,
+ height: 64,
+ layout: 'vertical',
+ children: [
+ {
+ id: 'glyph',
+ type: 'path',
+ geometry: 'M0 0H10V10H0Z',
+ viewBox: [0, 0, 10, 10],
+ width: 'fill_container',
+ height: 'fill_container'
+ }
+ ]
+ },
+ { id: 'small', type: 'ref', ref: 'mark', width: 16, height: 16 }
+ ])
+
+ const extent = (id: string) => {
+ const vertices = graph.getNode(id)?.vectorNetwork?.vertices ?? []
+ return {
+ width: Math.max(...vertices.map((vertex) => vertex.x)),
+ height: Math.max(...vertices.map((vertex) => vertex.y))
+ }
+ }
+ const copy = graph.getNode('small')?.childIds[0] ?? ''
+ expect(extent('glyph')).toEqual({ width: 64, height: 64 })
+ expect(graph.getNode(copy)).toMatchObject({ width: 16, height: 16 })
+ expect(extent(copy)).toEqual({ width: 16, height: 16 })
+ })
+
+ test('draws a filling path at the size a second layout gives it', () => {
+ // Fitting the group to its 40 wide layer lays the row out again, widening the path.
+ const graph = parseLayoutDocument([
+ {
+ id: 'row',
+ type: 'frame',
+ width: 200,
+ height: 50,
+ children: [
+ {
+ id: 'group',
+ type: 'group',
+ children: [{ id: 'swatch', type: 'rectangle', width: 40, height: 20 }]
+ },
+ {
+ id: 'line',
+ type: 'path',
+ geometry: 'M0 0H10V10H0Z',
+ viewBox: [0, 0, 10, 10],
+ width: 'fill_container',
+ height: 50
+ }
+ ]
+ }
+ ])
+
+ const line = graph.getNode('line')
+ const xs = line?.vectorNetwork?.vertices.map((vertex) => vertex.x) ?? []
+ expect(line?.width).toBe(160)
+ expect(Math.max(...xs)).toBe(160)
+ })
+})
+
+describe('parsePenFile — icons sized by layout', () => {
+ /** Draws each glyph as one square path, `size` wide, as the Iconify source does. */
+ const icons: PenIconSource = {
+ draw(graph, frameId, name, size, color) {
+ graph.createNode('VECTOR', frameId, {
+ name,
+ width: size,
+ height: size,
+ fills: [{ type: 'SOLID', color, opacity: 1, visible: true }]
+ })
+ return true
+ }
+ }
+ const icon: PenNode = {
+ id: 'icon',
+ type: 'icon',
+ library: 'lucide',
+ icon: 'zap',
+ width: 'fill_container',
+ height: 'fill_container',
+ fill: '#FF0000'
+ }
+ const box = (id: string, children: PenNode[]): PenNode => ({
+ id,
+ type: 'frame',
+ width: 24,
+ height: 24,
+ layout: 'vertical',
+ children
+ })
+
+ test('draws a filling icon at its laid-out size in its own colour', () => {
+ const graph = parseLayoutDocument([box('box', [icon])], icons)
+ const [glyph] = graph.getChildren('icon')
+ expect(glyph).toMatchObject({ width: 24, height: 24 })
+ expect(glyph.fills[0]?.color).toEqual({ r: 1, g: 0, b: 0, a: 1 })
+ })
+
+ test('redraws a filling icon in the theme it was read in', () => {
+ const graph = parseLayoutDocument(
+ [{ ...box('box', [{ ...icon, fill: '$ink' }]), theme: { mode: 'dark' } }],
+ icons,
+ {
+ themes: { mode: ['light', 'dark'] },
+ variables: {
+ ink: {
+ type: 'color',
+ value: [
+ { value: '#FF0000', theme: { mode: 'light' } },
+ { value: '#00FF00', theme: { mode: 'dark' } }
+ ]
+ }
+ }
+ }
+ )
+ const [glyph] = graph.getChildren('icon')
+ expect(glyph).toMatchObject({ width: 24, height: 24 })
+ expect(glyph.fills[0]?.color).toEqual({ r: 0, g: 1, b: 0, a: 1 })
+ })
+
+ test('draws a filling icon in a component at the size of each instance', () => {
+ const graph = parseLayoutDocument(
+ [
+ { ...box('mark', [icon]), reusable: true },
+ { id: 'same', type: 'ref', ref: 'mark' },
+ { id: 'large', type: 'ref', ref: 'mark', width: 40, height: 40 }
+ ],
+ icons
+ )
+ const glyphSize = (iconId: string) => {
+ const [glyph] = graph.getChildren(iconId)
+ return { width: glyph.width, height: glyph.height }
+ }
+ const copy = (instanceId: string) => graph.getNode(instanceId)?.childIds[0] ?? ''
+ expect(glyphSize('icon')).toEqual({ width: 24, height: 24 })
+ expect(glyphSize(copy('same'))).toEqual({ width: 24, height: 24 })
+ expect(glyphSize(copy('large'))).toEqual({ width: 40, height: 40 })
+ })
+
+ test('keeps only the icon components a laid-out icon shows', () => {
+ const graph = parseLayoutDocument(
+ [
+ { ...box('mark', [icon]), reusable: true },
+ { id: 'large', type: 'ref', ref: 'mark', width: 40, height: 40 }
+ ],
+ icons
+ )
+ const iconPage = graph.getPages(true).find((page) => page.name === 'Icons')
+ expect(graph.getChildren(iconPage?.id ?? '').map((component) => component.name)).toEqual([
+ 'lucide/zap/24x24',
+ 'lucide/zap/40x40'
+ ])
+ })
+})
diff --git a/packages/pen/src/icons.ts b/packages/pen/src/icons.ts
index a725f8f57..25f36d3bd 100644
--- a/packages/pen/src/icons.ts
+++ b/packages/pen/src/icons.ts
@@ -5,6 +5,7 @@ import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { BLACK } from '@open-pencil/scene-graph/constants'
import { readIconTint } from '@open-pencil/scene-graph/icons'
import {
+ getInstances,
INSTANCE_SYNC_PROPS,
instanceMainComponent,
populateInstanceChildren,
@@ -123,6 +124,17 @@ function keepOwnFields(
recordInstanceOverride(graph, instanceId, differing)
}
+/**
+ * Whether a copy of an icon still shows the glyph its source showed when it was copied: drawing
+ * the source again at its laid-out size gives it a new glyph, which the copy does not follow.
+ */
+function showsReplacedGlyph(graph: SceneGraph, copy: SceneNode, sourceId: string): boolean {
+ const sourceChildIds = graph.getNode(sourceId)?.childIds ?? []
+ return graph
+ .getChildren(copy.id)
+ .some((glyph) => !glyph.componentId || !sourceChildIds.includes(glyph.componentId))
+}
+
/**
* Makes the icon instance `node` show its icon: the icon component for its glyph and size,
* swapped in when an override changed either, with the glyph in the icon's fill colour.
@@ -140,7 +152,22 @@ export function useIconComponent(node: SceneNode, pen: PenNode, build: Build): v
swapInstanceComponent(graph, node.id, componentId, { keepName: true })
// The layer keeps its own name rather than the icon's, which a saved file keeps as an override.
recordInstanceOverride(graph, node.id, ['name'])
+ } else if (showsReplacedGlyph(graph, node, node.componentId)) {
+ for (const childId of node.childIds) graph.deleteNode(childId)
+ populateInstanceChildren(graph, node.id, node.componentId)
}
keepOwnFields(graph, node.id, own, componentId)
recolorGlyph(graph, node.id, color)
}
+
+/**
+ * Removes the icon components no icon shows any more: those for the sizes reading guessed before
+ * laying out gave the icons theirs.
+ */
+export function removeUnusedIconComponents(build: Build): void {
+ for (const [key, id] of build.iconComponents) {
+ if (getInstances(build.graph, id).length > 0) continue
+ build.graph.deleteNode(id)
+ build.iconComponents.delete(key)
+ }
+}
diff --git a/packages/pen/src/instances.ts b/packages/pen/src/instances.ts
index 1b6cdf219..c2b6712d5 100644
--- a/packages/pen/src/instances.ts
+++ b/packages/pen/src/instances.ts
@@ -52,7 +52,7 @@ function resolvePath(graph: SceneGraph, instance: SceneNode, path: string): Scen
}
/** Runs `apply` in the merged theme of a layer's ancestors, as the layer was read in. */
-function inAncestorThemes<T>(build: Build, node: SceneNode, apply: () => T): T {
+export function inAncestorThemes<T>(build: Build, node: SceneNode, apply: () => T): T {
const chain: Record<string, string>[] = []
for (let id = node.parentId; id; id = build.graph.getNode(id)?.parentId ?? null) {
const theme = build.effective.get(id)?.theme
diff --git a/packages/pen/src/nodes.ts b/packages/pen/src/nodes.ts
index 96c70d9e4..59974cc2f 100644
--- a/packages/pen/src/nodes.ts
+++ b/packages/pen/src/nodes.ts
@@ -11,7 +11,7 @@ import { fillSizingFields } from '@open-pencil/scene-graph/layout'
import type { Color } from '@open-pencil/scene-graph/primitives'
import { convertEffects } from './effects'
-import { ellipseArc, pathNetwork } from './geometry'
+import { ellipseArc } from './geometry'
import { drawIcon, insideComponent, useIconComponent } from './icons'
import type { PenImages } from './images'
import {
@@ -222,6 +222,22 @@ export function fieldsSetBy(pen: PenOverride): (keyof SceneNode)[] {
return Object.keys(pen).flatMap((key) => (isProperty(key) ? PROPERTY_FIELDS[key] : []))
}
+function drawIconLayer(node: SceneNode, pen: PenNode, build: Build): void {
+ if (node.type === 'INSTANCE') useIconComponent(node, pen, build)
+ else drawIcon(node, pen, build)
+}
+
+/**
+ * Draws a filling or fitting icon again at its laid-out size, which reading it could only guess.
+ * Drawing takes the icon's colour from its fill and moves it to the glyph, so the fill is read again.
+ */
+export function redrawIconAtLaidOutSize(node: SceneNode, pen: PenNode, build: Build): void {
+ const { w, h } = resolveSizing(pen, build.ctx)
+ if (w.sizing === 'FIXED' && h.sizing === 'FIXED') return
+ node.fills = convertPaints(pen.fill, 'fills', build.ctx, node, build.images)
+ drawIconLayer(node, pen, build)
+}
+
/**
* Sets every field a layer takes from its pen.dev fields, so a layer copied from a component can be
* given its overrides by applying its merged fields again. Turned and mirrored layers are built
@@ -285,14 +301,9 @@ export function applyPenProperties(node: SceneNode, pen: PenNode, build: Build):
// Text without a width resizes to its content, which laying out the document measures.
if (isTextLike) applyTextProps(node, pen, ctx)
- if (pen.type === 'icon' && node.type === 'INSTANCE') useIconComponent(node, pen, build)
- else if (pen.type === 'icon') drawIcon(node, pen, build)
+ if (pen.type === 'icon') drawIconLayer(node, pen, build)
if (pen.type === 'ellipse') node.arcData = ellipseArc(pen, ctx)
if (pen.type === 'polygon') node.pointCount = Math.max(3, resolveNumber(pen.polygonCount, ctx, 3))
- if (pen.type === 'path') {
- const network = pathNetwork(pen, node.width, node.height)
- if (network) node.vectorNetwork = network
- }
if (flowLayout !== 'NONE') {
if (w.sizing === 'FILL') Object.assign(node, fillSizingFields(flowLayout, 'HORIZONTAL'))
diff --git a/packages/pen/src/read.ts b/packages/pen/src/read.ts
index c8e305a1c..350251da6 100644
--- a/packages/pen/src/read.ts
+++ b/packages/pen/src/read.ts
@@ -2,10 +2,12 @@ import * as v from 'valibot'
import { SceneGraph } from '@open-pencil/scene-graph'
+import { pathNetwork } from './geometry'
+import { removeUnusedIconComponents } from './icons'
import { createImageStore } from './images'
-import { populateInstances } from './instances'
+import { inAncestorThemes, populateInstances } from './instances'
import { spreadAround } from './layout'
-import { createSceneNode, type Build, type PenIconSource } from './nodes'
+import { createSceneNode, redrawIconAtLaidOutSize, type Build, type PenIconSource } from './nodes'
import { placeLayers } from './placement'
import { penFileSchema, type PenDocument, type PenNode } from './schema'
import { buildVarContext } from './variables'
@@ -40,6 +42,31 @@ function groupsInFlow(graph: SceneGraph, groupIds: Iterable<string>): boolean {
return false
}
+/**
+ * Draws each path in its box once boxes have their final size, which fill and fit sizing only give
+ * once laid out, and redraws each icon laying out sized.
+ */
+function drawAtFinalSize(build: Build, laidOut: boolean): void {
+ for (const [id, pen] of build.effective) {
+ const node = build.graph.getNode(id)
+ if (!node) continue
+ if (pen.type === 'path') {
+ const network = pathNetwork(pen, node.width, node.height)
+ if (network) node.vectorNetwork = network
+ } else if (pen.type === 'icon' && laidOut) {
+ // In the themes the icon was read in, which its colour and glyph may take variables from.
+ inAncestorThemes(build, node, () => {
+ const leave = pen.theme ? build.ctx.enterTheme(pen.theme) : undefined
+ try {
+ redrawIconAtLaidOutSize(node, pen, build)
+ } finally {
+ leave?.()
+ }
+ })
+ }
+ }
+}
+
/** A `.pen` document's JSON, validated; throws for text that is not one. */
export function parsePenDocument(json: string): PenDocument {
const parsed = v.safeParse(penFileSchema, json)
@@ -79,9 +106,14 @@ export function buildPenGraph(doc: PenDocument, options: PenReadOptions = {}): S
populateInstances(build)
options.layout?.(graph)
+ drawAtFinalSize(build, options.layout !== undefined)
const spread = options.layout ? spreadAround(graph, [...build.aroundIds]) : false
placeLayers(graph, build.placements, [...build.groupIds])
- if (spread || groupsInFlow(graph, build.groupIds)) options.layout?.(graph)
+ if (options.layout && (spread || groupsInFlow(graph, build.groupIds))) {
+ options.layout(graph)
+ drawAtFinalSize(build, true)
+ }
+ removeUnusedIconComponents(build)
if (graph.getPages(true).length === 0) {
graph.addPage('Page 1')
diff --git a/tests/fixtures/pen-oracles/dqtl8.png b/tests/fixtures/pen-oracles/dqtl8.png
new file mode 100644
index 000000000..e19310108
Binary files /dev/null and b/tests/fixtures/pen-oracles/dqtl8.png differ
diff --git a/tests/fixtures/pen-oracles/manifest.json b/tests/fixtures/pen-oracles/manifest.json
index 4885bc981..dde29d668 100644
--- a/tests/fixtures/pen-oracles/manifest.json
+++ b/tests/fixtures/pen-oracles/manifest.json
@@ -102,6 +102,11 @@
"node": "P Icon variables",
"penNodeId": "alRyT",
"maximumDifferentPercent": 0.05
+ },
+ {
+ "node": "P Sized paths",
+ "penNodeId": "dqtl8",
+ "maximumDifferentPercent": 0.05
}
]
}
diff --git a/tests/fixtures/pen-oracles/probes.pen b/tests/fixtures/pen-oracles/probes.pen
index a9473922b..32889e31a 100644
--- a/tests/fixtures/pen-oracles/probes.pen
+++ b/tests/fixtures/pen-oracles/probes.pen
@@ -3558,6 +3558,143 @@
"fill": "#AA0000"
}
]
+ },
+ {
+ "id": "dqtl8",
+ "type": "frame",
+ "x": 0,
+ "y": 5490,
+ "name": "P Sized paths",
+ "width": 420,
+ "height": 200,
+ "fill": "#FFFFFF",
+ "layout": "none",
+ "children": [
+ {
+ "type": "frame",
+ "id": "TnUMH",
+ "x": 16,
+ "y": 16,
+ "name": "Icon mark",
+ "reusable": true,
+ "width": 32,
+ "height": 32,
+ "fill": "#F1F5F9",
+ "layout": "vertical",
+ "children": [
+ {
+ "type": "icon",
+ "id": "wmolH",
+ "name": "Glyph",
+ "width": "fill_container",
+ "height": "fill_container",
+ "icon": "house",
+ "library": "lucide",
+ "fill": "#E11D48"
+ }
+ ]
+ },
+ {
+ "id": "AnkZJ",
+ "type": "ref",
+ "ref": "TnUMH",
+ "name": "Icon same",
+ "x": 64,
+ "y": 16
+ },
+ {
+ "id": "PtK4O",
+ "type": "ref",
+ "ref": "TnUMH",
+ "name": "Icon large",
+ "x": 112,
+ "y": 16,
+ "width": 64,
+ "height": 64
+ },
+ {
+ "type": "frame",
+ "id": "FuncN",
+ "x": 16,
+ "y": 100,
+ "name": "Path mark",
+ "reusable": true,
+ "width": 32,
+ "height": 32,
+ "fill": "#F1F5F9",
+ "layout": "vertical",
+ "children": [
+ {
+ "type": "path",
+ "id": "GlszO",
+ "name": "Shape",
+ "geometry": "M0 10l5-10 5 10z",
+ "viewBox": [
+ 0,
+ 0,
+ 10,
+ 10
+ ],
+ "fill": "#2563EB",
+ "width": "fill_container",
+ "height": "fill_container"
+ }
+ ]
+ },
+ {
+ "id": "L4Vzwh",
+ "type": "ref",
+ "ref": "FuncN",
+ "name": "Path same",
+ "x": 64,
+ "y": 100
+ },
+ {
+ "id": "Lc9IU",
+ "type": "ref",
+ "ref": "FuncN",
+ "name": "Path large",
+ "x": 112,
+ "y": 100,
+ "width": 64,
+ "height": 64
+ },
+ {
+ "type": "frame",
+ "id": "p07zHx",
+ "x": 200,
+ "y": 16,
+ "name": "Row",
+ "width": 200,
+ "height": 48,
+ "fill": "#F1F5F9",
+ "children": [
+ {
+ "type": "rectangle",
+ "id": "OKBgC",
+ "name": "Swatch",
+ "fill": "#16A34A",
+ "width": 40,
+ "height": 20
+ },
+ {
+ "type": "path",
+ "id": "zwP4n",
+ "name": "Line",
+ "geometry": "M0 0h10v10h-10z",
+ "viewBox": [
+ 0,
+ 0,
+ 10,
+ 10
+ ],
+ "fill": "#F59E0B",
+ "width": "fill_container",
+ "height": 48
+ }
+ ]
+ }
+ ]
}
],
"version": "2.21",