AI-native design editor. Open-source Figma alternative.
fix(pen)!: read paints, strokes, and effects of current .pen files (#1410)
Danila Poyarkov67aef3e1a842
diff --git a/bun.lock b/bun.lockindex 9995e070e..4ac4c1d5d 100644--- a/bun.lock+++ b/bun.lock@@ -515,6 +515,9 @@"packages/pen": {"name": "@open-pencil/pen","version": "0.16.0",+ "dependencies": {+ "valibot": "^1.5.0",+ },"devDependencies": {"@types/bun": "^1.3.14","tsdown": "^0.22.14",diff --git a/changes/1410/breaking.md b/changes/1410/breaking.mdnew file mode 100644index 000000000..5ff9ac4f2--- /dev/null+++ b/changes/1410/breaking.md@@ -0,0 +1 @@+- `@open-pencil/pen` exports only `parsePenFile`, `readPenFile`, and the `PenDocument`, `PenNode`, and `PenOverride` types; its conversion helpers, such as `parseSize`, `applyPadding`, `convertFill`, `convertStroke`, `isVarRef`, and `buildVarContext`, are no longer public.diff --git a/changes/1410/fixed.md b/changes/1410/fixed.mdnew file mode 100644index 000000000..6b60cd68e--- /dev/null+++ b/changes/1410/fixed.md@@ -0,0 +1 @@+- Strokes, gradients, blend modes, blurs, and disabled effects of current `.pen` files draw as in pen.dev, and a `.pen` file whose strokes are lists of paints opens instead of failing (#1324).diff --git a/package.json b/package.jsonindex 458cfcfe8..00cc49ce8 100644--- a/package.json+++ b/package.json@@ -64,8 +64,8 @@"benchmark:navigation": "bun tools/dev/navigation-benchmark/src/cli.ts run","test:native": "bun run build:native-test && wdio run wdio.conf.ts","lint": "bun run lint:structure && oxlint -c oxlint.json --type-aware --type-check src/ packages/scene-graph/src/ packages/core/src/ packages/vue/src/ packages/cli/src/ packages/mcp/src/ packages/harness/src/ packages/feedback/src/ packages/cloud/src/ packages/dom-css/src/ packages/pen/src/ packages/design-jsx/src/ packages/emit/src/ packages/kiwi/src/ packages/fig/src/ packages/docs/.vitepress/theme/landing/",- "lint:structure": "oxlint -c oxlint.json commitlint.config.ts vite.config.ts vite/ .storybook/ src/ packages/scene-graph/src/ packages/scene-graph/scripts/ packages/core/src/ packages/vue/src/ packages/cli/src/ packages/mcp/src/ packages/mcp/tests/ packages/harness/src/ packages/harness/tests/ packages/feedback/src/ packages/feedback/tests/ packages/cloud/src/ packages/cloud/tests/ packages/cloud/deploy/ packages/dom-css/src/ packages/dom-css/tests/ packages/dom-css/scripts/ packages/pen/src/ packages/pen/scripts/ packages/design-jsx/src/ packages/design-jsx/tests/ packages/design-jsx/scripts/ packages/emit/src/ packages/emit/tests/ packages/emit/scripts/ packages/kiwi/src/ packages/kiwi/tests/ packages/kiwi/scripts/ packages/fig/src/ packages/fig/tests/ packages/fig/scripts/ packages/core/tests/ packages/cli/tests/ packages/scene-graph/tests/ packages/vue/tests/ tests/ scripts/ tools/ packages/docs/.vitepress/theme/landing/",- "format": "oxfmt --write .oxfmtrc.json commitlint.config.ts vite.config.ts vite/ .storybook/ src/ packages/scene-graph/src/ packages/scene-graph/scripts/ packages/core/src/ packages/cli/src/ packages/mcp/src/ packages/mcp/tests/ packages/harness/src/ packages/harness/tests/ packages/feedback/src/ packages/feedback/tests/ packages/cloud/src/ packages/cloud/tests/ packages/cloud/deploy/ packages/cloud/tsdown.config.ts packages/cloud/tsdown.standalone.config.ts packages/vue/src/ packages/dom-css/src/ packages/dom-css/tests/ packages/dom-css/scripts/ packages/pen/src/ packages/pen/scripts/ packages/design-jsx/src/ packages/design-jsx/tests/ packages/design-jsx/scripts/ packages/emit/src/ packages/emit/tests/ packages/emit/scripts/ packages/kiwi/src/ packages/kiwi/tests/ packages/kiwi/scripts/ packages/fig/src/ packages/fig/tests/ packages/fig/scripts/ tests scripts/ tools/ packages/docs/.vitepress/theme/landing/",+ "lint:structure": "oxlint -c oxlint.json commitlint.config.ts vite.config.ts vite/ .storybook/ src/ packages/scene-graph/src/ packages/scene-graph/scripts/ packages/core/src/ packages/vue/src/ packages/cli/src/ packages/mcp/src/ packages/mcp/tests/ packages/harness/src/ packages/harness/tests/ packages/feedback/src/ packages/feedback/tests/ packages/cloud/src/ packages/cloud/tests/ packages/cloud/deploy/ packages/dom-css/src/ packages/dom-css/tests/ packages/dom-css/scripts/ packages/pen/src/ packages/pen/tests/ packages/pen/scripts/ packages/design-jsx/src/ packages/design-jsx/tests/ packages/design-jsx/scripts/ packages/emit/src/ packages/emit/tests/ packages/emit/scripts/ packages/kiwi/src/ packages/kiwi/tests/ packages/kiwi/scripts/ packages/fig/src/ packages/fig/tests/ packages/fig/scripts/ packages/core/tests/ packages/cli/tests/ packages/scene-graph/tests/ packages/vue/tests/ tests/ scripts/ tools/ packages/docs/.vitepress/theme/landing/",+ "format": "oxfmt --write .oxfmtrc.json commitlint.config.ts vite.config.ts vite/ .storybook/ src/ packages/scene-graph/src/ packages/scene-graph/scripts/ packages/core/src/ packages/cli/src/ packages/mcp/src/ packages/mcp/tests/ packages/harness/src/ packages/harness/tests/ packages/feedback/src/ packages/feedback/tests/ packages/cloud/src/ packages/cloud/tests/ packages/cloud/deploy/ packages/cloud/tsdown.config.ts packages/cloud/tsdown.standalone.config.ts packages/vue/src/ packages/dom-css/src/ packages/dom-css/tests/ packages/dom-css/scripts/ packages/pen/src/ packages/pen/tests/ packages/pen/scripts/ packages/design-jsx/src/ packages/design-jsx/tests/ packages/design-jsx/scripts/ packages/emit/src/ packages/emit/tests/ packages/emit/scripts/ packages/kiwi/src/ packages/kiwi/tests/ packages/kiwi/scripts/ packages/fig/src/ packages/fig/tests/ packages/fig/scripts/ tests scripts/ tools/ packages/docs/.vitepress/theme/landing/","format:check": "bun run format && status=$(git status --porcelain -uall) && test -z \"$status\" || (echo \"$status\" && exit 1)","check": "bun run check:icons && bun run build:packages && bun run lint && tsgo --noEmit && bun run check:vue && bun run check:native-test && bun run check:i18n && bun run check:docs && bun run check:changelog && bun run check:packages && bun run check:deps && bun run check:audit && bun run check:secrets && bun run check:monorepo && bun run check:arch && bun run check:test-homes && bun run check:cloud-off && bun run check:test-types && bun run test:type-shapes && bun run check:tools && bun run test:tools && bun run test:dupes","check:commits": "commitlint",diff --git a/tests/engine/pen/layout.test.ts b/packages/core/tests/io/formats/pen/layout.test.tssimilarity index 86%rename from tests/engine/pen/layout.test.tsrename to packages/core/tests/io/formats/pen/layout.test.tsindex 9e332e175..be6d1bafe 100644--- a/tests/engine/pen/layout.test.ts+++ b/packages/core/tests/io/formats/pen/layout.test.ts@@ -1,7 +1,7 @@import { describe, expect, test } from 'bun:test'import { layoutAuthoredNodes } from '@open-pencil/core/layout'-import { parsePenFile, parseSize, type PenDocument, type PenNode } from '@open-pencil/pen'+import { parsePenFile, type PenDocument, type PenNode } from '@open-pencil/pen'function parseLayoutDocument(children: PenNode[]) {const document: PenDocument = { version: '2.17', children }@@ -135,23 +135,35 @@ describe('parsePenFile — Pen layout defaults (#564)', () => {})})-describe('parseSize — Pen sizing fallbacks (#564)', () => {- test('preserves parameterized fill-container fallback values', () => {- expect(parseSize('fill_container(900)', 100)).toEqual({ value: 900, sizing: 'FILL' })- })-- test('preserves parameterized fit-content fallback metadata', () => {- expect(parseSize('fit_content(900)', 100)).toEqual({- value: 900,- sizing: 'HUG',- fitContentFallback: 900- })+describe('parsePenFile — Pen sizing fallbacks (#564)', () => {+ test('sizes fill-container outside a layout by its fallback', () => {+ const graph = parseLayoutDocument([+ {+ id: 'free',+ type: 'frame',+ layout: 'none',+ width: 1000,+ height: 400,+ children: [{ id: 'filler', type: 'rectangle', width: 'fill_container(900)', height: 40 }]+ }+ ])+ expect(graph.getNode('filler')?.width).toBe(900)})test.each(['fit_content()', 'fit_content(nope)', 'fit_content(100)garbage'])(- 'rejects malformed sizing behavior %s',- (value) => {- expect(parseSize(value, 100)).toEqual({ value: 100, sizing: 'FIXED' })+ 'falls back to the default size for malformed sizing %s',+ (width) => {+ const graph = parseLayoutDocument([+ {+ id: 'free',+ type: 'frame',+ layout: 'none',+ width: 1000,+ height: 400,+ children: [{ id: 'shape', type: 'rectangle', width, height: 40 }]+ }+ ])+ expect(graph.getNode('shape')?.width).toBe(100)})})diff --git a/packages/pen/package.json b/packages/pen/package.jsonindex 265f39de8..55a00ac4b 100644--- a/packages/pen/package.json+++ b/packages/pen/package.json@@ -38,6 +38,9 @@"peerDependencies": {"@open-pencil/scene-graph": "workspace:*"},+ "dependencies": {+ "valibot": "^1.5.0"+ },"devDependencies": {"@types/bun": "^1.3.14","tsdown": "^0.22.14",diff --git a/packages/pen/src/convert.ts b/packages/pen/src/convert.tsindex 7d04af1c5..8e9ee421e 100644--- a/packages/pen/src/convert.ts+++ b/packages/pen/src/convert.ts@@ -1,377 +1,21 @@-import {- generateId,- type Effect,- type Fill,- type LayoutAlign,- type LayoutCounterAlign,- type LayoutMode,- type LayoutSizing,- type NodeType,- type SceneGraph,- type SceneNode,- type Stroke,- type StrokeCap,- type StrokeJoin,- type TextAlignVertical,- type Variable,- type VariableCollection,- type VariableCollectionMode,- type VariableType,- type VariableValue+import type {+ LayoutAlign,+ LayoutCounterAlign,+ LayoutMode,+ LayoutSizing,+ NodeType,+ SceneNode,+ TextAlignVertical} from '@open-pencil/scene-graph'-import { parseColor } from '@open-pencil/scene-graph/color'-import { BLACK } from '@open-pencil/scene-graph/constants'import {paddingFromShorthand,parseAutoLayoutDirection,parseCounterAxisAlign,parsePrimaryAxisAlign} from '@open-pencil/scene-graph/layout'-import type { Color, Vector } from '@open-pencil/scene-graph/primitives'--export interface PenDocument {- version: string- children: PenNode[]- themes?: Record<string, string[]>- variables?: Record<string, PenVariable>-}--export interface PenVariable {- type: 'color' | 'string' | 'number'- value: PenVariableValue[] | PenVariableValue | string | number-}--interface PenVariableValue {- value: string | number- theme?: Record<string, string>-}--interface PenStroke {- align: 'inside' | 'center' | 'outside'- thickness: number | { top?: number; right?: number; bottom?: number; left?: number }- fill?: string- join?: string- cap?: string-}--interface PenEffect {- type: string- shadowType?: string- color?: string- offset?: Vector- blur?: number- spread?: number-}--interface PenFillObject {- type: string- color: string- enabled?: boolean-}--type PenFill = string | PenFillObject | PenFillObject[]-type PenSpacingValue = number | string-type PenPadding =- | PenSpacingValue- | [PenSpacingValue, PenSpacingValue]- | [PenSpacingValue, PenSpacingValue, PenSpacingValue, PenSpacingValue]--export interface PenNode {- type: string- id: string- name?: string- x?: number- y?: number- width?: number | string- height?: number | string- fill?: PenFill- opacity?: number- enabled?: boolean- clip?: boolean- rotation?: number- flipX?: boolean- flipY?: boolean- reusable?: boolean- cornerRadius?: number | string | (number | string)[]- stroke?: PenStroke- effect?: PenEffect | PenEffect[]- layout?: string- gap?: number | string- padding?: PenPadding- justifyContent?: string- alignItems?: string- children?: PenNode[]- content?: string- fontFamily?: string- fontSize?: number- fontWeight?: string | number- lineHeight?: number- letterSpacing?: number- textAlign?: string- textAlignVertical?: string- textGrowth?: string- ref?: string- descendants?: Record<string, Partial<PenNode>>- slot?: string[]- geometry?: string- iconFontName?: string- iconFontFamily?: string- weight?: number- model?: string- theme?: Record<string, string>-}--export interface VarContext {- byName: Map<string, { id: string; variable: Variable }>- activeModeId: string- collectionId: string- modeByThemeName: Map<string, string>- resolveColor(ref: string): Color- resolveNumber(ref: string): number- resolveString(ref: string): string- setActiveTheme(themeName: string): void-}--function penVarTypeToSceneType(t: string): VariableType {- if (t === 'color') return 'COLOR'- if (t === 'number') return 'FLOAT'- return 'STRING'-}--function penValueToSceneValue(raw: string | number, type: VariableType): VariableValue {- if (type === 'COLOR' && typeof raw === 'string') return parseColor(raw)- if (type === 'FLOAT' && typeof raw === 'number') return raw- if (type === 'STRING') return String(raw)- if (typeof raw === 'number') return raw- return String(raw)-}--function defaultForType(type: VariableType): VariableValue {- if (type === 'COLOR') return { ...BLACK }- if (type === 'FLOAT') return 0- if (type === 'BOOLEAN') return false- return ''-}--export function isVarRef(val: unknown): val is string {- return typeof val === 'string' && val.startsWith('$') && val.length > 1-}--function varName(ref: string): string {- return ref.replace(/^\$/, '')-}--export function bindIfVar(node: SceneNode, field: string, val: unknown, ctx: VarContext): void {- if (!isVarRef(val)) return- const entry = ctx.byName.get(varName(val))- if (entry) node.boundVariables[field] = entry.id-}--export function buildVarContext(- graph: SceneGraph,- penVars: Record<string, PenVariable>,- themes: Record<string, string[]>-): VarContext {- const collectionId = generateId()- const modes: VariableCollectionMode[] = []- const themeKeys = Object.keys(themes)-- if (themeKeys.length > 0) {- const themeKey = themeKeys[0]- for (const modeName of themes[themeKey]) {- modes.push({ modeId: generateId(), name: modeName })- }- }- if (modes.length === 0) {- modes.push({ modeId: generateId(), name: 'Default' })- }-- const collection: VariableCollection = {- id: collectionId,- name: 'Variables',- modes,- defaultModeId: modes[0].modeId,- variableIds: []- }- graph.addCollection(collection)-- const modeByThemeValue = new Map<string, string>()- if (themeKeys.length > 0) {- const themeKey = themeKeys[0]- for (const mode of modes) {- modeByThemeValue.set(`${themeKey}:${mode.name}`, mode.modeId)- }- }-- const byName = new Map<string, { id: string; variable: Variable }>()-- for (const [name, def] of Object.entries(penVars)) {- const varId = generateId()- const varType = penVarTypeToSceneType(def.type)- const valuesByMode: Record<string, VariableValue> = {}-- if (Array.isArray(def.value)) {- for (const entry of def.value) {- if (entry.theme) {- const [tKey, tVal] = Object.entries(entry.theme)[0]- const modeId = modeByThemeValue.get(`${tKey}:${tVal}`)- if (modeId) valuesByMode[modeId] = penValueToSceneValue(entry.value, varType)- } else {- valuesByMode[modes[0].modeId] = penValueToSceneValue(entry.value, varType)- }- }- } else {- valuesByMode[modes[0].modeId] = penValueToSceneValue(def.value as string | number, varType)- }-- for (const mode of modes) {- if (!(mode.modeId in valuesByMode)) {- valuesByMode[mode.modeId] = valuesByMode[modes[0].modeId] ?? defaultForType(varType)- }- }-- const variable: Variable = {- id: varId,- name,- type: varType,- collectionId,- valuesByMode,- description: '',- hiddenFromPublishing: false- }- graph.addVariable(variable)- byName.set(name, { id: varId, variable })- }-- let activeModeId = modes[0].modeId-- function resolveVal(ref: string): VariableValue | undefined {- const entry = byName.get(ref.replace(/^\$/, ''))- if (!entry) return undefined- return (- entry.variable.valuesByMode[activeModeId] ?? Object.values(entry.variable.valuesByMode)[0]- )- }-- return {- byName,- activeModeId,- collectionId,- modeByThemeName: modeByThemeValue,- resolveColor(ref: string): Color {- const val = resolveVal(ref)- if (val === undefined) return parseColor(ref)- if (typeof val === 'object' && 'r' in val) return val- if (typeof val === 'string') return parseColor(val)- return { ...BLACK }- },- resolveNumber(ref: string): number {- const val = resolveVal(ref)- return typeof val === 'number' ? val : 0- },- resolveString(ref: string): string {- const val = resolveVal(ref)- return typeof val === 'string' ? val : ''- },- setActiveTheme(themeName: string) {- const modeId = modeByThemeValue.get(`theme:${themeName}`)- if (modeId) {- activeModeId = modeId- graph.activeMode.set(collectionId, modeId)- }- }- }-}-function parseFillColor(fill: string | PenFillObject, ctx: VarContext): Color {- const raw = typeof fill === 'string' ? fill : fill.color- return isVarRef(raw) ? ctx.resolveColor(raw) : parseColor(raw)-}--export function convertFill(fill: PenFill | undefined, ctx: VarContext, node?: SceneNode): Fill[] {- if (fill === undefined) return []- const fills = Array.isArray(fill) ? fill : [fill]- return fills.map((item, index) => {- const visible = typeof item === 'string' ? true : item.enabled !== false- const color = parseFillColor(item, ctx)- const result: Fill = { type: 'SOLID', visible, opacity: color.a, color }- if (node) bindIfVar(node, `fills[${index}]`, typeof item === 'string' ? item : item.color, ctx)- return result- })-}--function strokeWeight(stroke: PenStroke): number {- return typeof stroke.thickness === 'number'- ? stroke.thickness- : Math.max(...Object.values(stroke.thickness))-}--export function convertStroke(- stroke: PenStroke | undefined,- ctx: VarContext,- node?: SceneNode-): Stroke[] {- if (!stroke?.fill) return []- const color = isVarRef(stroke.fill) ? ctx.resolveColor(stroke.fill) : parseColor(stroke.fill)- let align: Stroke['align'] = 'CENTER'- if (stroke.align === 'inside') align = 'INSIDE'- else if (stroke.align === 'outside') align = 'OUTSIDE'-- const result: Stroke = {- type: 'SOLID',- visible: true,- color,- opacity: color.a,- weight: strokeWeight(stroke),- align,- dashPattern: []- }- if (node) {- bindIfVar(node, 'strokes[0]', stroke.fill, ctx)- if (typeof stroke.thickness === 'object') {- node.independentStrokeWeights = true- node.borderTopWeight = stroke.thickness.top ?? 0- node.borderRightWeight = stroke.thickness.right ?? 0- node.borderBottomWeight = stroke.thickness.bottom ?? 0- node.borderLeftWeight = stroke.thickness.left ?? 0- }- node.strokeJoin = mapStrokeJoin(stroke.join)- node.strokeCap = mapStrokeCap(stroke.cap)- }- return [result]-}--function mapStrokeJoin(join: string | undefined): StrokeJoin {- if (join === 'round') return 'ROUND'- if (join === 'bevel') return 'BEVEL'- return 'MITER'-}--function mapStrokeCap(cap: string | undefined): StrokeCap {- if (cap === 'round') return 'ROUND'- if (cap === 'square') return 'SQUARE'- return 'NONE'-}--export function convertEffects(effect: PenEffect | PenEffect[] | undefined): Effect[] {- if (!effect) return []- const effects = Array.isArray(effect) ? effect : [effect]- return effects.flatMap((item) => {- if (item.type !== 'shadow') return []- const color = item.color ? parseColor(item.color) : { r: 0, g: 0, b: 0, a: 0.25 }- return [- {- type: item.shadowType === 'inner' ? 'INNER_SHADOW' : 'DROP_SHADOW',- visible: true,- blendMode: 'NORMAL',- color,- offset: item.offset ?? { x: 0, y: 0 },- radius: item.blur ?? 0,- spread: item.spread ?? 0- } satisfies Effect- ]- })-}+import type { PenNode, PenNumber } from './schema'+import { isVarRef, resolveNumber, type VarContext } from './variables'export function applyCornerRadius(node: SceneNode,@@ -391,10 +35,9 @@ export function applyCornerRadius(node.cornerRadius = parseSize(radius, 0, ctx).value}-export function applyPadding(node: SceneNode, padding: PenNode['padding'], ctx?: VarContext): void {+export function applyPadding(node: SceneNode, padding: PenNode['padding'], ctx: VarContext): void {if (padding === undefined) return- const resolve = (v: number | string): number =>- typeof v === 'string' ? (isVarRef(v) && ctx ? ctx.resolveNumber(v) : Number(v) || 0) : v+ const resolve = (value: PenNumber): number => resolveNumber(value, ctx)Object.assign(node,paddingFromShorthand(Array.isArray(padding) ? padding.map(resolve) : [resolve(padding)])diff --git a/packages/pen/src/effects.ts b/packages/pen/src/effects.tsnew file mode 100644index 000000000..682e91474--- /dev/null+++ b/packages/pen/src/effects.ts@@ -0,0 +1,43 @@+import type { Effect } from '@open-pencil/scene-graph'++import { mapBlendMode } from './paints'+import type { PenEffect, PenNode } from './schema'+import { resolveBoolean, resolveColor, resolveNumber, type VarContext } from './variables'++const DEFAULT_SHADOW_COLOR = { r: 0, g: 0, b: 0, a: 0.25 }++function convertEffect(effect: PenEffect, ctx: VarContext): Effect | null {+ const base = {+ visible: resolveBoolean(effect.enabled, ctx),+ color: { ...DEFAULT_SHADOW_COLOR },+ offset: { x: 0, y: 0 },+ spread: 0,+ blendMode: mapBlendMode(effect.blendMode) ?? 'NORMAL'+ } satisfies Partial<Effect>+ if (effect.type === 'blur' || effect.type === 'background_blur') {+ return {+ ...base,+ type: effect.type === 'blur' ? 'LAYER_BLUR' : 'BACKGROUND_BLUR',+ radius: resolveNumber(effect.radius, ctx)+ }+ }+ if (effect.type !== 'shadow') return null+ return {+ ...base,+ type: effect.shadowType === 'inner' ? 'INNER_SHADOW' : 'DROP_SHADOW',+ color: effect.color ? resolveColor(effect.color, ctx) : base.color,+ offset: {+ x: resolveNumber(effect.offset?.x, ctx),+ y: resolveNumber(effect.offset?.y, ctx)+ },+ radius: resolveNumber(effect.blur, ctx),+ spread: resolveNumber(effect.spread, ctx)+ }+}++/** A node's effects; shader effects are not drawn. */+export function convertEffects(effect: PenNode['effect'], ctx: VarContext): Effect[] {+ if (!effect) return []+ const effects = Array.isArray(effect) ? effect : [effect]+ return effects.flatMap((item) => convertEffect(item, ctx) ?? [])+}diff --git a/packages/pen/src/index.ts b/packages/pen/src/index.tsindex 7a64c8910..d6defc5be 100644--- a/packages/pen/src/index.ts+++ b/packages/pen/src/index.ts@@ -1,2 +1,2 @@export { parsePenFile, readPenFile } from './read'-export * from './convert'+export type { PenDocument, PenNode, PenOverride } from './schema'diff --git a/packages/pen/src/paints.ts b/packages/pen/src/paints.tsnew file mode 100644index 000000000..e491d589a--- /dev/null+++ b/packages/pen/src/paints.ts@@ -0,0 +1,258 @@+import type {+ BlendMode,+ Fill,+ FillType,+ GradientStop,+ SceneNode,+ Stroke,+ StrokeCap,+ StrokeJoin+} from '@open-pencil/scene-graph'+import { TRANSPARENT } from '@open-pencil/scene-graph/constants'+import {+ ellipticalGradientTransform,+ linearGradientTransformFromAxes+} from '@open-pencil/scene-graph/gradient'+import type { Vector } from '@open-pencil/scene-graph/primitives'++import type {+ PenGradientPaint,+ PenLegacyStroke,+ PenNode,+ PenOverride,+ PenPaint,+ PenPaints,+ PenSides+} from './schema'+import {+ bindIfVar,+ resolveBoolean,+ resolveColor,+ resolveNumber,+ type VarContext+} from './variables'++type PaintField = 'fills' | 'strokes'++/**+ * pen.dev blend modes by name. Linear burn and linear dodge have no counterpart in the scene+ * graph, so they draw as normal.+ */+const BLEND_MODES: Partial<Record<string, BlendMode>> = {+ normal: 'NORMAL',+ darken: 'DARKEN',+ multiply: 'MULTIPLY',+ colorBurn: 'COLOR_BURN',+ light: 'LIGHTEN',+ screen: 'SCREEN',+ colorDodge: 'COLOR_DODGE',+ overlay: 'OVERLAY',+ softLight: 'SOFT_LIGHT',+ hardLight: 'HARD_LIGHT',+ difference: 'DIFFERENCE',+ exclusion: 'EXCLUSION',+ hue: 'HUE',+ saturation: 'SATURATION',+ color: 'COLOR',+ luminosity: 'LUMINOSITY'+}++export function mapBlendMode(value: string | undefined): BlendMode | undefined {+ return value === undefined ? undefined : BLEND_MODES[value]+}++const GRADIENT_TYPES: Partial<Record<string, FillType>> = {+ linear: 'GRADIENT_LINEAR',+ radial: 'GRADIENT_RADIAL',+ angular: 'GRADIENT_ANGULAR'+}++/**+ * pen.dev places a gradient in the layer's unit square: `center` defaults to the middle, a linear+ * gradient runs `size.height` long from bottom to top, radial and angular ones are ellipses of+ * diameter `size`, and `rotation` turns all of it counter-clockwise in that square. An angular+ * gradient starts at the top and turns clockwise. Measured against pen.dev 2.21 renders.+ */+function gradientTransform(paint: PenGradientPaint, type: FillType, ctx: VarContext) {+ const center = { x: paint.center?.x ?? 0.5, y: paint.center?.y ?? 0.5 }+ const width = resolveNumber(paint.size?.width, ctx, 1)+ const height = resolveNumber(paint.size?.height, ctx, 1)+ const angle = (resolveNumber(paint.rotation, ctx) * Math.PI) / 180+ // Up, and right, after turning counter-clockwise on a y-down canvas.+ const up = { x: -Math.sin(angle), y: -Math.cos(angle) }+ const right = { x: Math.cos(angle), y: -Math.sin(angle) }+ const along = (direction: Vector, length: number): Vector => ({+ x: center.x + direction.x * length,+ y: center.y + direction.y * length+ })+ if (type === 'GRADIENT_LINEAR') {+ return linearGradientTransformFromAxes(along(up, -height / 2), along(up, height / 2), {+ x: right.x * height,+ y: right.y * height+ })+ }+ if (type === 'GRADIENT_ANGULAR') {+ return ellipticalGradientTransform(center, along(up, height / 2), along(right, width / 2))+ }+ return ellipticalGradientTransform(center, along(right, width / 2), {+ x: center.x - up.x * (height / 2),+ y: center.y - up.y * (height / 2)+ })+}++function gradientStops(paint: PenGradientPaint, ctx: VarContext): GradientStop[] {+ return (paint.colors ?? []).map((stop) => ({+ color: resolveColor(stop.color, ctx),+ position: resolveNumber(stop.position, ctx)+ }))+}++function convertPaint(+ paint: PenPaint,+ index: number,+ field: PaintField,+ ctx: VarContext,+ node: SceneNode | undefined+): Fill | null {+ if (typeof paint === 'string' || paint.type === 'color') {+ const raw = typeof paint === 'string' ? paint : paint.color+ if (typeof raw !== 'string') return null+ const color = resolveColor(raw, ctx)+ if (node) bindIfVar(node, `${field}/${index}/color`, raw, ctx)+ return {+ type: 'SOLID',+ color,+ opacity: color.a,+ visible: typeof paint === 'string' || resolveBoolean(paint.enabled, ctx),+ blendMode: typeof paint === 'string' ? undefined : mapBlendMode(paint.blendMode)+ }+ }+ if (paint.type === 'gradient') {+ const gradient = paint as PenGradientPaint+ const type = GRADIENT_TYPES[gradient.gradientType ?? 'linear']+ if (!type) return null+ return {+ type,+ color: { ...TRANSPARENT },+ opacity: resolveNumber(gradient.opacity, ctx, 1),+ visible: resolveBoolean(gradient.enabled, ctx),+ blendMode: mapBlendMode(gradient.blendMode),+ gradientStops: gradientStops(gradient, ctx),+ gradientTransform: gradientTransform(gradient, type, ctx)+ }+ }+ return null+}++/** A node's fills, or its strokes' paints, in pen.dev's order: the last one draws on top. */+export function convertPaints(+ paints: PenPaints | undefined,+ field: PaintField,+ ctx: VarContext,+ node?: SceneNode+): Fill[] {+ if (paints === undefined) return []+ const list = Array.isArray(paints) ? paints : [paints]+ const result: Fill[] = []+ for (const paint of list) {+ const converted = convertPaint(paint, result.length, field, ctx, node)+ if (converted) result.push(converted)+ }+ return result+}++const ALIGNMENTS: Partial<Record<string, Stroke['align']>> = {+ inner: 'INSIDE',+ inside: 'INSIDE',+ center: 'CENTER',+ outer: 'OUTSIDE',+ outside: 'OUTSIDE'+}++const JOINS: Partial<Record<string, StrokeJoin>> = {+ miter: 'MITER',+ bevel: 'BEVEL',+ round: 'ROUND'+}+const CAPS: Partial<Record<string, StrokeCap>> = { butt: 'NONE', round: 'ROUND', square: 'SQUARE' }++/** The stroke fields of a node, with the 2.8 object form spread into the current ones. */+export interface PenStrokeFields {+ paints: PenPaints | undefined+ width: PenNode['strokeWidth']+ alignment: string | undefined+ cap: string | undefined+ join: string | undefined+}++function isLegacyStroke(stroke: PenNode['stroke']): stroke is PenLegacyStroke {+ return typeof stroke === 'object' && !Array.isArray(stroke) && 'thickness' in stroke+}++/** A node's stroke fields; an instance's own fields replace its component's one by one. */+export function strokeFields(pen: PenOverride, base?: PenStrokeFields): PenStrokeFields {+ if (isLegacyStroke(pen.stroke)) {+ return {+ paints: pen.stroke.fill,+ width: pen.stroke.thickness,+ alignment: pen.stroke.align,+ cap: pen.stroke.cap,+ join: pen.stroke.join+ }+ }+ return {+ paints: pen.stroke ?? base?.paints,+ width: pen.strokeWidth ?? base?.width,+ alignment: pen.strokeAlignment ?? base?.alignment,+ cap: pen.strokeLinecap ?? base?.cap,+ join: pen.strokeLinejoin ?? base?.join+ }+}++function sideWeights(sides: PenSides, ctx: VarContext) {+ return {+ top: resolveNumber(sides.top, ctx),+ right: resolveNumber(sides.right, ctx),+ bottom: resolveNumber(sides.bottom, ctx),+ left: resolveNumber(sides.left, ctx)+ }+}++/**+ * Sets a node's strokes. pen.dev draws a stroke only with both paints and a width: a missing side+ * of a per-side width is zero, and the alignment defaults to centred.+ */+export function applyStroke(node: SceneNode, fields: PenStrokeFields, ctx: VarContext): void {+ node.strokes = []+ node.independentStrokeWeights = false+ if (fields.paints === undefined || fields.width === undefined) return++ let weight: number+ if (typeof fields.width === 'object') {+ const sides = sideWeights(fields.width, ctx)+ weight = Math.max(sides.top, sides.right, sides.bottom, sides.left)+ node.independentStrokeWeights = true+ node.borderTopWeight = sides.top+ node.borderRightWeight = sides.right+ node.borderBottomWeight = sides.bottom+ node.borderLeftWeight = sides.left+ } else {+ weight = resolveNumber(fields.width, ctx)+ bindIfVar(node, 'strokeWeight', fields.width, ctx)+ }+ if (weight <= 0) return++ const align = ALIGNMENTS[fields.alignment ?? 'center'] ?? 'CENTER'+ const cap = CAPS[fields.cap ?? 'butt'] ?? 'NONE'+ const join = JOINS[fields.join ?? 'miter'] ?? 'MITER'+ node.strokeCap = cap+ node.strokeJoin = join+ node.strokes = convertPaints(fields.paints, 'strokes', ctx, node).map((paint) => ({+ ...paint,+ weight,+ align,+ cap,+ join,+ dashPattern: []+ }))+}diff --git a/packages/pen/src/read.ts b/packages/pen/src/read.tsindex e4cd518d5..815fe0008 100644--- a/packages/pen/src/read.ts+++ b/packages/pen/src/read.ts@@ -1,3 +1,5 @@+import * as v from 'valibot'+import {SceneGraph,type AxisSizingMode,@@ -14,12 +16,6 @@ import { parseSVGPath } from '@open-pencil/scene-graph/parse-path'import {applyCornerRadius,applyPadding,- bindIfVar,- buildVarContext,- convertEffects,- convertFill,- convertStroke,- isVarRef,mapAlignItems,mapFontWeight,mapJustifyContent,@@ -27,11 +23,19 @@ import {mapNodeType,mapTextAlign,mapTextAlignVertical,- parseSize,- type PenDocument,- type PenNode,- type VarContext+ parseSize} from './convert'+import { convertEffects } from './effects'+import { applyStroke, convertPaints, strokeFields } from './paints'+import { penFileSchema, type PenNode, type PenOverride } from './schema'+import {+ bindIfVar,+ buildVarContext,+ isVarRef,+ resolveBoolean,+ resolveNumber,+ type VarContext+} from './variables'function scaleVectorNetwork(vn: VectorNetwork, targetW: number, targetH: number): void {if (vn.vertices.length === 0) return@@ -67,18 +71,18 @@ function resolveFontFamily(raw: string | undefined, ctx: VarContext): string {return raw}-function buildBaseOverrides(pen: PenNode): Partial<SceneNode> {+function buildBaseOverrides(pen: PenNode, ctx: VarContext): Partial<SceneNode> {return {id: pen.id,name: pen.name ?? (pen.type === 'icon_font' ? (pen.iconFontName ?? 'Icon') : pen.type),x: pen.x ?? 0,y: pen.y ?? 0,- visible: pen.enabled !== false,- opacity: pen.opacity ?? 1,- rotation: pen.rotation ?? 0,- flipX: pen.flipX ?? false,- flipY: pen.flipY ?? false,- clipsContent: pen.clip ?? false,+ visible: resolveBoolean(pen.enabled, ctx),+ opacity: resolveNumber(pen.opacity, ctx, 1),+ rotation: resolveNumber(pen.rotation, ctx),+ flipX: resolveBoolean(pen.flipX, ctx, false),+ flipY: resolveBoolean(pen.flipY, ctx, false),+ clipsContent: resolveBoolean(pen.clip, ctx, false),boundVariables: {}}}@@ -116,16 +120,17 @@ function applyTextProps(node: SceneNode, pen: PenNode, ctx: VarContext): void {pen.type === 'icon_font'? (pen.iconFontFamily ?? 'Material Symbols Sharp'): resolveFontFamily(pen.fontFamily, ctx)- node.fontSize = pen.fontSize ?? 14+ 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) {- node.lineHeight = pen.lineHeight < 5 ? pen.lineHeight * node.fontSize : pen.lineHeight+ const lineHeight = resolveNumber(pen.lineHeight, ctx)+ node.lineHeight = lineHeight < 5 ? lineHeight * node.fontSize : lineHeight}- if (pen.letterSpacing !== undefined) node.letterSpacing = pen.letterSpacing+ 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)@@ -178,11 +183,9 @@ function applyRefVisuals(ctx: VarContext): void {if (!compPen) return- if (pen.fill === undefined && compPen.fill !== undefined)- node.fills = convertFill(compPen.fill, ctx, node)- if (pen.stroke === undefined && compPen.stroke)- node.strokes = convertStroke(compPen.stroke, ctx, node)- if (pen.effect === undefined && compPen.effect) node.effects = convertEffects(compPen.effect)+ if (pen.fill === undefined) node.fills = convertPaints(compPen.fill, 'fills', ctx, node)+ applyStroke(node, strokeFields(pen, strokeFields(compPen)), ctx)+ if (pen.effect === undefined) node.effects = convertEffects(compPen.effect, ctx)if (pen.cornerRadius === undefined) applyCornerRadius(node, compPen.cornerRadius, ctx)}@@ -239,7 +242,7 @@ function createSceneNode(if (pen.theme) applyTheme(pen.theme, ctx)const { w, h, layout, isTextLike } = resolveSizing(pen, ctx)- const overrides = buildBaseOverrides(pen)+ const overrides = buildBaseOverrides(pen, ctx)overrides.width = w.valueoverrides.height = h.valueconst hasChildren = (pen.children?.length ?? 0) > 0@@ -257,9 +260,9 @@ function createSceneNode(const node = graph.createNode(mapNodeType(pen), parentId, overrides)- if (pen.fill !== undefined) node.fills = convertFill(pen.fill, ctx, node)- if (pen.stroke) node.strokes = convertStroke(pen.stroke, ctx, node)- node.effects = convertEffects(pen.effect)+ node.fills = convertPaints(pen.fill, 'fills', ctx, node)+ applyStroke(node, strokeFields(pen), ctx)+ node.effects = convertEffects(pen.effect, ctx)applyCornerRadius(node, pen.cornerRadius, ctx)applyPadding(node, pen.padding, ctx)@@ -339,21 +342,19 @@ function findCloneByNameFallback(return matches.length === 1 ? matches[0] : undefined}-function applyOverrideProps(- target: SceneNode,- overrideData: Partial<PenNode>,- ctx: VarContext-): void {- if (overrideData.fill !== undefined) target.fills = convertFill(overrideData.fill, ctx, target)+function applyOverrideProps(target: SceneNode, overrideData: PenOverride, ctx: VarContext): void {+ if (overrideData.fill !== undefined)+ target.fills = convertPaints(overrideData.fill, 'fills', ctx, target)if (overrideData.content !== undefined) target.text = overrideData.contentif (overrideData.x !== undefined) target.x = overrideData.xif (overrideData.y !== undefined) target.y = overrideData.y- if (overrideData.enabled !== undefined) target.visible = overrideData.enabled+ if (overrideData.enabled !== undefined) target.visible = resolveBoolean(overrideData.enabled, ctx)if (overrideData.width !== undefined)target.width = parseSize(overrideData.width, target.width, ctx).valueif (overrideData.height !== undefined)target.height = parseSize(overrideData.height, target.height, ctx).value- if (overrideData.rotation !== undefined) target.rotation = overrideData.rotation+ if (overrideData.rotation !== undefined)+ target.rotation = resolveNumber(overrideData.rotation, ctx)if (overrideData.name !== undefined) target.name = overrideData.name}@@ -433,13 +434,10 @@ function resolveNodeVars(node: SceneNode, graph: SceneGraph, ctx: VarContext): vif (!variable) continueconst modeVal =variable.valuesByMode[ctx.activeModeId] ?? Object.values(variable.valuesByMode)[0]- if (key.startsWith('fills[') && typeof modeVal === 'object' && 'r' in modeVal) {- const idx = Number.parseInt(key.match(/\d+/)?.[0] ?? '0', 10)- if (node.fills[idx]) node.fills[idx].color = modeVal- } else if (key.startsWith('strokes[') && typeof modeVal === 'object' && 'r' in modeVal) {- const idx = Number.parseInt(key.match(/\d+/)?.[0] ?? '0', 10)- if (node.strokes[idx]) node.strokes[idx].color = modeVal- }+ const paint = /^(fills|strokes)\/(\d+)\/color$/.exec(key)+ if (!paint || typeof modeVal !== 'object' || !('r' in modeVal)) continue+ const target = node[paint[1] === 'fills' ? 'fills' : 'strokes'].at(Number(paint[2]))+ if (target) target.color = modeVal}for (const childId of node.childIds) {const child = graph.getNode(childId)@@ -472,7 +470,11 @@ function fixInstanceWidths(graph: SceneGraph): void {}export function parsePenFile(json: string): SceneGraph {- const doc: PenDocument = JSON.parse(json)+ const parsed = v.safeParse(penFileSchema, json)+ if (!parsed.success) {+ throw new Error(`Not a .pen document: ${v.summarize(parsed.issues)}`)+ }+ const doc = parsed.outputconst graph = new SceneGraph()for (const page of graph.getPages(true)) {diff --git a/packages/pen/src/schema.ts b/packages/pen/src/schema.tsnew file mode 100644index 000000000..150d7254d--- /dev/null+++ b/packages/pen/src/schema.ts@@ -0,0 +1,233 @@+import * as v from 'valibot'++/**+ * The `.pen` document as pen.dev writes it (schema 2.21), plus the older forms still found in+ * files: the object `stroke` of 2.8 and `icon_font` nodes. Properties typed `…OrVariable` hold a+ * `$name` reference in place of the value. Enumerated values stay strings so a value this reader+ * does not know falls back to the default instead of rejecting the document.+ */++const numSchema = v.union([v.number(), v.string()])+const boolSchema = v.union([v.boolean(), v.string()])+const strSchema = v.string()+const sidesSchema = v.looseObject({+ top: v.optional(numSchema),+ right: v.optional(numSchema),+ bottom: v.optional(numSchema),+ left: v.optional(numSchema)+})++const paintBase = {+ enabled: v.optional(boolSchema),+ blendMode: v.optional(strSchema)+}++const colorPaintSchema = v.looseObject({+ type: v.literal('color'),+ ...paintBase,+ color: strSchema+})++const gradientPaintSchema = v.looseObject({+ type: v.literal('gradient'),+ ...paintBase,+ gradientType: v.optional(strSchema),+ opacity: v.optional(numSchema),+ center: v.optional(v.looseObject({ x: v.optional(v.number()), y: v.optional(v.number()) })),+ size: v.optional(v.looseObject({ width: v.optional(numSchema), height: v.optional(numSchema) })),+ rotation: v.optional(numSchema),+ colors: v.optional(v.array(v.looseObject({ color: strSchema, position: numSchema })))+})++const imagePaintSchema = v.looseObject({+ type: v.literal('image'),+ ...paintBase,+ opacity: v.optional(numSchema),+ url: v.optional(strSchema),+ mode: v.optional(strSchema),+ transform: v.optional(+ v.tuple([v.number(), v.number(), v.number(), v.number(), v.number(), v.number()])+ )+})++/** Shader and mesh gradient paints, and any paint type this reader does not draw. */+const otherPaintSchema = v.looseObject({ type: strSchema, ...paintBase })++const paintSchema = v.union([+ strSchema,+ colorPaintSchema,+ gradientPaintSchema,+ imagePaintSchema,+ otherPaintSchema+])+const paintsSchema = v.union([paintSchema, v.array(paintSchema)])++/** The 2.8 stroke: one colour with its weight and placement in one object. */+const legacyStrokeSchema = v.looseObject({+ thickness: v.union([numSchema, sidesSchema]),+ fill: v.optional(strSchema),+ align: v.optional(strSchema),+ join: v.optional(strSchema),+ cap: v.optional(strSchema)+})++const effectSchema = v.looseObject({+ type: strSchema,+ enabled: v.optional(boolSchema),+ radius: v.optional(numSchema),+ shadowType: v.optional(strSchema),+ offset: v.optional(v.looseObject({ x: numSchema, y: numSchema })),+ blur: v.optional(numSchema),+ /** Written by older files; current pen.dev shadows have no spread. */+ spread: v.optional(numSchema),+ color: v.optional(strSchema),+ blendMode: v.optional(strSchema)+})++const sizeSchema = numSchema+const paddingSchema = v.union([+ numSchema,+ v.tuple([numSchema, numSchema]),+ v.tuple([numSchema, numSchema, numSchema, numSchema])+])+const cornerRadiusSchema = v.union([numSchema, v.array(numSchema)])++/** Every property a node, or an override of one, can carry. */+const nodeFields = {+ name: v.optional(strSchema),+ context: v.optional(strSchema),+ x: v.optional(v.number()),+ y: v.optional(v.number()),+ width: v.optional(sizeSchema),+ height: v.optional(sizeSchema),+ reusable: v.optional(v.boolean()),+ theme: v.optional(v.record(strSchema, strSchema)),+ enabled: v.optional(boolSchema),+ opacity: v.optional(numSchema),+ flipX: v.optional(boolSchema),+ flipY: v.optional(boolSchema),+ layoutPosition: v.optional(strSchema),+ rotation: v.optional(numSchema),++ fill: v.optional(paintsSchema),+ stroke: v.optional(v.union([paintsSchema, legacyStrokeSchema])),+ strokeWidth: v.optional(v.union([numSchema, sidesSchema])),+ strokeLinecap: v.optional(strSchema),+ strokeLinejoin: v.optional(strSchema),+ strokeAlignment: v.optional(strSchema),+ effect: v.optional(v.union([effectSchema, v.array(effectSchema)])),+ cornerRadius: v.optional(cornerRadiusSchema),++ layout: v.optional(strSchema),+ gap: v.optional(numSchema),+ layoutIncludeStroke: v.optional(v.boolean()),+ padding: v.optional(paddingSchema),+ justifyContent: v.optional(strSchema),+ alignItems: v.optional(strSchema),+ clip: v.optional(boolSchema),+ placeholder: v.optional(v.boolean()),+ slot: v.optional(v.union([v.literal(false), v.array(strSchema)])),++ innerRadius: v.optional(numSchema),+ startAngle: v.optional(numSchema),+ sweepAngle: v.optional(numSchema),+ polygonCount: v.optional(numSchema),+ geometry: v.optional(strSchema),+ fillRule: v.optional(strSchema),+ viewBox: v.optional(v.tuple([v.number(), v.number(), v.number(), v.number()])),++ content: v.optional(strSchema),+ textGrowth: v.optional(strSchema),+ fontFamily: v.optional(strSchema),+ fontSize: v.optional(numSchema),+ fontWeight: v.optional(numSchema),+ fontStyle: v.optional(strSchema),+ letterSpacing: v.optional(numSchema),+ lineHeight: v.optional(numSchema),+ textAlign: v.optional(strSchema),+ textAlignVertical: v.optional(strSchema),+ underline: v.optional(boolSchema),+ strikethrough: v.optional(boolSchema),+ href: v.optional(strSchema),++ library: v.optional(strSchema),+ icon: v.optional(strSchema),+ weight: v.optional(numSchema),+ iconFontName: v.optional(strSchema),+ iconFontFamily: v.optional(strSchema),++ ref: v.optional(strSchema)+}++type NodeFields = v.InferOutput<v.ObjectSchema<typeof nodeFields, undefined>>++/** Properties an instance sets on one of its component's descendants, or a node replacing it. */+export interface PenOverride extends NodeFields {+ type?: string+ id?: string+ children?: PenNode[]+ descendants?: Record<string, PenOverride>+ [key: string]: unknown+}++export interface PenNode extends PenOverride {+ type: string+ id: string+}++const overrideSchema: v.GenericSchema<unknown, PenOverride> = v.looseObject({+ ...nodeFields,+ type: v.optional(strSchema),+ id: v.optional(strSchema),+ children: v.optional(v.array(v.lazy(() => nodeSchema))),+ descendants: v.optional(+ v.record(+ strSchema,+ v.lazy(() => overrideSchema)+ )+ )+})++const nodeSchema: v.GenericSchema<unknown, PenNode> = v.looseObject({+ ...nodeFields,+ type: strSchema,+ id: strSchema,+ children: v.optional(v.array(v.lazy(() => nodeSchema))),+ descendants: v.optional(v.record(strSchema, overrideSchema))+})++const variableScalarSchema = v.union([v.string(), v.number(), v.boolean()])++const variableSchema = v.looseObject({+ type: strSchema,+ value: v.union([+ variableScalarSchema,+ v.array(+ v.looseObject({+ value: variableScalarSchema,+ theme: v.optional(v.record(strSchema, strSchema))+ })+ )+ ])+})++export const penDocumentSchema = v.looseObject({+ version: v.optional(strSchema),+ themes: v.optional(v.record(strSchema, v.array(strSchema))),+ imports: v.optional(v.record(strSchema, strSchema)),+ variables: v.optional(v.record(strSchema, variableSchema)),+ children: v.array(nodeSchema)+})++export type PenDocument = v.InferOutput<typeof penDocumentSchema>+export type PenVariable = v.InferOutput<typeof variableSchema>+export type PenVariableScalar = v.InferOutput<typeof variableScalarSchema>+export type PenPaint = v.InferOutput<typeof paintSchema>+export type PenPaints = v.InferOutput<typeof paintsSchema>+export type PenGradientPaint = v.InferOutput<typeof gradientPaintSchema>+export type PenLegacyStroke = v.InferOutput<typeof legacyStrokeSchema>+export type PenEffect = v.InferOutput<typeof effectSchema>+export type PenSides = v.InferOutput<typeof sidesSchema>+export type PenNumber = v.InferOutput<typeof numSchema>++export const penFileSchema = v.pipe(v.string(), v.parseJson(), penDocumentSchema)diff --git a/packages/pen/src/variables.ts b/packages/pen/src/variables.tsnew file mode 100644index 000000000..6cbe142e0--- /dev/null+++ b/packages/pen/src/variables.ts@@ -0,0 +1,206 @@+import {+ generateId,+ type SceneGraph,+ type SceneNode,+ type Variable,+ type VariableCollection,+ type VariableCollectionMode,+ type VariableType,+ type VariableValue+} from '@open-pencil/scene-graph'+import { parseColor } from '@open-pencil/scene-graph/color'+import { BLACK } from '@open-pencil/scene-graph/constants'+import type { Color } from '@open-pencil/scene-graph/primitives'++import type { PenNumber, PenVariable, PenVariableScalar } from './schema'++export interface VarContext {+ byName: Map<string, { id: string; variable: Variable }>+ activeModeId: string+ collectionId: string+ modeByThemeName: Map<string, string>+ resolveColor(ref: string): Color+ resolveNumber(ref: string): number+ resolveString(ref: string): string+ resolveBoolean(ref: string): boolean+ setActiveTheme(themeName: string): void+}++function penVarTypeToSceneType(t: string): VariableType {+ if (t === 'color') return 'COLOR'+ if (t === 'number') return 'FLOAT'+ if (t === 'boolean') return 'BOOLEAN'+ return 'STRING'+}++function penValueToSceneValue(raw: PenVariableScalar, type: VariableType): VariableValue {+ if (type === 'COLOR' && typeof raw === 'string') return parseColor(raw)+ if (type === 'STRING') return String(raw)+ return raw+}++function defaultForType(type: VariableType): VariableValue {+ if (type === 'COLOR') return { ...BLACK }+ if (type === 'FLOAT') return 0+ if (type === 'BOOLEAN') return false+ return ''+}++export function isVarRef(val: unknown): val is string {+ return typeof val === 'string' && val.startsWith('$') && val.length > 1+}++function varName(ref: string): string {+ return ref.replace(/^\$/, '')+}++export function bindIfVar(node: SceneNode, field: string, val: unknown, ctx: VarContext): void {+ if (!isVarRef(val)) return+ const entry = ctx.byName.get(varName(val))+ if (entry) node.boundVariables[field] = entry.id+}++/** A number, or the value of the number variable it references. */+export function resolveNumber(value: PenNumber | undefined, ctx: VarContext, fallback = 0): number {+ if (value === undefined) return fallback+ if (typeof value === 'number') return value+ if (isVarRef(value)) return ctx.resolveNumber(value)+ const parsed = Number(value)+ return Number.isFinite(parsed) ? parsed : fallback+}++/** A boolean, or the value of the variable it references. */+export function resolveBoolean(+ value: boolean | string | undefined,+ ctx: VarContext,+ fallback = true+): boolean {+ if (value === undefined) return fallback+ if (typeof value === 'boolean') return value+ return isVarRef(value) ? ctx.resolveBoolean(value) : value !== 'false'+}++/** A colour, or the value of the colour variable it references. */+export function resolveColor(value: string, ctx: VarContext): Color {+ return isVarRef(value) ? ctx.resolveColor(value) : parseColor(value)+}++export function buildVarContext(+ graph: SceneGraph,+ penVars: Record<string, PenVariable>,+ themes: Record<string, string[]>+): VarContext {+ const collectionId = generateId()+ const modes: VariableCollectionMode[] = []+ const themeKeys = Object.keys(themes)++ if (themeKeys.length > 0) {+ const themeKey = themeKeys[0]+ for (const modeName of themes[themeKey]) {+ modes.push({ modeId: generateId(), name: modeName })+ }+ }+ if (modes.length === 0) {+ modes.push({ modeId: generateId(), name: 'Default' })+ }++ const collection: VariableCollection = {+ id: collectionId,+ name: 'Variables',+ modes,+ defaultModeId: modes[0].modeId,+ variableIds: []+ }+ graph.addCollection(collection)++ const modeByThemeValue = new Map<string, string>()+ if (themeKeys.length > 0) {+ const themeKey = themeKeys[0]+ for (const mode of modes) {+ modeByThemeValue.set(`${themeKey}:${mode.name}`, mode.modeId)+ }+ }++ const byName = new Map<string, { id: string; variable: Variable }>()++ for (const [name, def] of Object.entries(penVars)) {+ const varId = generateId()+ const varType = penVarTypeToSceneType(def.type)+ const valuesByMode: Record<string, VariableValue> = {}++ if (Array.isArray(def.value)) {+ for (const entry of def.value) {+ if (entry.theme) {+ const [tKey, tVal] = Object.entries(entry.theme)[0]+ const modeId = modeByThemeValue.get(`${tKey}:${tVal}`)+ if (modeId) valuesByMode[modeId] = penValueToSceneValue(entry.value, varType)+ } else {+ valuesByMode[modes[0].modeId] = penValueToSceneValue(entry.value, varType)+ }+ }+ } else {+ valuesByMode[modes[0].modeId] = penValueToSceneValue(def.value, varType)+ }++ for (const mode of modes) {+ if (!(mode.modeId in valuesByMode)) {+ valuesByMode[mode.modeId] = valuesByMode[modes[0].modeId] ?? defaultForType(varType)+ }+ }++ const variable: Variable = {+ id: varId,+ name,+ type: varType,+ collectionId,+ valuesByMode,+ description: '',+ hiddenFromPublishing: false+ }+ graph.addVariable(variable)+ byName.set(name, { id: varId, variable })+ }++ let activeModeId = modes[0].modeId++ function resolveVal(ref: string): VariableValue | undefined {+ const entry = byName.get(varName(ref))+ if (!entry) return undefined+ return (+ entry.variable.valuesByMode[activeModeId] ?? Object.values(entry.variable.valuesByMode)[0]+ )+ }++ return {+ byName,+ activeModeId,+ collectionId,+ modeByThemeName: modeByThemeValue,+ resolveColor(ref: string): Color {+ const val = resolveVal(ref)+ if (val === undefined) return parseColor(ref)+ if (typeof val === 'object' && 'r' in val) return val+ if (typeof val === 'string') return parseColor(val)+ return { ...BLACK }+ },+ resolveNumber(ref: string): number {+ const val = resolveVal(ref)+ return typeof val === 'number' ? val : 0+ },+ resolveString(ref: string): string {+ const val = resolveVal(ref)+ return typeof val === 'string' ? val : ''+ },+ resolveBoolean(ref: string): boolean {+ const val = resolveVal(ref)+ return typeof val === 'boolean' ? val : val !== undefined && val !== 'false'+ },+ setActiveTheme(themeName: string) {+ const modeId = modeByThemeValue.get(`theme:${themeName}`)+ if (modeId) {+ activeModeId = modeId+ graph.activeMode.set(collectionId, modeId)+ }+ }+ }+}diff --git a/tests/engine/pen/file.test.ts b/packages/pen/tests/document.test.tssimilarity index 89%rename from tests/engine/pen/file.test.tsrename to packages/pen/tests/document.test.tsindex 8726f0d0e..90bd17f6b 100644--- a/tests/engine/pen/file.test.ts+++ b/packages/pen/tests/document.test.ts@@ -2,12 +2,10 @@ import { describe, expect, test } from 'bun:test'import { parsePenFile } from '@open-pencil/pen'-import { repoPath } from '#tests/helpers/paths'--const FIXTURE_DIR = repoPath('tests/fixtures')+import { FIXTURES } from './helpers/paths'async function loadFixture(name: string): Promise<string> {- return Bun.file(`${FIXTURE_DIR}/${name}`).text()+ return Bun.file(`${FIXTURES}/${name}`).text()}describe('parsePenFile', () => {diff --git a/packages/pen/tests/effects.test.ts b/packages/pen/tests/effects.test.tsnew file mode 100644index 000000000..8c2c6346f--- /dev/null+++ b/packages/pen/tests/effects.test.ts@@ -0,0 +1,46 @@+import { describe, expect, test } from 'bun:test'++import type { PenNode } from '@open-pencil/pen'++import { expectDefined, getNodeOrThrow } from './helpers/assert'+import { parseDocument } from './helpers/document'++function effectsOf(effect: PenNode['effect']) {+ return getNodeOrThrow(+ parseDocument([{ id: 'shape', type: 'rectangle', width: 100, height: 80, effect }]),+ 'shape'+ ).effects+}++describe('parsePenFile — effects', () => {+ test('reads layer and background blurs', () => {+ expect(+ effectsOf([+ { type: 'blur', radius: 8 },+ { type: 'background_blur', radius: 4 }+ ]).map((effect) => [effect.type, effect.radius])+ ).toEqual([+ ['LAYER_BLUR', 8],+ ['BACKGROUND_BLUR', 4]+ ])+ })++ test('reads inner and outer shadows', () => {+ const [outer, inner] = effectsOf([+ { type: 'shadow', offset: { x: 6, y: 8 }, blur: 10, color: '#00000080' },+ { type: 'shadow', shadowType: 'inner', offset: { x: 4, y: 4 }, blur: 6, enabled: false }+ ])+ expect(outer).toMatchObject({+ type: 'DROP_SHADOW',+ offset: { x: 6, y: 8 },+ radius: 10,+ visible: true+ })+ expect(expectDefined(outer).color.a).toBeCloseTo(128 / 255)+ expect(inner).toMatchObject({ type: 'INNER_SHADOW', radius: 6, visible: false })+ })++ test('skips shader effects', () => {+ expect(effectsOf({ type: 'shader', url: './fx.glsl' })).toEqual([])+ })+})diff --git a/packages/pen/tests/helpers/assert.ts b/packages/pen/tests/helpers/assert.tsnew file mode 100644index 000000000..d4d48ef65--- /dev/null+++ b/packages/pen/tests/helpers/assert.ts@@ -0,0 +1,12 @@+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'++export function expectDefined<T>(value: T | null | undefined, label = 'value'): NonNullable<T> {+ if (value == null) {+ throw new Error(`${label} was expected to be defined`)+ }+ return value+}++export function getNodeOrThrow(graph: SceneGraph, id: string): SceneNode {+ return expectDefined(graph.getNode(id), `node ${id}`)+}diff --git a/packages/pen/tests/helpers/document.ts b/packages/pen/tests/helpers/document.tsnew file mode 100644index 000000000..fd646fded--- /dev/null+++ b/packages/pen/tests/helpers/document.ts@@ -0,0 +1,6 @@+import { parsePenFile, type PenDocument, type PenNode } from '@open-pencil/pen'++/** Reads a document holding `children`, as pen.dev 2.21 writes it. */+export function parseDocument(children: PenNode[], fields: Partial<PenDocument> = {}) {+ return parsePenFile(JSON.stringify({ version: '2.21', ...fields, children }))+}diff --git a/packages/pen/tests/helpers/paths.ts b/packages/pen/tests/helpers/paths.tsnew file mode 100644index 000000000..b082321fe--- /dev/null+++ b/packages/pen/tests/helpers/paths.ts@@ -0,0 +1,14 @@+import { existsSync } from 'node:fs'+import { dirname, join } from 'node:path'+import { fileURLToPath } from 'node:url'++/** The workspace root, found by its lockfile rather than by counting directories. */+function workspaceRoot(from = dirname(fileURLToPath(import.meta.url))): string {+ for (let dir = from; ; dir = dirname(dir)) {+ if (existsSync(join(dir, 'bun.lock'))) return dir+ if (dirname(dir) === dir) throw new Error(`No workspace root above ${from}`)+ }+}++/** Fixtures shared across the repository; a module import would escape the package root. */+export const FIXTURES = join(workspaceRoot(), 'tests/fixtures')diff --git a/packages/pen/tests/paints.test.ts b/packages/pen/tests/paints.test.tsnew file mode 100644index 000000000..f30e15d40--- /dev/null+++ b/packages/pen/tests/paints.test.ts@@ -0,0 +1,105 @@+import { describe, expect, test } from 'bun:test'++import type { PenNode } from '@open-pencil/pen'+import { gradientPoint } from '@open-pencil/scene-graph/gradient'+import type { Vector } from '@open-pencil/scene-graph/primitives'++import { expectDefined, getNodeOrThrow } from './helpers/assert'+import { parseDocument } from './helpers/document'++function gradientOf(fill: PenNode['fill']) {+ const paint = expectDefined(fillsOf(fill)[0], 'gradient')+ return { paint, transform: expectDefined(paint.gradientTransform, 'gradient transform') }+}++function fillsOf(fill: PenNode['fill']) {+ return getNodeOrThrow(+ parseDocument([{ id: 'shape', type: 'rectangle', width: 200, height: 100, fill }]),+ 'shape'+ ).fills+}++const stops = [+ { color: '#000000', position: 0 },+ { color: '#FFFFFF', position: 1 }+]++function expectPoint(actual: Vector, x: number, y: number) {+ expect(actual.x).toBeCloseTo(x, 6)+ expect(actual.y).toBeCloseTo(y, 6)+}++describe('parsePenFile — fills', () => {+ test('keeps a hex alpha as the fill opacity', () => {+ expect(fillsOf('#FF000080')[0]).toMatchObject({ type: 'SOLID', opacity: 128 / 255 })+ })++ test('hides a disabled paint and keeps its blend mode', () => {+ const [base, top] = fillsOf([+ '#FFFF00',+ { type: 'color', color: '#00FFFF', blendMode: 'multiply', enabled: false }+ ])+ expect(expectDefined(base).visible).toBe(true)+ expect(top).toMatchObject({ visible: false, blendMode: 'MULTIPLY' })+ })++ // Measured on pen.dev 2.21: gradients live in the layer's unit square, rotation turns them+ // counter-clockwise, and an unrotated linear gradient runs from bottom to top.+ test('places an unrotated linear gradient from bottom to top', () => {+ const { paint: fill, transform } = gradientOf({+ type: 'gradient',+ gradientType: 'linear',+ colors: stops+ })+ expect(fill.type).toBe('GRADIENT_LINEAR')+ expect(fill.gradientStops?.map((stop) => stop.position)).toEqual([0, 1])+ expectPoint(gradientPoint(transform, { x: 0, y: 0.5 }), 0.5, 1)+ expectPoint(gradientPoint(transform, { x: 1, y: 0.5 }), 0.5, 0)+ })++ test('turns, moves and shortens a linear gradient in the unit square', () => {+ const { paint: fill, transform } = gradientOf({+ type: 'gradient',+ gradientType: 'linear',+ rotation: 90,+ center: { x: 0.3, y: 0.6 },+ size: { height: 0.5 },+ opacity: 0.7,+ colors: stops+ })+ expect(fill.opacity).toBe(0.7)+ expectPoint(gradientPoint(transform, { x: 0, y: 0.5 }), 0.55, 0.6)+ expectPoint(gradientPoint(transform, { x: 1, y: 0.5 }), 0.05, 0.6)+ })++ test('sizes a radial gradient by its diameters', () => {+ const { paint: fill, transform } = gradientOf({+ type: 'gradient',+ gradientType: 'radial',+ center: { x: 0.3, y: 0.6 },+ size: { width: 0.6, height: 0.8 },+ colors: stops+ })+ expect(fill.type).toBe('GRADIENT_RADIAL')+ expectPoint(gradientPoint(transform, { x: 0.5, y: 0.5 }), 0.3, 0.6)+ expectPoint(gradientPoint(transform, { x: 1, y: 0.5 }), 0.6, 0.6)+ expectPoint(gradientPoint(transform, { x: 0.5, y: 1 }), 0.3, 1)+ })++ test('starts an angular gradient at the top, turned counter-clockwise', () => {+ const { paint: fill, transform } = gradientOf({+ type: 'gradient',+ gradientType: 'angular',+ rotation: 90,+ colors: stops+ })+ expect(fill.type).toBe('GRADIENT_ANGULAR')+ // The scene graph starts angular gradients at +x of gradient space and turns clockwise.+ expectPoint(gradientPoint(transform, { x: 1, y: 0.5 }), 0, 0.5)+ expectPoint(gradientPoint(transform, { x: 0.5, y: 1 }), 0.5, 0)+ })++ test('skips paints it cannot draw instead of painting them black', () => {+ expect(fillsOf([{ type: 'mesh_gradient', columns: 2 }, '#FF0000'])).toHaveLength(1)+ })+})diff --git a/packages/pen/tests/strokes.test.ts b/packages/pen/tests/strokes.test.tsnew file mode 100644index 000000000..0efcd6c75--- /dev/null+++ b/packages/pen/tests/strokes.test.ts@@ -0,0 +1,116 @@+import { describe, expect, test } from 'bun:test'++import type { PenNode } from '@open-pencil/pen'++import { getNodeOrThrow } from './helpers/assert'+import { parseDocument } from './helpers/document'++const RED = { r: 1, g: 0, b: 0, a: 1 }++function rectangle(fields: Partial<PenNode>): PenNode {+ return { id: 'shape', type: 'rectangle', width: 100, height: 80, ...fields }+}++function strokeOf(fields: Partial<PenNode>) {+ return getNodeOrThrow(parseDocument([rectangle(fields)]), 'shape')+}++describe('parsePenFile — strokes (#1324)', () => {+ test('reads a stroke paint with a sibling width, centred by default', () => {+ const node = strokeOf({ stroke: '#FF0000', strokeWidth: 4 })+ expect(node.strokes).toHaveLength(1)+ expect(node.strokes[0]).toMatchObject({ type: 'SOLID', color: RED, weight: 4, align: 'CENTER' })+ })++ test('draws no stroke without a width, nor a width without a paint', () => {+ expect(strokeOf({ stroke: '#FF0000' }).strokes).toEqual([])+ expect(strokeOf({ strokeWidth: 4 }).strokes).toEqual([])+ })++ test('maps inner and outer alignment', () => {+ expect(+ strokeOf({ stroke: '#F00', strokeWidth: 2, strokeAlignment: 'inner' }).strokes[0]?.align+ ).toBe('INSIDE')+ expect(+ strokeOf({ stroke: '#F00', strokeWidth: 2, strokeAlignment: 'outer' }).strokes[0]?.align+ ).toBe('OUTSIDE')+ })++ test('stacks a list of stroke paints, the last on top', () => {+ const node = strokeOf({ stroke: ['#FF0000', '#0000FF80'], strokeWidth: 4 })+ expect(node.strokes.map((stroke) => stroke.color)).toEqual([+ RED,+ { r: 0, g: 0, b: 1, a: 128 / 255 }+ ])+ expect(node.strokes.every((stroke) => stroke.weight === 4)).toBe(true)+ })++ test('reads per-side widths, a missing side being zero', () => {+ const node = strokeOf({ stroke: '#F00', strokeWidth: { top: 2, right: 8, left: 4 } })+ expect(node.independentStrokeWeights).toBe(true)+ expect([+ node.borderTopWeight,+ node.borderRightWeight,+ node.borderBottomWeight,+ node.borderLeftWeight+ ]).toEqual([2, 8, 0, 4])+ expect(node.strokes[0]?.weight).toBe(8)+ })++ test('reads caps and joins', () => {+ const node = strokeOf({+ stroke: '#000',+ strokeWidth: 10,+ strokeLinecap: 'round',+ strokeLinejoin: 'bevel'+ })+ expect(node.strokeCap).toBe('ROUND')+ expect(node.strokeJoin).toBe('BEVEL')+ })++ test('skips a disabled stroke paint by hiding it', () => {+ const node = strokeOf({+ stroke: { type: 'color', color: '#F00', enabled: false },+ strokeWidth: 2+ })+ expect(node.strokes[0]?.visible).toBe(false)+ })++ test('still reads the 2.8 object form', () => {+ const node = strokeOf({+ stroke: { align: 'inside', thickness: { bottom: 1 }, fill: '#FF0000' }+ })+ expect(node.strokes[0]).toMatchObject({ color: RED, align: 'INSIDE', weight: 1 })+ expect(node.borderBottomWeight).toBe(1)+ })++ test('resolves and binds a variable width', () => {+ const graph = parseDocument([rectangle({ stroke: '#F00', strokeWidth: '$w' })], {+ variables: { w: { type: 'number', value: 3 } }+ })+ const node = getNodeOrThrow(graph, 'shape')+ expect(node.strokes[0]?.weight).toBe(3)+ expect(node.boundVariables.strokeWeight).toBeDefined()+ })++ test('lets an instance replace its component stroke field by field', () => {+ const graph = parseDocument([+ {+ id: 'button',+ type: 'frame',+ reusable: true,+ width: 80,+ height: 30,+ stroke: '#001155',+ strokeWidth: 2,+ strokeAlignment: 'inner'+ },+ { id: 'recoloured', type: 'ref', ref: 'button', stroke: '#FF0000' }+ ])+ expect(getNodeOrThrow(graph, 'recoloured').strokes[0]).toMatchObject({+ color: RED,+ weight: 2,+ align: 'INSIDE'+ })+ })+})diff --git a/tests/engine/pen/variables.test.ts b/packages/pen/tests/variables.test.tssimilarity index 95%rename from tests/engine/pen/variables.test.tsrename to packages/pen/tests/variables.test.tsindex 0afdcc6b4..26e72675f 100644--- a/tests/engine/pen/variables.test.ts+++ b/packages/pen/tests/variables.test.ts@@ -2,7 +2,7 @@ import { describe, expect, test } from 'bun:test'import { parsePenFile, type PenDocument, type PenNode } from '@open-pencil/pen'-import { expectDefined } from '#tests/helpers/assert'+import { expectDefined } from './helpers/assert'const BLUE = { r: 64 / 255, g: 148 / 255, b: 208 / 255, a: 1 }@@ -35,8 +35,8 @@ test('keeps plain and double-dash variable names distinct in one document', () =const graph = parsePenFile(JSON.stringify(document))const plain = graph.getNode('plain')const dashed = graph.getNode('dashed')- const plainId = plain?.boundVariables['fills[0]']- const dashedId = dashed?.boundVariables['fills[0]']+ const plainId = plain?.boundVariables['fills/0/color']+ const dashedId = dashed?.boundVariables['fills/0/color']expect(plain?.fills[0]?.color).toEqual(BLUE)expect(dashed?.fills[0]?.color).toEqual({ r: 1, g: 1, b: 1, a: 1 })@@ -82,8 +82,8 @@ describe.each(['', '--'])('parsePenFile — $%sname references (#563)', (prefix)expect(node?.fills[0]?.color).toEqual(BLUE)expect(node?.strokes[0]?.color).toEqual(BLUE)expect(node?.boundVariables).toEqual({- 'fills[0]': variable.id,- 'strokes[0]': variable.id+ 'fills/0/color': variable.id,+ 'strokes/0/color': variable.id})expect(graph.getNode('literal')?.boundVariables).toEqual({})}diff --git a/tests/engine/pen/var-padding.test.ts b/tests/engine/pen/var-padding.test.tsdeleted file mode 100644index b65867820..000000000--- a/tests/engine/pen/var-padding.test.ts+++ /dev/null@@ -1,169 +0,0 @@-import { describe, expect, test } from 'bun:test'--import { applyPadding, isVarRef, type VarContext } from '@open-pencil/pen'-import type { SceneNode, Variable } from '@open-pencil/scene-graph'--/**- * Regression test for open-pencil/open-pencil#201- *- * Design token variables ($--spacing-lg etc.) in padding and gap fields- * must be resolved to numeric values before reaching yoga-layout.- * Without the fix, yoga-layout crashes with:- * "Invalid value $--spacing-lg for setPadding"- */--function makeNode(): SceneNode {- return {- paddingTop: 0,- paddingRight: 0,- paddingBottom: 0,- paddingLeft: 0,- boundVariables: {}- } as SceneNode-}--function makeVarContext(vars: Record<string, number>): VarContext {- const byName = new Map<string, { id: string; variable: Variable }>()- for (const [name, value] of Object.entries(vars)) {- byName.set(name, {- id: name,- variable: {- id: name,- name,- type: 'FLOAT',- collectionId: 'test',- valuesByMode: { default: value },- description: '',- hiddenFromPublishing: false- }- })- }- return {- byName,- activeModeId: 'default',- collectionId: 'test',- modeByThemeName: new Map(),- resolveColor: () => ({ r: 0, g: 0, b: 0, a: 1 }),- resolveNumber(ref: string): number {- const entry = byName.get(ref.replace(/^\$/, ''))- if (!entry) return 0- const val = entry.variable.valuesByMode['default']- return typeof val === 'number' ? val : 0- },- resolveString: () => '',- setActiveTheme: () => undefined- }-}--const ctx = makeVarContext({- '--spacing-sm': 8,- '--spacing-md': 16,- '--spacing-lg': 24-})--describe('applyPadding — variable resolution (#201)', () => {- test('resolves $--spacing-lg variable as single padding value', () => {- const node = makeNode()- applyPadding(node, '$--spacing-lg', ctx)-- expect(node.paddingTop).toBe(24)- expect(node.paddingRight).toBe(24)- expect(node.paddingBottom).toBe(24)- expect(node.paddingLeft).toBe(24)- })-- test('resolves variable references in padding array', () => {- const node = makeNode()- applyPadding(node, ['$--spacing-sm', '$--spacing-lg', '$--spacing-sm', '$--spacing-lg'], ctx)-- expect(node.paddingTop).toBe(8)- expect(node.paddingRight).toBe(24)- expect(node.paddingBottom).toBe(8)- expect(node.paddingLeft).toBe(24)- })-- test('mixed numeric and variable padding array', () => {- const node = makeNode()- applyPadding(node, [10, '$--spacing-lg', 10, '$--spacing-sm'], ctx)-- expect(node.paddingTop).toBe(10)- expect(node.paddingRight).toBe(24)- expect(node.paddingBottom).toBe(10)- expect(node.paddingLeft).toBe(8)- })-- test('numeric padding still works (regression)', () => {- const node = makeNode()- applyPadding(node, [10, 20, 10, 20])-- expect(node.paddingTop).toBe(10)- expect(node.paddingRight).toBe(20)- expect(node.paddingBottom).toBe(10)- expect(node.paddingLeft).toBe(20)- })-- test('single numeric padding still works (regression)', () => {- const node = makeNode()- applyPadding(node, 16)-- expect(node.paddingTop).toBe(16)- expect(node.paddingRight).toBe(16)- expect(node.paddingBottom).toBe(16)- expect(node.paddingLeft).toBe(16)- })-- test('undefined padding is a no-op', () => {- const node = makeNode()- node.paddingTop = 99- applyPadding(node, undefined, ctx)-- expect(node.paddingTop).toBe(99)- })-- test('unresolvable variable falls back to 0', () => {- const node = makeNode()- applyPadding(node, '$--unknown-var', ctx)-- expect(node.paddingTop).toBe(0)- })-})--describe('applyPadding — Pen shorthand (#564)', () => {- test('expands two values as vertical and horizontal pairs', () => {- const node = makeNode()- applyPadding(node, [72, 80])-- expect(node.paddingTop).toBe(72)- expect(node.paddingRight).toBe(80)- expect(node.paddingBottom).toBe(72)- expect(node.paddingLeft).toBe(80)- })-})--describe('isVarRef', () => {- test.each(['$merk-blauw', '$font-tekst', '$color.background', '$x'])(- 'recognizes %s as a variable reference',- (reference) => {- expect(isVarRef(reference)).toBe(true)- }- )-- test('recognizes $--xxx as variable reference', () => {- expect(isVarRef('$--spacing-lg')).toBe(true)- expect(isVarRef('$--color-primary')).toBe(true)- })-- test('rejects non-variable strings', () => {- expect(isVarRef('24')).toBe(false)- expect(isVarRef('spacing-lg')).toBe(false)- expect(isVarRef('')).toBe(false)- expect(isVarRef('$')).toBe(false)- expect(isVarRef('price$')).toBe(false)- })-- test('rejects non-string values', () => {- expect(isVarRef(24)).toBe(false)- expect(isVarRef(undefined)).toBe(false)- expect(isVarRef(null)).toBe(false)- })-})diff --git a/tools/checks/test-homes/engine-baseline.txt b/tools/checks/test-homes/engine-baseline.txtindex 29a2cd3c2..b830a169f 100644--- a/tools/checks/test-homes/engine-baseline.txt+++ b/tools/checks/test-homes/engine-baseline.txt@@ -326,10 +326,6 @@ tests/engine/mcp/tools.test.tstests/engine/mcp/transport/paths.test.tstests/engine/mcp/webmcp/registration.test.tstests/engine/mcp/webmcp/settings.test.ts-tests/engine/pen/file.test.ts-tests/engine/pen/layout.test.ts-tests/engine/pen/var-padding.test.ts-tests/engine/pen/variables.test.tstests/engine/profiler/capture-stack.test.tstests/engine/profiler/draw-call-counter.test.tstests/engine/profiler/frame-stats.test.tsdiff --git a/tools/dev/unit-tests/src/shards.ts b/tools/dev/unit-tests/src/shards.tsindex 2f460019b..3800352a4 100644--- a/tools/dev/unit-tests/src/shards.ts+++ b/tools/dev/unit-tests/src/shards.ts@@ -48,8 +48,7 @@ export const UNIT_TEST_GROUPS = {'packages/design-jsx/tests','packages/dom-css/tests','packages/pen/tests',- 'tests/engine/dom-css',- 'tests/engine/pen'+ 'tests/engine/dom-css'],fig: ['packages/fig/tests',