Skip to content

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

fix(pen): read icons in components as instances of icon components (#1464)

Marcos Velásquez73113e1d10fa
diff --git a/changes/1464/fixed.md b/changes/1464/fixed.md
new file mode 100644
index 000000000..711de9258
--- /dev/null
+++ b/changes/1464/fixed.md
@@ -0,0 +1 @@
+- `.pen` icons inside components open as instances of icon components on an "Icons" page, so instances that change an icon's glyph, colour, or size save as `.fig`.
diff --git a/packages/pen/src/icons.ts b/packages/pen/src/icons.ts
new file mode 100644
index 000000000..991f8ef36
--- /dev/null
+++ b/packages/pen/src/icons.ts
@@ -0,0 +1,178 @@
+import { pick } from 'es-toolkit/object'
+import { isEqual } from 'es-toolkit/predicate'
+
+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 {
+ INSTANCE_SYNC_PROPS,
+ instanceMainComponent,
+ populateInstanceChildren,
+ recordInstanceOverride,
+ swapInstanceComponent
+} from '@open-pencil/scene-graph/instances'
+import type { Color } from '@open-pencil/scene-graph/primitives'
+
+import { iconFontFamily, iconName } from './assets'
+import type { Build } from './nodes'
+import type { PenNode } from './schema'
+import { resolveNumber, resolveString } from './variables'
+
+/** The weight pen.dev draws Material Symbols at when an icon sets none. */
+const MATERIAL_SYMBOLS_WEIGHT = 200
+
+/** Space between the icon components on their page. */
+const ICON_COMPONENT_GAP = 16
+
+/** A font icon's glyph: its name set in the icon font, which turns it into the glyph. */
+function drawFontGlyph(
+ build: Build,
+ frameId: string,
+ family: string,
+ icon: string,
+ weight: number,
+ size: number,
+ color: Color
+): void {
+ build.graph.createNode('TEXT', frameId, {
+ name: icon,
+ text: icon,
+ fontFamily: family,
+ fontWeight: weight,
+ fontVariations: [{ axis: 'wght', value: weight }],
+ fontSize: size,
+ lineHeight: size,
+ width: size,
+ height: size,
+ textAutoResize: 'NONE',
+ fills: [{ type: 'SOLID', color, opacity: 1, visible: true }]
+ })
+}
+
+/**
+ * An icon draws its glyph in its fill colour, scaled to fit its box and centred, as pen.dev does;
+ * an icon the host could not load is an empty frame. Its library and name may be variables.
+ */
+export function drawIcon(node: SceneNode, pen: PenNode, build: Build): void {
+ const { graph, ctx } = build
+ const color = node.fills.find((fill) => fill.type === 'SOLID')?.color ?? { ...BLACK }
+ node.fills = []
+ for (const childId of node.childIds) graph.deleteNode(childId)
+ const library = resolveString(pen.library, ctx)
+ const icon = resolveString(pen.icon, ctx)
+ const size = Math.min(node.width, node.height)
+ if (!library || !icon || size <= 0) return
+ const family = iconFontFamily(library)
+ const name = iconName(library, icon)
+ if (family) {
+ const weight = resolveNumber(pen.weight, ctx, MATERIAL_SYMBOLS_WEIGHT)
+ drawFontGlyph(build, node.id, family, icon, weight, size, color)
+ } else if (!name || !build.icons?.draw(graph, node.id, name, size, color)) return
+ const dx = (node.width - size) / 2
+ const dy = (node.height - size) / 2
+ for (const glyph of graph.getChildren(node.id)) {
+ graph.updateNode(glyph.id, { x: glyph.x + dx, y: glyph.y + dy })
+ }
+}
+
+/**
+ * Whether a layer built under `parentId` is part of a component. An instance cannot redraw the
+ * paths of a layer it copies, so an icon there is an instance of an icon component, which an
+ * instance of the enclosing component can swap, as Figma's icon sets work.
+ */
+export function insideComponent(graph: SceneGraph, parentId: string): boolean {
+ for (let node = graph.getNode(parentId); node;) {
+ if (node.type === 'COMPONENT' || node.type === 'COMPONENT_SET') return true
+ node = node.parentId ? graph.getNode(node.parentId) : undefined
+ }
+ return false
+}
+
+/**
+ * The component that draws an icon at a size, made on first use on an "Icons" page. Each size is
+ * its own component, so the glyph is drawn at that size, as pen.dev draws it, rather than scaled.
+ */
+function iconComponent(build: Build, pen: PenNode, width: number, height: number): string {
+ const { graph, ctx } = build
+ const library = resolveString(pen.library, ctx) ?? ''
+ const icon = resolveString(pen.icon, ctx) ?? ''
+ const weight = iconFontFamily(library)
+ ? `/${resolveNumber(pen.weight, ctx, MATERIAL_SYMBOLS_WEIGHT)}`
+ : ''
+ const key = `${library}/${icon}/${width}x${height}${weight}`
+ const existing = build.iconComponents.get(key)
+ if (existing) return existing
+ build.iconPageId ??= graph.addPage('Icons').id
+ const placed = [...build.iconComponents.values()].map((id) => graph.getNode(id))
+ const x = placed.reduce((end, node) => Math.max(end, (node?.x ?? 0) + (node?.width ?? 0)), 0)
+ const component = graph.createNode('COMPONENT', build.iconPageId, {
+ name: key,
+ x: placed.length > 0 ? x + ICON_COMPONENT_GAP : 0,
+ width,
+ height,
+ fills: [{ type: 'SOLID', color: { ...BLACK }, opacity: 1, visible: true }]
+ })
+ drawIcon(component, pen, build)
+ build.iconComponents.set(key, component.id)
+ return component.id
+}
+
+/** Paints an icon's glyph `color` where it takes the icon's colour, as overrides of the instance. */
+function recolorGlyph(graph: SceneGraph, instanceId: string, color: Color): void {
+ for (const glyph of graph.getChildren(instanceId)) {
+ const tint = readIconTint(glyph)
+ // A font icon's glyph is text in the icon's colour.
+ const fills =
+ glyph.type === 'TEXT' || tint.includes('fill')
+ ? glyph.fills.map((fill) => ({ ...fill, color }))
+ : glyph.fills
+ const strokes = tint.includes('stroke')
+ ? glyph.strokes.map((stroke) => ({ ...stroke, color }))
+ : glyph.strokes
+ const changed = [
+ ...(isEqual(fills, glyph.fills) ? [] : ['fills']),
+ ...(isEqual(strokes, glyph.strokes) ? [] : ['strokes'])
+ ]
+ if (changed.length === 0) continue
+ graph.updateNode(glyph.id, { fills, strokes })
+ recordInstanceOverride(graph, glyph.id, changed)
+ }
+}
+
+/**
+ * Keeps what the icon instance sets on itself, such as its opacity or effects, as overrides of it:
+ * the icon component is shared by every use of the glyph at that size, so linking to it would
+ * otherwise give the instance the component's values.
+ */
+function keepOwnFields(
+ graph: SceneGraph,
+ instanceId: string,
+ own: Partial<SceneNode>,
+ componentId: string
+): void {
+ const component = graph.getNode(componentId)
+ const differing = INSTANCE_SYNC_PROPS.filter((field) => !isEqual(own[field], component?.[field]))
+ if (differing.length === 0) return
+ graph.updateNode(instanceId, pick(own, differing))
+ recordInstanceOverride(graph, instanceId, differing)
+}
+
+/**
+ * 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.
+ */
+export function useIconComponent(node: SceneNode, pen: PenNode, build: Build): void {
+ const { graph } = build
+ const color = node.fills.find((fill) => fill.type === 'SOLID')?.color ?? { ...BLACK }
+ node.fills = []
+ const own = structuredClone(pick(node, INSTANCE_SYNC_PROPS))
+ const componentId = iconComponent(build, pen, node.width, node.height)
+ if (!node.componentId) {
+ graph.updateNode(node.id, { componentId })
+ populateInstanceChildren(graph, node.id, componentId)
+ } else if (instanceMainComponent(graph, node)?.id !== componentId) {
+ swapInstanceComponent(graph, node.id, componentId, { keepName: true })
+ }
+ keepOwnFields(graph, node.id, own, componentId)
+ recolorGlyph(graph, node.id, color)
+}
diff --git a/packages/pen/src/nodes.ts b/packages/pen/src/nodes.ts
index bf6333576..4a400c3bc 100644
--- a/packages/pen/src/nodes.ts
+++ b/packages/pen/src/nodes.ts
@@ -6,13 +6,12 @@ import type {
SceneGraph,
SceneNode
} from '@open-pencil/scene-graph'
-import { BLACK } from '@open-pencil/scene-graph/constants'
import { fillSizingFields } from '@open-pencil/scene-graph/layout'
import type { Color } from '@open-pencil/scene-graph/primitives'
-import { iconFontFamily, iconName } from './assets'
import { convertEffects } from './effects'
import { ellipseArc, pathNetwork } from './geometry'
+import { drawIcon, insideComponent, useIconComponent } from './icons'
import type { PenImages } from './images'
import {
applyCornerRadius,
@@ -26,13 +25,7 @@ import { applyStroke, convertPaints, strokeFields } from './paints'
import { isPlain, type PenPlacement } from './placement'
import type { PenNode, PenOverride } from './schema'
import { applyTextProps } from './text'
-import {
- bindIfVar,
- resolveBoolean,
- resolveNumber,
- resolveString,
- type VarContext
-} from './variables'
+import { bindIfVar, resolveBoolean, resolveNumber, type VarContext } from './variables'
/** Where icon glyphs come from, as the host loaded them. */
export interface PenIconSource {
@@ -61,6 +54,10 @@ export interface Build {
groupIds: Set<string>
/** Frames spreading their children with `space_around`. */
aroundIds: Set<string>
+ /** The components icons in components are instances of, by glyph and size. */
+ iconComponents: Map<string, string>
+ /** The page those components are on, added with the first one. */
+ iconPageId: string | null
}
function penPlacement(pen: PenOverride, ctx: VarContext): PenPlacement {
@@ -187,7 +184,8 @@ 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') drawIcon(node, pen, build)
+ if (pen.type === 'icon' && node.type === 'INSTANCE') useIconComponent(node, pen, build)
+ else if (pen.type === 'icon') drawIcon(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') {
@@ -202,60 +200,6 @@ export function applyPenProperties(node: SceneNode, pen: PenNode, build: Build):
build.effective.set(node.id, pen)
}
-/** The weight pen.dev draws Material Symbols at when an icon sets none. */
-const MATERIAL_SYMBOLS_WEIGHT = 200
-
-/** A font icon's glyph: its name set in the icon font, which turns it into the glyph. */
-function drawFontGlyph(
- build: Build,
- frameId: string,
- family: string,
- icon: string,
- weight: number,
- size: number,
- color: Color
-): void {
- build.graph.createNode('TEXT', frameId, {
- name: icon,
- text: icon,
- fontFamily: family,
- fontWeight: weight,
- fontVariations: [{ axis: 'wght', value: weight }],
- fontSize: size,
- lineHeight: size,
- width: size,
- height: size,
- textAutoResize: 'NONE',
- fills: [{ type: 'SOLID', color, opacity: 1, visible: true }]
- })
-}
-
-/**
- * An icon draws its glyph in its fill colour, scaled to fit its box and centred, as pen.dev does;
- * an icon the host could not load is an empty frame. Its library and name may be variables.
- */
-function drawIcon(node: SceneNode, pen: PenNode, build: Build): void {
- const { graph, ctx } = build
- const color = node.fills.find((fill) => fill.type === 'SOLID')?.color ?? { ...BLACK }
- node.fills = []
- for (const childId of node.childIds) graph.deleteNode(childId)
- const library = resolveString(pen.library, ctx)
- const icon = resolveString(pen.icon, ctx)
- const size = Math.min(node.width, node.height)
- if (!library || !icon || size <= 0) return
- const family = iconFontFamily(library)
- const name = iconName(library, icon)
- if (family) {
- const weight = resolveNumber(pen.weight, ctx, MATERIAL_SYMBOLS_WEIGHT)
- drawFontGlyph(build, node.id, family, icon, weight, size, color)
- } else if (!name || !build.icons?.draw(graph, node.id, name, size, color)) return
- const dx = (node.width - size) / 2
- const dy = (node.height - size) / 2
- for (const glyph of graph.getChildren(node.id)) {
- graph.updateNode(glyph.id, { x: glyph.x + dx, y: glyph.y + dy })
- }
-}
-
/**
* The fields an instance draws with: its component's, with the `ref` node's own replacing them one
* by one, as pen.dev reads them. A theme on both merges axis by axis.
@@ -281,11 +225,11 @@ export function createSceneNode(pen: PenNode, parentId: string, build: Build): s
// A component that is not a frame has no instances; its uses are plain copies.
const instanceOf = pen.type === 'ref' && component?.type === 'frame' ? component : undefined
const fields = pen.type === 'ref' ? instanceFields(pen, component) : pen
+ const iconInstance = fields.type === 'icon' && insideComponent(build.graph, parentId)
const leaveTheme = fields.theme ? build.ctx.enterTheme(fields.theme) : undefined
try {
- const node = build.graph.createNode(instanceOf ? 'INSTANCE' : sceneType(fields), parentId, {
- id: pen.id
- })
+ const type = instanceOf || iconInstance ? 'INSTANCE' : sceneType(fields)
+ const node = build.graph.createNode(type, parentId, { id: pen.id })
applyPenProperties(node, fields, build)
if (instanceOf) {
node.componentId = instanceOf.id
diff --git a/packages/pen/src/read.ts b/packages/pen/src/read.ts
index 45f98edc1..17af64f97 100644
--- a/packages/pen/src/read.ts
+++ b/packages/pen/src/read.ts
@@ -67,7 +67,9 @@ export function buildPenGraph(doc: PenDocument, options: PenReadOptions = {}): S
instances: new Map(),
placements: new Map(),
groupIds: new Set(),
- aroundIds: new Set()
+ aroundIds: new Set(),
+ iconComponents: new Map(),
+ iconPageId: null
}
collectComponents(doc.children, build.components)
diff --git a/packages/pen/tests/icons.test.ts b/packages/pen/tests/icons.test.ts
new file mode 100644
index 000000000..eb07d9cc8
--- /dev/null
+++ b/packages/pen/tests/icons.test.ts
@@ -0,0 +1,170 @@
+import { describe, expect, test } from 'bun:test'
+
+import type { PenNode } from '@open-pencil/pen'
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import { withIconTint } from '@open-pencil/scene-graph/icons'
+import {
+ hasInstanceOverride,
+ instanceMainComponent,
+ syncInstance
+} from '@open-pencil/scene-graph/instances'
+import type { Color } from '@open-pencil/scene-graph/primitives'
+
+import { expectDefined, getNodeOrThrow } from './helpers/assert'
+import { parseDocument } from './helpers/document'
+
+/** Draws each glyph as one path tinted with the icon's colour, as the Iconify source does. */
+const icons = {
+ draw(graph: SceneGraph, frameId: string, name: string, size: number, color: Color) {
+ const path = graph.createNode('VECTOR', frameId, {
+ name,
+ width: size,
+ height: size,
+ fills: [{ type: 'SOLID', color, opacity: 1, visible: true }]
+ })
+ graph.updateNode(path.id, { pluginData: withIconTint(path, ['fill']) })
+ return true
+ }
+}
+
+const item: PenNode = {
+ id: 'item',
+ type: 'frame',
+ reusable: true,
+ layout: 'horizontal',
+ children: [
+ {
+ id: 'glyph',
+ type: 'icon',
+ library: 'lucide',
+ icon: 'zap',
+ width: 16,
+ height: 16,
+ fill: '#333333'
+ },
+ { id: 'label', type: 'text', content: 'Item', fill: '#333333' }
+ ]
+}
+
+function read(...uses: PenNode[]) {
+ return parseDocument([item, ...uses], {}, { icons })
+}
+
+function glyphOf(graph: SceneGraph, instanceId: string): SceneNode {
+ return expectDefined(
+ graph.getChildren(instanceId).find((node) => node.type === 'INSTANCE'),
+ `the icon in ${instanceId}`
+ )
+}
+
+describe('parsePenFile — icons in components', () => {
+ test('reads an icon in a component as an instance of an icon component', () => {
+ const graph = read()
+ const glyph = getNodeOrThrow(graph, 'glyph')
+ expect(glyph.type).toBe('INSTANCE')
+ const component = expectDefined(instanceMainComponent(graph, glyph), 'icon component')
+ expect(component.name).toBe('lucide/zap/16x16')
+ expect(graph.getNode(component.parentId ?? '')?.name).toBe('Icons')
+ expect(graph.getChildren(glyph.id).map((path) => path.componentId)).toEqual(
+ graph.getChildren(component.id).map((path) => path.id)
+ )
+ expect(graph.getChildren(glyph.id)[0]?.fills[0]?.color).toMatchObject({ r: 0.2, g: 0.2 })
+ })
+
+ test('swaps the icon component an instance changes the icon to', () => {
+ const graph = read({
+ id: 'swapped',
+ type: 'ref',
+ ref: 'item',
+ descendants: { glyph: { icon: 'star' } }
+ })
+ const glyph = glyphOf(graph, 'swapped')
+ expect(instanceMainComponent(graph, glyph)?.name).toBe('lucide/star/16x16')
+ // Every layer the instance holds is a copy of a component's layer, as a .fig file needs.
+ const queue = [...graph.getChildren('swapped')]
+ for (const node of queue) {
+ expect(node.componentId).not.toBeNull()
+ queue.push(...graph.getChildren(node.id))
+ }
+ })
+
+ test('recolors the glyph an instance gives another colour, as an override', () => {
+ const graph = read({
+ id: 'recolored',
+ type: 'ref',
+ ref: 'item',
+ descendants: { glyph: { fill: '#00CC00' } }
+ })
+ const path = expectDefined(graph.getChildren(glyphOf(graph, 'recolored').id)[0], 'path')
+ expect(path.fills[0]?.color).toMatchObject({ r: 0, g: 0.8, b: 0 })
+ expect(hasInstanceOverride(graph, path.id, 'fills')).toBe(true)
+ const component = expectDefined(
+ instanceMainComponent(graph, getNodeOrThrow(graph, 'glyph')),
+ 'icon component'
+ )
+ expect(graph.getChildren(component.id)[0]?.fills[0]?.color).toMatchObject({ r: 0, g: 0, b: 0 })
+ })
+
+ test('gives each size of a glyph its own component and keeps icons outside components', () => {
+ const graph = read(
+ {
+ id: 'larger',
+ type: 'ref',
+ ref: 'item',
+ descendants: { glyph: { width: 24, height: 24 } }
+ },
+ { id: 'loose', type: 'icon', library: 'lucide', icon: 'zap', width: 16, height: 16 }
+ )
+ expect(instanceMainComponent(graph, glyphOf(graph, 'larger'))?.name).toBe('lucide/zap/24x24')
+ expect(getNodeOrThrow(graph, 'loose').type).toBe('FRAME')
+ })
+
+ test('keeps what an icon sets on itself when an instance swaps its component', () => {
+ const faded: PenNode = {
+ id: 'faded-item',
+ type: 'frame',
+ reusable: true,
+ children: [
+ {
+ id: 'faded-glyph',
+ type: 'icon',
+ library: 'lucide',
+ icon: 'zap',
+ width: 16,
+ height: 16,
+ opacity: 0.5
+ }
+ ]
+ }
+ const graph = parseDocument(
+ [
+ faded,
+ {
+ id: 'swapped',
+ type: 'ref',
+ ref: 'faded-item',
+ descendants: { 'faded-glyph': { icon: 'star' } }
+ },
+ {
+ id: 'fainter',
+ type: 'ref',
+ ref: 'faded-item',
+ descendants: { 'faded-glyph': { icon: 'star', opacity: 0.25 } }
+ }
+ ],
+ {},
+ { icons }
+ )
+ expect(getNodeOrThrow(graph, 'faded-glyph').opacity).toBe(0.5)
+ for (const [id, opacity] of [
+ ['swapped', 0.5],
+ ['fainter', 0.25]
+ ] as const) {
+ const glyph = glyphOf(graph, id)
+ expect(instanceMainComponent(graph, glyph)?.name).toBe('lucide/star/16x16')
+ expect(glyph.opacity).toBe(opacity)
+ syncInstance(graph, glyph.id)
+ expect(glyphOf(graph, id).opacity).toBe(opacity)
+ }
+ })
+})