AI-native design editor. Open-source Figma alternative.
fix(pen): read text and auto layout as pen.dev lays them out (#1412)
Danila Poyarkov6c3e61e498d3
diff --git a/changes/1412/fixed.md b/changes/1412/fixed.mdnew file mode 100644index 000000000..c30d09785--- /dev/null+++ b/changes/1412/fixed.md@@ -0,0 +1 @@+- `.pen` text keeps its font weight, italic, fixed-size wrapping, and justified or middle alignment, and `.pen` auto layout keeps space-between, space-around, and absolutely positioned layers.diff --git a/packages/core/tests/io/formats/pen/layout.test.ts b/packages/core/tests/io/formats/pen/layout.test.tsindex f6f3d9b1e..05cbd0889 100644--- a/packages/core/tests/io/formats/pen/layout.test.ts+++ b/packages/core/tests/io/formats/pen/layout.test.ts@@ -280,3 +280,21 @@ describe('parsePenFile — turned layers sized by layout', () => {expect(endY).toBeCloseTo(200 - label.width)})})++describe('parsePenFile — space around', () => {+ test('gives each child an equal share of the free space, half on each side', () => {+ const graph = parseLayoutDocument([+ {+ id: 'row',+ type: 'frame',+ layout: 'horizontal',+ justifyContent: 'space_around',+ width: 300,+ height: 50,+ children: ['a', 'b', 'c'].map((id) => ({ id, type: 'rectangle', width: 30, height: 30 }))+ }+ ])+ // 210 of free space: 70 per child, 35 on each side of each.+ expect(['a', 'b', 'c'].map((id) => graph.getNode(id)?.x)).toEqual([35, 135, 235])+ })+})diff --git a/packages/pen/src/convert.ts b/packages/pen/src/layout.tssimilarity index 59%rename from packages/pen/src/convert.tsrename to packages/pen/src/layout.tsindex 01fed9640..55fc05ac8 100644--- a/packages/pen/src/convert.ts+++ b/packages/pen/src/layout.ts@@ -3,16 +3,10 @@ import type {LayoutCounterAlign,LayoutMode,LayoutSizing,- NodeType,- SceneNode,- TextAlignVertical+ SceneGraph,+ SceneNode} from '@open-pencil/scene-graph'-import {- paddingFromShorthand,- parseAutoLayoutDirection,- parseCounterAxisAlign,- parsePrimaryAxisAlign-} from '@open-pencil/scene-graph/layout'+import { paddingFromShorthand, parseAutoLayoutDirection } from '@open-pencil/scene-graph/layout'import type { PenNode, PenNumber } from './schema'import { isVarRef, resolveNumber, type VarContext } from './variables'@@ -103,48 +97,70 @@ export function mapLayoutMode(pen: PenNode): LayoutMode {return pen.type === 'frame' && pen.layout === undefined ? 'HORIZONTAL' : 'NONE'}-export function mapJustifyContent(value: string | undefined): LayoutAlign {- return parsePrimaryAxisAlign(value) ?? 'MIN'+/** pen.dev's main axis alignments; `space_around` lays out as `start` until {@link spreadAround}. */+const JUSTIFY_CONTENT: Partial<Record<string, LayoutAlign>> = {+ start: 'MIN',+ center: 'CENTER',+ end: 'MAX',+ space_between: 'SPACE_BETWEEN'}-export function mapAlignItems(value: string | undefined): LayoutCounterAlign {- return parseCounterAxisAlign(value) ?? 'MIN'+const ALIGN_ITEMS: Partial<Record<string, LayoutCounterAlign>> = {+ start: 'MIN',+ center: 'CENTER',+ end: 'MAX'}-export function mapTextAlign(value: string | undefined): SceneNode['textAlignHorizontal'] {- if (value === 'center') return 'CENTER'- if (value === 'right' || value === 'end') return 'RIGHT'- if (value === 'justified') return 'JUSTIFIED'- return 'LEFT'+export function mapJustifyContent(value: string | undefined): LayoutAlign {+ return JUSTIFY_CONTENT[value ?? 'start'] ?? 'MIN'}-export function mapTextAlignVertical(value: string | undefined): TextAlignVertical {- if (value === 'center') return 'CENTER'- if (value === 'bottom' || value === 'end') return 'BOTTOM'- return 'TOP'+export function mapAlignItems(value: string | undefined): LayoutCounterAlign {+ return ALIGN_ITEMS[value ?? 'start'] ?? 'MIN'}-export function mapFontWeight(value: string | number | undefined): number {- if (typeof value === 'number') return value- if (value === 'thin') return 100- if (value === 'extralight') return 200- if (value === 'light') return 300- if (value === 'medium') return 500- if (value === 'semibold') return 600- if (value === 'bold') return 700- if (value === 'extrabold') return 800- if (value === 'black') return 900- return 400+function flowChildren(graph: SceneGraph, frame: SceneNode): SceneNode[] {+ return graph+ .getChildren(frame.id)+ .filter((child) => child.visible && child.layoutPositioning !== 'ABSOLUTE')}-export function mapNodeType(pen: PenNode): NodeType {- if (pen.type === 'frame') return pen.reusable ? 'COMPONENT' : 'FRAME'- if (pen.type === 'rectangle') return 'RECTANGLE'- if (pen.type === 'ellipse') return 'ELLIPSE'- if (pen.type === 'polygon') return 'POLYGON'- if (pen.type === 'group') return 'GROUP'- if (pen.type === 'text' || pen.type === 'icon_font') return 'TEXT'- if (pen.type === 'path') return 'VECTOR'- if (pen.type === 'ref') return 'INSTANCE'- return 'FRAME'+/**+ * Auto layout has no `space_around`, which gives every child an equal share of the free space,+ * half of it on each side. Once laid out, the share goes into the gap and half of it into the+ * padding at both ends, which draws the same. Returns whether any frame changed.+ */+export function spreadAround(graph: SceneGraph, frameIds: readonly string[]): boolean {+ let changed = false+ for (const id of frameIds) {+ const frame = graph.getNode(id)+ if (!frame || frame.layoutMode === 'NONE' || frame.primaryAxisSizing !== 'FIXED') continue+ const children = flowChildren(graph, frame)+ if (children.length === 0) continue+ const horizontal = frame.layoutMode === 'HORIZONTAL'+ const used = children.reduce(+ (sum, child) => sum + (horizontal ? child.width : child.height),+ frame.itemSpacing * (children.length - 1)+ )+ const free = horizontal+ ? frame.width - frame.paddingLeft - frame.paddingRight - used+ : frame.height - frame.paddingTop - frame.paddingBottom - used+ if (free <= 0) continue+ const share = free / children.length+ if (horizontal) {+ graph.updateNode(frame.id, {+ itemSpacing: frame.itemSpacing + share,+ paddingLeft: frame.paddingLeft + share / 2,+ paddingRight: frame.paddingRight + share / 2+ })+ } else {+ graph.updateNode(frame.id, {+ itemSpacing: frame.itemSpacing + share,+ paddingTop: frame.paddingTop + share / 2,+ paddingBottom: frame.paddingBottom + share / 2+ })+ }+ changed = true+ }+ return changed}diff --git a/packages/pen/src/read.ts b/packages/pen/src/read.tsindex 9e3a958cc..da92b2145 100644--- a/packages/pen/src/read.ts+++ b/packages/pen/src/read.ts@@ -5,33 +5,31 @@ import {type AxisSizingMode,type LayoutMode,type LayoutSizing,+ type NodeType,type SceneNode} from '@open-pencil/scene-graph'import { copyEffects, copyFills, copyStrokes } from '@open-pencil/scene-graph/copy'import { populateInstanceChildren } from '@open-pencil/scene-graph/instances'import { fillSizingFields } from '@open-pencil/scene-graph/layout'+import { convertEffects } from './effects'+import { ellipseArc, pathNetwork } from './geometry'import {applyCornerRadius,applyPadding,mapAlignItems,- mapFontWeight,mapJustifyContent,mapLayoutMode,- mapNodeType,- mapTextAlign,- mapTextAlignVertical,- parseSize-} from './convert'-import { convertEffects } from './effects'-import { ellipseArc, pathNetwork } from './geometry'+ parseSize,+ spreadAround+} from './layout'import { applyStroke, convertPaints, strokeFields } from './paints'import { isPlain, placeLayers, type PenPlacement } from './placement'import { penFileSchema, type PenNode, type PenOverride } from './schema'+import { applyTextProps } from './text'import {bindIfVar,buildVarContext,- isVarRef,resolveBoolean,resolveNumber,type VarContext@@ -56,12 +54,8 @@ interface Build {placements: Map<string, PenPlacement>/** Groups in reading order. */groupIds: string[]-}--function resolveFontFamily(raw: string | undefined, ctx: VarContext): string {- if (!raw) return 'Inter'- if (isVarRef(raw)) return ctx.resolveString(raw)- return raw+ /** Frames spreading their children with `space_around`. */+ aroundIds: string[]}function penPlacement(pen: PenOverride, ctx: VarContext, base?: PenPlacement): PenPlacement {@@ -94,15 +88,13 @@ function applyAutoLayout(pen: PenNode,widthSizing: LayoutSizing,heightSizing: LayoutSizing,- ctx?: VarContext+ ctx: VarContext): void {overrides.layoutMode = layoutModeoverrides.primaryAxisAlign = mapJustifyContent(pen.justifyContent)overrides.counterAxisAlign = mapAlignItems(pen.alignItems)- overrides.itemSpacing =- typeof pen.gap === 'string' && isVarRef(pen.gap) && ctx- ? ctx.resolveNumber(pen.gap)- : ((pen.gap ?? 0) as number)+ overrides.itemSpacing = resolveNumber(pen.gap, ctx)+ overrides.strokesIncludedInLayout = pen.layoutIncludeStroke ?? false// Fill is the child's grow or stretch, set with its parent; the frame itself stays fixed.const own = (sizing: LayoutSizing): AxisSizingMode => (sizing === 'HUG' ? 'HUG' : 'FIXED')@@ -115,29 +107,6 @@ function applyAutoLayout(}}-function applyTextProps(node: SceneNode, pen: PenNode, ctx: VarContext): void {- node.text = pen.type === 'icon_font' ? (pen.iconFontName ?? '') : (pen.content ?? '')- node.fontFamily =- pen.type === 'icon_font'- ? (pen.iconFontFamily ?? 'Material Symbols Sharp')- : resolveFontFamily(pen.fontFamily, ctx)- node.fontSize = resolveNumber(pen.fontSize, ctx, 14)- node.fontWeight = mapFontWeight(- pen.fontWeight ?? (pen.type === 'icon_font' ? pen.weight : undefined)- )- node.textAlignHorizontal = mapTextAlign(pen.textAlign)- node.textAlignVertical = mapTextAlignVertical(pen.textAlignVertical)- if (pen.lineHeight !== undefined) {- const lineHeight = resolveNumber(pen.lineHeight, ctx)- node.lineHeight = lineHeight < 5 ? lineHeight * node.fontSize : lineHeight- }- if (pen.letterSpacing !== undefined) node.letterSpacing = resolveNumber(pen.letterSpacing, ctx)- node.textAutoResize = pen.textGrowth === 'fixed-width' ? 'HEIGHT' : 'WIDTH_AND_HEIGHT'- if (pen.fontFamily && isVarRef(pen.fontFamily)) {- bindIfVar(node, 'fontFamily', pen.fontFamily, ctx)- }-}-function resolveSizing(pen: PenNode, ctx: VarContext) {const isTextLike = pen.type === 'text' || pen.type === 'icon_font'const defaultSize = isTextLike ? 20 : 100@@ -233,17 +202,23 @@ function createSceneNode(pen: PenNode, parentId: string, build: Build): string |if (!hasChildren && h.fitContentFallback !== undefined) overrides.minHeight = h.fitContentFallbackconst parentLayout = graph.getNode(parentId)?.layoutMode ?? 'NONE'+ // An absolute layer leaves its parent's flow; fill sizing then falls back to its value.+ const absolute = pen.layoutPosition === 'absolute' && parentLayout !== 'NONE'+ if (absolute) overrides.layoutPositioning = 'ABSOLUTE'+ const flowLayout = absolute ? 'NONE' : parentLayoutif (layout !== 'NONE') {const widthSizing =- parentLayout === 'NONE' && w.sizing === 'FILL' ? ('FIXED' as LayoutSizing) : w.sizing+ flowLayout === 'NONE' && w.sizing === 'FILL' ? ('FIXED' as LayoutSizing) : w.sizingconst heightSizing =- parentLayout === 'NONE' && h.sizing === 'FILL' ? ('FIXED' as LayoutSizing) : h.sizing+ flowLayout === 'NONE' && h.sizing === 'FILL' ? ('FIXED' as LayoutSizing) : h.sizingapplyAutoLayout(overrides, layout, pen, widthSizing, heightSizing, ctx)}const node = graph.createNode(mapNodeType(pen), parentId, overrides)const placement = penPlacement(pen, ctx)if (pen.type === 'group') build.groupIds.push(node.id)+ if (layout !== 'NONE' && pen.justifyContent === 'space_around') build.aroundIds.push(node.id)+ bindIfVar(node, 'itemSpacing', pen.gap, ctx)if (pen.type === 'group' || !isPlain(placement)) build.placements.set(node.id, placement)node.fills = convertPaints(pen.fill, 'fills', ctx, node)@@ -262,9 +237,9 @@ function createSceneNode(pen: PenNode, parentId: string, build: Build): string |if (network) node.vectorNetwork = network}- if (parentLayout !== 'NONE') {- if (w.sizing === 'FILL') Object.assign(node, fillSizingFields(parentLayout, 'HORIZONTAL'))- if (h.sizing === 'FILL') Object.assign(node, fillSizingFields(parentLayout, 'VERTICAL'))+ if (flowLayout !== 'NONE') {+ if (w.sizing === 'FILL') Object.assign(node, fillSizingFields(flowLayout, 'HORIZONTAL'))+ if (h.sizing === 'FILL') Object.assign(node, fillSizingFields(flowLayout, 'VERTICAL'))}if (pen.reusable) {@@ -443,6 +418,18 @@ function fixInstanceWidths(graph: SceneGraph): void {}}+function mapNodeType(pen: PenNode): NodeType {+ if (pen.type === 'frame') return pen.reusable ? 'COMPONENT' : 'FRAME'+ if (pen.type === 'rectangle') return 'RECTANGLE'+ if (pen.type === 'ellipse') return 'ELLIPSE'+ if (pen.type === 'polygon') return 'POLYGON'+ if (pen.type === 'group') return 'GROUP'+ if (pen.type === 'text' || pen.type === 'icon_font') return 'TEXT'+ if (pen.type === 'path') return 'VECTOR'+ if (pen.type === 'ref') return 'INSTANCE'+ return 'FRAME'+}+/** Whether a group sits in an auto layout's flow, where fitting it changes the layout. */function groupsInFlow(graph: SceneGraph, groupIds: readonly string[]): boolean {return groupIds.some((id) => {@@ -471,7 +458,8 @@ export function parsePenFile(json: string, options: PenReadOptions = {}): SceneGcomponentIds: new Map(),penSources: new Map(),placements: new Map(),- groupIds: []+ groupIds: [],+ aroundIds: []}collectComponentIds(doc.children, build.componentIds)@@ -487,8 +475,9 @@ export function parsePenFile(json: string, options: PenReadOptions = {}): SceneGfixInstanceWidths(graph)options.layout?.(graph)+ const spread = options.layout ? spreadAround(graph, build.aroundIds) : falseplaceLayers(graph, build.placements, build.groupIds)- if (groupsInFlow(graph, build.groupIds)) options.layout?.(graph)+ if (spread || groupsInFlow(graph, build.groupIds)) options.layout?.(graph)if (graph.getPages(true).length === 0) {graph.addPage('Page 1')diff --git a/packages/pen/src/text.ts b/packages/pen/src/text.tsnew file mode 100644index 000000000..1094bc26f--- /dev/null+++ b/packages/pen/src/text.ts@@ -0,0 +1,80 @@+import type { SceneNode, TextAlignVertical, TextAutoResize } from '@open-pencil/scene-graph'++import type { PenNode } from './schema'+import { bindIfVar, isVarRef, resolveNumber, type VarContext } from './variables'++const FONT_WEIGHTS: Partial<Record<string, number>> = {+ thin: 100,+ extralight: 200,+ light: 300,+ normal: 400,+ regular: 400,+ medium: 500,+ semibold: 600,+ bold: 700,+ extrabold: 800,+ black: 900+}++/** pen.dev writes weights as numbers in strings, such as "700"; older files use names. */+function fontWeight(value: PenNode['fontWeight'], ctx: VarContext): number {+ if (value === undefined) return 400+ if (typeof value === 'number') return value+ const named = isVarRef(value) ? ctx.resolveString(value) || ctx.resolveNumber(value) : value+ const numeric = Number(named)+ if (Number.isFinite(numeric) && numeric > 0) return numeric+ return FONT_WEIGHTS[String(named).toLowerCase()] ?? 400+}++const TEXT_ALIGN: Partial<Record<string, SceneNode['textAlignHorizontal']>> = {+ left: 'LEFT',+ center: 'CENTER',+ right: 'RIGHT',+ justify: 'JUSTIFIED'+}++const TEXT_ALIGN_VERTICAL: Partial<Record<string, TextAlignVertical>> = {+ top: 'TOP',+ middle: 'CENTER',+ bottom: 'BOTTOM'+}++/**+ * `auto` grows on one line, `fixed-width` wraps and grows down, and `fixed-width-height` wraps in+ * a fixed box its text may overflow.+ */+const TEXT_GROWTH: Partial<Record<string, TextAutoResize>> = {+ auto: 'WIDTH_AND_HEIGHT',+ 'fixed-width': 'HEIGHT',+ 'fixed-width-height': 'NONE'+}++function resolveString(value: string | undefined, ctx: VarContext): string | undefined {+ return value !== undefined && isVarRef(value) ? ctx.resolveString(value) : value+}++/**+ * A text layer's content and style. Content that reads like a variable reference stays as written,+ * as pen.dev shows it. pen.dev 2.21 draws no underline, strikethrough, or text stroke, so those+ * are left out to match it.+ */+export function applyTextProps(node: SceneNode, pen: PenNode, ctx: VarContext): void {+ const isIconFont = pen.type === 'icon_font'+ node.text = isIconFont ? (pen.iconFontName ?? '') : (pen.content ?? '')+ node.fontFamily = isIconFont+ ? (pen.iconFontFamily ?? 'Material Symbols Sharp')+ : (resolveString(pen.fontFamily, ctx) ?? 'Inter')+ bindIfVar(node, 'fontFamily', pen.fontFamily, ctx)+ node.fontSize = resolveNumber(pen.fontSize, ctx, 14)+ bindIfVar(node, 'fontSize', pen.fontSize, ctx)+ node.fontWeight = fontWeight(pen.fontWeight ?? (isIconFont ? pen.weight : undefined), ctx)+ node.italic = resolveString(pen.fontStyle, ctx)?.toLowerCase() === 'italic'+ node.textAlignHorizontal = TEXT_ALIGN[pen.textAlign ?? 'left'] ?? 'LEFT'+ node.textAlignVertical = TEXT_ALIGN_VERTICAL[pen.textAlignVertical ?? 'top'] ?? 'TOP'+ // pen.dev's line height multiplies the font size.+ if (pen.lineHeight !== undefined)+ node.lineHeight = resolveNumber(pen.lineHeight, ctx) * node.fontSize+ if (pen.letterSpacing !== undefined) node.letterSpacing = resolveNumber(pen.letterSpacing, ctx)+ node.textAutoResize = TEXT_GROWTH[pen.textGrowth ?? 'auto'] ?? 'WIDTH_AND_HEIGHT'+ node.strokes = []+}diff --git a/packages/pen/tests/text.test.ts b/packages/pen/tests/text.test.tsnew file mode 100644index 000000000..a9305addf--- /dev/null+++ b/packages/pen/tests/text.test.ts@@ -0,0 +1,127 @@+import { describe, expect, test } from 'bun:test'++import type { PenDocument, PenNode } from '@open-pencil/pen'++import { getNodeOrThrow } from './helpers/assert'+import { parseDocument } from './helpers/document'++function textOf(fields: Partial<PenNode>, variables?: PenDocument['variables']) {+ const graph = parseDocument(+ [+ {+ id: 'text',+ type: 'text',+ content: 'Label',+ fontFamily: 'Inter',+ fontSize: 16,+ fill: '#111111',+ ...fields+ }+ ],+ { variables }+ )+ return getNodeOrThrow(graph, 'text')+}++describe('parsePenFile — text', () => {+ test.each([+ ['700', 700],+ ['300', 300],+ ['normal', 400],+ ['bold', 700]+ ])('reads font weight %s', (fontWeight, expected) => {+ expect(textOf({ fontWeight }).fontWeight).toBe(expected)+ })++ test('reads italic', () => {+ expect(textOf({ fontStyle: 'italic' }).italic).toBe(true)+ expect(textOf({}).italic).toBe(false)+ })++ test.each([+ ['auto', 'WIDTH_AND_HEIGHT'],+ ['fixed-width', 'HEIGHT'],+ ['fixed-width-height', 'NONE']+ ] as const)('maps text growth %s', (textGrowth, expected) => {+ expect(textOf({ textGrowth, width: 120, height: 40 }).textAutoResize).toBe(expected)+ })++ test('maps justified and middle alignment', () => {+ const node = textOf({ textAlign: 'justify', textAlignVertical: 'middle' })+ expect(node.textAlignHorizontal).toBe('JUSTIFIED')+ expect(node.textAlignVertical).toBe('CENTER')+ })++ test('multiplies the font size by the line height', () => {+ expect(textOf({ fontSize: 28, lineHeight: 2 }).lineHeight).toBe(56)+ expect(textOf({ fontSize: 10, lineHeight: 6 }).lineHeight).toBe(60)+ })++ test('draws no text stroke, as pen.dev does not', () => {+ expect(textOf({ stroke: '#FF0000', strokeWidth: 1 }).strokes).toEqual([])+ })++ test('has no fill unless given one', () => {+ expect(textOf({ fill: undefined }).fills).toEqual([])+ })++ test('keeps content that reads like a variable reference, as pen.dev shows it', () => {+ const node = textOf({ content: '$label' }, { label: { type: 'string', value: 'Resolved' } })+ expect(node.text).toBe('$label')+ })++ test('resolves and binds font size variables', () => {+ const node = textOf({ fontSize: '$size' }, { size: { type: 'number', value: 22 } })+ expect(node.fontSize).toBe(22)+ expect(node.boundVariables.fontSize).toBeDefined()+ })+})++describe('parsePenFile — absolute layers', () => {+ test('takes an absolute layer out of its parent auto layout', () => {+ const graph = parseDocument([+ {+ id: 'row',+ type: 'frame',+ layout: 'horizontal',+ width: 300,+ height: 50,+ children: [+ { id: 'flow', type: 'rectangle', width: 30, height: 30 },+ {+ id: 'pinned',+ type: 'rectangle',+ layoutPosition: 'absolute',+ x: 200,+ y: 10,+ width: 30,+ height: 30+ }+ ]+ }+ ])+ expect(getNodeOrThrow(graph, 'pinned')).toMatchObject({+ layoutPositioning: 'ABSOLUTE',+ x: 200,+ y: 10+ })+ expect(getNodeOrThrow(graph, 'flow').layoutPositioning).toBe('AUTO')+ })++ test('maps space-between with an underscore', () => {+ const graph = parseDocument([+ {+ id: 'row',+ type: 'frame',+ layout: 'horizontal',+ justifyContent: 'space_between',+ alignItems: 'end',+ width: 300+ }+ ])+ expect(getNodeOrThrow(graph, 'row')).toMatchObject({+ primaryAxisAlign: 'SPACE_BETWEEN',+ counterAxisAlign: 'MAX'+ })+ })+})