Skip to content

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

fix(figma-api): keep percent text lengths, take Figma's paints, and report variant values (#1494)

Danila Poyarkov769d210e7c31
diff --git a/changes/1494/breaking.md b/changes/1494/breaking.md
new file mode 100644
index 000000000..861b5744e
--- /dev/null
+++ b/changes/1494/breaking.md
@@ -0,0 +1,2 @@
+- `SceneNode.lineHeight` and `letterSpacing`, and the same style run fields, are `{ value, unit }` objects in pixels or percent; documents and rooms saved with the old numbers are not converted.
+- The plugin API reads and takes paints in Figma's shape, so image paints use `scaleMode`, `rotation`, and `scalingFactor` instead of `imageScaleMode`, and strokes refuse geometry keys such as `weight` or `align`, which belong on the node.
diff --git a/changes/1494/fixed.md b/changes/1494/fixed.md
new file mode 100644
index 000000000..d2e887da9
--- /dev/null
+++ b/changes/1494/fixed.md
@@ -0,0 +1,3 @@
+- Percent line heights and letter spacing stay a percent of the font size, as in Figma, from scripts, `.fig` files, CSS, design JSX, and `.pen` files, and the typography panel shows and edits them in their own unit.
+- Paints scripts set in Figma's shape draw as in Figma: image paints with `scaleMode`, `rotation`, or `scalingFactor` take effect, invalid paints throw Figma's validation messages, and solid paints read back with an RGB `color` and the alpha in `opacity`.
+- An instance's `componentProperties` reports its own variant for VARIANT properties, as in Figma.
diff --git a/packages/core/src/canvas/text/layout/build.ts b/packages/core/src/canvas/text/layout/build.ts
index 825e8e085..ce3576685 100644
--- a/packages/core/src/canvas/text/layout/build.ts
+++ b/packages/core/src/canvas/text/layout/build.ts
@@ -9,6 +9,7 @@ import {
paragraphStyleAt,
textListItems,
textParagraphRanges,
+ lineHeightPixels,
topLevelNumberDigits,
type TextListItem,
type TextParagraphRange
@@ -60,7 +61,8 @@ function sliceStyleRuns(runs: readonly StyleRun[], start: number, end: number):
/** Line heights by paragraph index, `lead` places before the text: each run's, the text's elsewhere. */
function lineHeightRuns(node: ParagraphNode, lead: number): LineHeightRun[] {
- const own = node.lineHeight || null
+ // A percent line height follows the font size of the characters it spaces.
+ const own = (fontSize = node.fontSize) => lineHeightPixels(node.lineHeight, fontSize) || null
const runs: LineHeightRun[] = []
const add = (start: number, end: number, lineHeight: number | null) => {
const last = runs.at(-1)
@@ -70,12 +72,16 @@ function lineHeightRuns(node: ParagraphNode, lead: number): LineHeightRun[] {
}
let position = 0
for (const run of node.styleRuns) {
- if (position < run.start) add(position + lead, run.start + lead, own)
- const lineHeight = run.style.lineHeight !== undefined ? run.style.lineHeight || null : own
+ if (position < run.start) add(position + lead, run.start + lead, own())
+ const runSize = run.style.fontSize ?? node.fontSize
+ const lineHeight =
+ run.style.lineHeight !== undefined
+ ? lineHeightPixels(run.style.lineHeight, runSize) || null
+ : own(runSize)
add(run.start + lead, run.start + run.length + lead, lineHeight)
position = run.start + run.length
}
- if (position < node.text.length) add(position + lead, node.text.length + lead, own)
+ if (position < node.text.length) add(position + lead, node.text.length + lead, own())
return runs
}
diff --git a/packages/core/src/canvas/text/paragraph/index.ts b/packages/core/src/canvas/text/paragraph/index.ts
index da73f0f36..5b0850b16 100644
--- a/packages/core/src/canvas/text/paragraph/index.ts
+++ b/packages/core/src/canvas/text/paragraph/index.ts
@@ -13,6 +13,7 @@ import type {
import type { SceneNode } from '@open-pencil/scene-graph'
import { resolveRGBAForPreview } from '@open-pencil/scene-graph/color'
import { weightToStyle } from '@open-pencil/scene-graph/font-style'
+import { lineHeightPixels, textLengthPixels } from '@open-pencil/scene-graph/text'
import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text/direction'
import {
@@ -50,7 +51,7 @@ export function buildTruncateOpts(
if (node.maxLines != null && node.maxLines > 0) {
opts.maxLines = node.maxLines
} else if (node.height > 0) {
- const lineH = node.lineHeight || baseFontSize * 1.2
+ const lineH = lineHeightPixels(node.lineHeight, baseFontSize) || baseFontSize * 1.2
opts.maxLines = Math.max(1, Math.floor(node.height / lineH))
}
return opts
@@ -170,8 +171,12 @@ function pushStyleRun(
): void {
const ck = r.ck
const style = run.style
- const runLineHeight = style.lineHeight !== undefined ? style.lineHeight : node.lineHeight
const runFontSize = style.fontSize ?? baseFontSize
+ // A percent follows the run's own font size, as in Figma.
+ const runLineHeight = lineHeightPixels(
+ style.lineHeight !== undefined ? style.lineHeight : node.lineHeight,
+ runFontSize
+ )
const runFamily = style.fontFamily ?? (node.fontFamily || DEFAULT_FONT_FAMILY)
const runWeight = style.fontWeight ?? node.fontWeight
const runItalic = style.italic ?? node.italic
@@ -193,7 +198,7 @@ function pushStyleRun(
})
),
fontFeatures: textFontFeatures(style.fontFeatures ?? node.fontFeatures),
- letterSpacing: style.letterSpacing ?? (node.letterSpacing || 0),
+ letterSpacing: textLengthPixels(style.letterSpacing ?? node.letterSpacing, runFontSize),
heightMultiplier: runLineHeight ? runLineHeight / runFontSize : undefined,
halfLeading
})
@@ -272,6 +277,7 @@ export function buildSkParagraph(
const ck = r.ck
const baseColor = color ?? ck.BLACK
const baseFontSize = node.fontSize || DEFAULT_FONT_SIZE
+ const baseLineHeight = lineHeightPixels(node.lineHeight, baseFontSize)
const cjkFallbacks = fontManager.getCJKFallbackFamilies()
const arabicFallbacks = fontManager.getArabicFallbackFamilies()
const textDirection = resolveNodeTextDirection(node)
@@ -312,8 +318,8 @@ export function buildSkParagraph(
})
),
fontFeatures: textFontFeatures(node.fontFeatures),
- letterSpacing: node.letterSpacing || 0,
- heightMultiplier: node.lineHeight ? node.lineHeight / baseFontSize : undefined,
+ letterSpacing: textLengthPixels(node.letterSpacing, baseFontSize),
+ heightMultiplier: baseLineHeight ? baseLineHeight / baseFontSize : undefined,
halfLeading
}
const paraStyle = new ck.ParagraphStyle({
diff --git a/packages/core/src/clipboard.ts b/packages/core/src/clipboard.ts
index 0bc992e5e..63fb2a1c6 100644
--- a/packages/core/src/clipboard.ts
+++ b/packages/core/src/clipboard.ts
@@ -4,6 +4,7 @@ import {
type FigmaClipboardAssetType
} from '@open-pencil/fig/clipboard'
import {
+ figmaLineHeight,
placeSlotContent,
relinkConnectorEnds,
type FigNodeChangeExportRuntime,
@@ -245,10 +246,7 @@ async function writeFigmaClipboardHTML(
if (change.type !== 'TEXT' || !change.guid) continue
const source = sourceByGuid.get(`${change.guid.sessionID}:${change.guid.localID}`)
if (!source) continue
- change.lineHeight = {
- value: source.lineHeight ?? 100,
- units: source.lineHeight ? 'PIXELS' : 'PERCENT'
- }
+ change.lineHeight = figmaLineHeight(source.lineHeight)
}
embedClipboardImages(nodeChanges, blobs, graph.images)
return encodeFigmaClipboard(nodeChanges, blobs, randomInt(), assetType)
diff --git a/packages/core/src/editor/text/path-edit.ts b/packages/core/src/editor/text/path-edit.ts
index dabe8907a..0da3d1469 100644
--- a/packages/core/src/editor/text/path-edit.ts
+++ b/packages/core/src/editor/text/path-edit.ts
@@ -4,6 +4,7 @@ import { encodePathCommandsBlob } from '@open-pencil/fig/node-change'
import type { DerivedTextGlyph, SceneNode, TextPathData } from '@open-pencil/scene-graph'
import { weightToStyle } from '@open-pencil/scene-graph/font-style'
import type { Rect } from '@open-pencil/scene-graph/primitives'
+import { textLengthPixels } from '@open-pencil/scene-graph/text'
import { getGlyphOutlineMetricsSync } from '#core/text/opentype'
import {
@@ -39,7 +40,8 @@ function layOutPathText(
type: PathTextType,
layout: PathTextLayout
): DerivedTextGlyph[] | null {
- const { fontSize, letterSpacing } = type
+ const { fontSize } = type
+ const letterSpacing = textLengthPixels(type.letterSpacing, fontSize)
const metrics = getGlyphOutlineMetricsSync(
type.fontFamily,
weightToStyle(type.fontWeight, type.italic),
@@ -236,7 +238,7 @@ function alignedRun(
if (!old) return all
const shift = alignmentShift(
align,
- runWidth(old, node.letterSpacing),
+ runWidth(old, textLengthPixels(node.letterSpacing, node.fontSize)),
runWidth(metrics, letterSpacing)
)
return { anchor: anchor + (direction * shift) / path.length, count: metrics.length }
diff --git a/packages/core/src/editor/text/session.ts b/packages/core/src/editor/text/session.ts
index 16be762e0..9138b5be6 100644
--- a/packages/core/src/editor/text/session.ts
+++ b/packages/core/src/editor/text/session.ts
@@ -98,8 +98,8 @@ function styleEqual(a: StyleRun['style'], b: StyleRun['style']): boolean {
a.textDecoration === b.textDecoration &&
a.fontSize === b.fontSize &&
a.fontFamily === b.fontFamily &&
- a.letterSpacing === b.letterSpacing &&
- a.lineHeight === b.lineHeight &&
+ isEqual(a.letterSpacing, b.letterSpacing) &&
+ isEqual(a.lineHeight, b.lineHeight) &&
fillsEqual(a.fills ?? [], b.fills ?? [])
)
}
diff --git a/packages/core/src/figma-api/accessors/text/index.ts b/packages/core/src/figma-api/accessors/text/index.ts
index d934e80a8..c6d798d63 100644
--- a/packages/core/src/figma-api/accessors/text/index.ts
+++ b/packages/core/src/figma-api/accessors/text/index.ts
@@ -1,5 +1,4 @@
import type {
- CharacterStyleOverride,
HyperlinkTarget,
SceneNode,
TextCase,
@@ -57,8 +56,7 @@ function characterStyle<T>(
internals: NodeProxyInternals,
field: TextSegmentField,
mixed: symbol,
- changes: (node: SceneNode, value: T) => Partial<SceneNode>,
- sized?: (value: T) => ((fontSize: number) => CharacterStyleOverride) | undefined
+ changes: (node: SceneNode, value: T) => Partial<SceneNode>
) {
return {
get(this: ProxyThis): unknown {
@@ -66,18 +64,11 @@ function characterStyle<T>(
},
set(this: ProxyThis, value: T) {
const node = raw(this, internals)
- updateNode(this, internals, textStyleChanges(node, changes(node, value), sized?.(value)))
+ updateNode(this, internals, textStyleChanges(node, changes(node, value)))
}
}
}
-/** A length given in percent of the font size, which characters of each size resolve. */
-function percentOf(value: unknown): number | null {
- if (!value || typeof value !== 'object') return null
- const length = value as { unit?: unknown; value?: unknown }
- return length.unit === 'PERCENT' && typeof length.value === 'number' ? length.value / 100 : null
-}
-
/** Getter/setter pair for a text property stored verbatim on the node. */
function field<Field extends keyof SceneNode>(internals: NodeProxyInternals, name: Field) {
return {
@@ -127,21 +118,13 @@ export function installTextNodeProxyAccessors(
internals,
'letterSpacing',
mixed,
- (node, value) => ({ letterSpacing: letterSpacingValue(node, value) }),
- (value) => {
- const percent = percentOf(value)
- return percent === null ? undefined : (fontSize) => ({ letterSpacing: percent * fontSize })
- }
+ (_node, value) => ({ letterSpacing: letterSpacingValue(value) })
),
lineHeight: characterStyle<FigmaLineHeight | number | null>(
internals,
'lineHeight',
mixed,
- (node, value) => ({ lineHeight: lineHeightValue(node, value) }),
- (value) => {
- const percent = percentOf(value)
- return percent === null ? undefined : (fontSize) => ({ lineHeight: percent * fontSize })
- }
+ (_node, value) => ({ lineHeight: lineHeightValue(value) })
),
textCase: characterStyle<TextCase>(internals, 'textCase', mixed, (_node, textCase) => ({
textCase
diff --git a/packages/core/src/figma-api/accessors/text/ranges.ts b/packages/core/src/figma-api/accessors/text/ranges.ts
index 70fe769c2..0c96b0688 100644
--- a/packages/core/src/figma-api/accessors/text/ranges.ts
+++ b/packages/core/src/figma-api/accessors/text/ranges.ts
@@ -9,8 +9,10 @@ import type {
TextBindableField,
TextCase,
TextDecoration,
- TextDecorationStyle
+ TextDecorationStyle,
+ TextLength
} from '@open-pencil/scene-graph'
+import { textLengthPixels } from '@open-pencil/scene-graph/text'
import {
assertProxyEditable,
@@ -20,7 +22,6 @@ import {
type NodeProxyInternals,
type ProxyThis
} from '#core/figma-api/accessor-utils'
-import { figmaPaintToFill, type FigmaPaint } from '#core/figma-api/accessors/visual'
import {
fontNameInputStyle,
readVariationSettings,
@@ -30,6 +31,7 @@ import {
type FigmaFontNameInput,
type FigmaVariationSettings
} from '#core/figma-api/fonts'
+import { parseFigmaPaints, type FigmaPaint } from '#core/figma-api/paints'
import {
getRangeIndentation,
getRangeListOptions,
@@ -97,12 +99,17 @@ function numberProblem(value: unknown, at = ''): string | null {
/** A length in pixels for a font size: a percent is of the size of the characters it styles. */
type SizedLength<T> = (fontSize: number) => T
-function lengthFor(value: { unit: 'PIXELS' | 'PERCENT'; value: number }): SizedLength<number> {
- return (fontSize) => (value.unit === 'PERCENT' ? (value.value / 100) * fontSize : value.value)
+function lengthFor(value: { unit: 'PIXELS' | 'PERCENT'; value: number }): TextLength {
+ return { unit: value.unit, value: value.value }
+}
+
+/** `length` in pixels at the size of the characters it styles, for fields kept in pixels. */
+function sized(length: TextLength | null): SizedLength<number | null> {
+ return (fontSize) => length && textLengthPixels(length, fontSize)
}
/** A letter spacing Figma takes: pixels or percent, never automatic. */
-function letterSpacingLength(method: string, value: unknown): SizedLength<number> {
+function letterSpacingLength(method: string, value: unknown): TextLength {
const length = value as Partial<FigmaTextLength & { value: number }> | null
if (!length || typeof length !== 'object') {
throw invalid(method, `Expected object, received ${received(value)}`)
@@ -119,12 +126,12 @@ function letterSpacingLength(method: string, value: unknown): SizedLength<number
}
/** A length that may also be automatic, as line heights and decoration sizes are. */
-function lengthOrAuto(method: string, value: unknown): SizedLength<number | null> {
+function lengthOrAuto(method: string, value: unknown): TextLength | null {
const length = value as Partial<FigmaTextLength & { value: number }> | null
if (!length || typeof length !== 'object') {
throw invalid(method, `Expected object, received ${received(value)}`)
}
- if (length.unit === 'AUTO') return () => null
+ if (length.unit === 'AUTO') return null
if (!LENGTH_UNITS.has(String(length.unit))) {
throw invalid(
method,
@@ -243,9 +250,7 @@ function fillsFromPaints(method: string, value: unknown): CharacterStyleOverride
const problem = paintProblem(paint, index)
if (problem) throw invalid(method, problem)
}
- return (value as FigmaPaint[]).map((paint, index) =>
- figmaPaintToFill(paint, index, method, 'value')
- )
+ return parseFigmaPaints(value, method, 'value')
}
/**
@@ -283,7 +288,7 @@ function decorationColorFills(method: string, value: unknown): Fill[] {
// A solid paint whose channels are out of range fails on them alone.
const problem = solidPaintProblem(color as { color?: unknown; opacity?: unknown }, '.value')
if (problem) throw invalid(method, problem, 'textDecorationColor')
- return [figmaPaintToFill(color as FigmaPaint)]
+ return parseFigmaPaints([color], method, 'textDecorationColor')
}
const paintIssues =
issues.length === 1
@@ -344,14 +349,13 @@ const RANGE_SETTERS: Record<string, RangeSetter> = {
setRangeFills: (method, _node, _start, _end, value) => ({
fills: fillsFromPaints(method, value)
}),
- setRangeLetterSpacing: (method, _node, _start, _end, value) => {
- const length = letterSpacingLength(method, value)
- return (fontSize) => ({ letterSpacing: length(fontSize) })
- },
- setRangeLineHeight: (method, _node, _start, _end, value) => {
- const length = lengthOrAuto(method, value)
- return (fontSize) => ({ lineHeight: length(fontSize) })
- },
+ // A percent stays a percent, following the size of the characters it styles, as in Figma.
+ setRangeLetterSpacing: (method, _node, _start, _end, value) => ({
+ letterSpacing: letterSpacingLength(method, value)
+ }),
+ setRangeLineHeight: (method, _node, _start, _end, value) => ({
+ lineHeight: lengthOrAuto(method, value)
+ }),
setRangeTextDecoration: (method, _node, _start, _end, value) => ({
textDecoration: enumValue(method, value, DECORATIONS)
}),
@@ -359,11 +363,11 @@ const RANGE_SETTERS: Record<string, RangeSetter> = {
textDecorationStyle: enumValue(method, value, DECORATION_STYLES)
})),
setRangeTextDecorationOffset: underlineStyle('offset', (method, value) => {
- const length = lengthOrAuto(method, value)
+ const length = sized(lengthOrAuto(method, value))
return (fontSize) => ({ textUnderlineOffset: length(fontSize) })
}),
setRangeTextDecorationThickness: underlineStyle('thickness', (method, value) => {
- const length = lengthOrAuto(method, value)
+ const length = sized(lengthOrAuto(method, value))
return (fontSize) => ({ textDecorationThickness: length(fontSize) })
}),
setRangeTextDecorationColor: underlineStyle('color', (method, value) => ({
@@ -428,7 +432,7 @@ export interface TextRangeMethods {
getRangeFontName: RangeGetter<FigmaFontName>
setRangeFontName: RangeSetterMethod<FigmaFontNameInput>
getRangeFontWeight: RangeGetter<number>
- getRangeFills: RangeGetter<Fill[]>
+ getRangeFills: RangeGetter<FigmaPaint[]>
setRangeFills: RangeSetterMethod<FigmaPaint[]>
getRangeLetterSpacing: RangeGetter<FigmaLetterSpacing>
setRangeLetterSpacing: RangeSetterMethod<FigmaLetterSpacing>
diff --git a/packages/core/src/figma-api/accessors/vector.ts b/packages/core/src/figma-api/accessors/vector.ts
index 3f58c6eae..f12b588ed 100644
--- a/packages/core/src/figma-api/accessors/vector.ts
+++ b/packages/core/src/figma-api/accessors/vector.ts
@@ -6,7 +6,6 @@ import type {
VectorVertex,
WindingRule
} from '@open-pencil/scene-graph'
-import { copyFills } from '@open-pencil/scene-graph/copy'
import { parsePluginVectorPath } from '@open-pencil/scene-graph/parse-path'
import {
mergeVectorNetworks,
@@ -23,8 +22,7 @@ import {
type NodeProxyInternals,
type ProxyThis
} from '#core/figma-api/accessor-utils'
-import { figmaPaintToFill, type FigmaPaint } from '#core/figma-api/accessors/visual'
-import { toFigmaPaint } from '#core/figma-api/paints'
+import { parseFigmaPaints, toFigmaPaint, type FigmaPaint } from '#core/figma-api/paints'
import { geometryBlobToSVGPath, vectorNetworkToSVGPaths } from '#core/io/formats/svg/paths'
import { computeAccurateBounds } from '#core/vector/curve-math'
import { regenerateFillGeometry } from '#core/vector/fill-geometry'
@@ -116,9 +114,7 @@ function geometryForRegions(regions: readonly FigmaVectorRegion[]): GeometryPath
return regions.map((region) => ({
windingRule: region.windingRule,
commandsBlob: new Uint8Array(),
- fills: (region.fills ?? []).map((paint, index) =>
- figmaPaintToFill(paint, index, 'set_vectorNetwork', 'vectorNetwork')
- ),
+ fills: parseFigmaPaints(region.fills ?? [], 'set_vectorNetwork', 'vectorNetwork'),
fillStyleId: region.fillStyleId ?? ''
}))
}
@@ -248,7 +244,7 @@ function readVectorNetwork(target: ProxyThis, internals: NodeProxyInternals): Fi
windingRule: region.windingRule,
loops: Object.freeze(region.loops.map((loop) => Object.freeze([...loop]))),
fillStyleId: geometry?.fillStyleId ?? '',
- fills: Object.freeze(copyFills(geometry?.fills ?? []).map(toFigmaPaint))
+ fills: Object.freeze((geometry?.fills ?? []).map((paint) => toFigmaPaint(paint)))
})
})
return Object.freeze({
diff --git a/packages/core/src/figma-api/accessors/visual.ts b/packages/core/src/figma-api/accessors/visual.ts
index 4883ea8cc..7c7842b01 100644
--- a/packages/core/src/figma-api/accessors/visual.ts
+++ b/packages/core/src/figma-api/accessors/visual.ts
@@ -1,8 +1,5 @@
-import type { Fill, GradientStop, SceneGraph, SceneNode, Stroke } from '@open-pencil/scene-graph'
-import { normalizeColor } from '@open-pencil/scene-graph/color'
-import { copyFills, copyStrokes } from '@open-pencil/scene-graph/copy'
+import type { SceneGraph, SceneNode, Stroke } from '@open-pencil/scene-graph'
import { newStrokeGeometry } from '@open-pencil/scene-graph/node-defaults'
-import type { Color } from '@open-pencil/scene-graph/primitives'
import { resolvedPaintBindings } from '@open-pencil/scene-graph/variables'
import {
@@ -14,14 +11,9 @@ import {
type ProxyThis
} from '#core/figma-api/accessor-utils'
import { parseFigmaEffects, toFigmaEffect, type FigmaEffect } from '#core/figma-api/effects'
-import { sceneTransforms, toFigmaPaint, type WithFigmaTransforms } from '#core/figma-api/paints'
+import { parseFigmaPaints, toFigmaPaint, type FigmaPaint } from '#core/figma-api/paints'
import { getTextStyle } from '#core/figma-api/text/style'
-import {
- paintBindings,
- setPaintBindings,
- withPaintBinding
-} from '#core/figma-api/variables/bindings'
-import type { FigmaVariableAlias } from '#core/figma-api/variables/values'
+import { paintBindings, setPaintBindings } from '#core/figma-api/variables/bindings'
import { textStyleChanges } from '#core/text/character-style'
function styleReference(
@@ -50,73 +42,25 @@ function styleReference(
}
}
-/** Figma treats a paint's `opacity` and `visible` as optional, defaulting to 1 and `true`. */
-function paintDefaults(paint: Partial<Pick<Fill, 'opacity' | 'visible'>>) {
- return { opacity: paint.opacity ?? 1, visible: paint.visible ?? true }
-}
-
-/** A colour as Figma's plugin API takes it, RGB with an optional alpha. */
-type FigmaColor = Omit<Color, 'a'> & Partial<Pick<Color, 'a'>>
-
-/**
- * A paint as Figma's plugin API takes it: RGB colours, optional opacity and visibility, transforms
- * as two rows of three, and the variable its colour is bound to.
- */
-export type FigmaPaint = WithFigmaTransforms<
- Omit<Fill, 'color' | 'opacity' | 'visible' | 'gradientStops'>
-> &
- Partial<Pick<Fill, 'opacity' | 'visible'>> & {
- color?: FigmaColor
- gradientStops?: Array<Omit<GradientStop, 'color'> & { color: FigmaColor }>
- boundVariables?: { color?: FigmaVariableAlias }
- }
-
-/** The scene paint for a Figma paint at `index` in the list a script passes to `method`. */
-export function figmaPaintToFill(
- paint: FigmaPaint,
- index = 0,
- method = 'set_fills',
- property = 'fills'
-): Fill {
- const { boundVariables: _bound, gradientTransform: _g, imageTransform: _i, ...fill } = paint
- return {
- ...fill,
- ...paintDefaults(fill),
- ...sceneTransforms(paint, index, method, property),
- color: normalizeColor(fill.color),
- gradientStops: fill.gradientStops?.map((stop) => ({
- ...stop,
- color: normalizeColor(stop.color)
- }))
- }
-}
-
/**
- * Copies of `node`'s fills as Figma's plugin API reads them: bound colours resolved and named,
- * transforms as two rows of three.
+ * `node`'s fills as Figma's plugin API reads them, bound colours resolved and carrying the
+ * variable they are bound to.
*/
-export function figmaFills(sceneGraph: SceneGraph, node: SceneNode): WithFigmaTransforms<Fill>[] {
+export function figmaFills(sceneGraph: SceneGraph, node: SceneNode): FigmaPaint[] {
const bound = paintBindings(node, 'fills')
const fills = bound.size
? (resolvedPaintBindings(sceneGraph, node).fills ?? node.fills)
: node.fills
- return copyFills(fills).map((fill, index) =>
- toFigmaPaint(withPaintBinding(fill, bound.get(index)))
- )
+ return fills.map((fill, index) => toFigmaPaint(fill, bound.get(index)))
}
-/** Copies of `node`'s strokes as Figma's plugin API reads them, as {@link figmaFills} reads fills. */
-export function figmaStrokes(
- sceneGraph: SceneGraph,
- node: SceneNode
-): WithFigmaTransforms<Stroke>[] {
+/** `node`'s strokes as Figma's plugin API reads them, as {@link figmaFills} reads fills. */
+export function figmaStrokes(sceneGraph: SceneGraph, node: SceneNode): FigmaPaint[] {
const bound = paintBindings(node, 'strokes')
const strokes = bound.size
? (resolvedPaintBindings(sceneGraph, node).strokes ?? node.strokes)
: node.strokes
- return copyStrokes(strokes).map((stroke, index) =>
- toFigmaPaint(withPaintBinding(stroke, bound.get(index)))
- )
+ return strokes.map((stroke, index) => toFigmaPaint(stroke, bound.get(index)))
}
export function installVisualNodeProxyAccessors(
@@ -127,18 +71,16 @@ export function installVisualNodeProxyAccessors(
Object.defineProperties(prototype, {
fills: {
// Text reads mixed while its characters are filled differently, and setting it fills them all.
- get(this: ProxyThis): readonly WithFigmaTransforms<Fill>[] | symbol {
+ get(this: ProxyThis): readonly FigmaPaint[] | symbol {
const node = raw(this, internals)
if (node.type !== 'TEXT') return Object.freeze(figmaFills(graph(this, internals), node))
const fills = getTextStyle(node, 'fills', mixed)
// Text styles read for scripts already give Figma's paints.
- return typeof fills === 'symbol'
- ? fills
- : Object.freeze(fills as WithFigmaTransforms<Fill>[])
+ return typeof fills === 'symbol' ? fills : Object.freeze(fills as FigmaPaint[])
},
set(this: ProxyThis, value: readonly FigmaPaint[]) {
const node = raw(this, internals)
- const fills = value.map((paint, index) => figmaPaintToFill(paint, index))
+ const fills = parseFigmaPaints(value)
updateNode(
this,
internals,
@@ -148,40 +90,20 @@ export function installVisualNodeProxyAccessors(
}
},
strokes: {
- get(this: ProxyThis): readonly WithFigmaTransforms<Stroke>[] {
+ get(this: ProxyThis): readonly FigmaPaint[] {
const owner = raw(strokeOwner(this, internals), internals)
return Object.freeze(figmaStrokes(graph(this, internals), owner))
},
// Figma paints carry no geometry; a stroke takes the node's weight and alignment, which
// outlast its strokes.
- set(
- this: ProxyThis,
- value: readonly (WithFigmaTransforms<Omit<Stroke, 'weight' | 'align'>> &
- Partial<Pick<Stroke, 'weight' | 'align'>> & {
- boundVariables?: { color?: FigmaVariableAlias }
- })[]
- ) {
+ set(this: ProxyThis, value: readonly FigmaPaint[]) {
const owner = strokeOwner(this, internals)
const geometry = newStrokeGeometry(raw(owner, internals))
- // The script keeps its paint objects; the node gets its own copies of every nested value.
- const strokes = copyStrokes(
- value.map((paint, index) => {
- const {
- boundVariables: _bound,
- gradientTransform: _g,
- imageTransform: _i,
- ...stroke
- } = paint
- return {
- ...stroke,
- ...paintDefaults(stroke),
- ...sceneTransforms(paint, index, 'set_strokes', 'strokes'),
- weight: stroke.weight ?? geometry.weight,
- align: stroke.align ?? geometry.align,
- color: normalizeColor(stroke.color)
- }
- })
- )
+ const strokes = parseFigmaPaints(value, 'set_strokes', 'strokes').map((paint): Stroke => ({
+ ...paint,
+ weight: geometry.weight,
+ align: geometry.align
+ }))
const kept = newStrokeGeometry({
strokes,
strokeWeight: geometry.weight,
diff --git a/packages/core/src/figma-api/compatibility.ts b/packages/core/src/figma-api/compatibility.ts
index ee87ad262..91a9a4d01 100644
--- a/packages/core/src/figma-api/compatibility.ts
+++ b/packages/core/src/figma-api/compatibility.ts
@@ -7,6 +7,7 @@ import type {
FigmaInstanceNode,
FigmaSlotNode
} from './node-types'
+import type { OpenPencilPaint } from './paints'
import type { FigmaNodeProxy } from './proxy'
import type {
FIGMA_API_HOST_MEMBERS,
@@ -125,6 +126,24 @@ const _slotSurfaceMatch: SlotSurfaceMatch = true
type EffectShapeMatch = Expect<Extends<FigmaNodeProxy['effects'][number], Effect>>
const _effectShapeMatch: EffectShapeMatch = true
+// `Paint` here is Figma's plugin-typings union. `fills`, `strokes`, and `backgrounds` share one
+// paint type: every paint they read is one of Figma's, apart from the noise and custom paints
+// OpenPencil models and Figma has no type for, and they take every paint Figma's types allow but
+// for the linear burn and dodge blend modes, which OpenPencil does not model.
+type ReadPaint = Exclude<Exclude<FigmaNodeProxy['fills'], symbol>[number], OpenPencilPaint>
+type WithoutLinearBlends<T> = T extends unknown
+ ? Omit<T, 'blendMode'> & { blendMode?: Exclude<BlendMode, 'LINEAR_BURN' | 'LINEAR_DODGE'> }
+ : never
+type PaintShapeMatch = Expect<Extends<ReadPaint, Paint>>
+const _paintShapeMatch: PaintShapeMatch = true
+type PaintArgumentMatch = Expect<
+ Extends<
+ WithoutLinearBlends<SolidPaint | GradientPaint | ImagePaint | VideoPaint | PatternPaint>,
+ ReadPaint
+ >
+>
+const _paintArgumentMatch: PaintArgumentMatch = true
+
type TextListKeys =
| 'setRangeListOptions'
| 'setRangeIndentation'
@@ -153,7 +172,7 @@ type TextListSurfaceMatch = Expect<
const _textListSurfaceMatch: TextListSurfaceMatch = true
// Figma's mixed values are its own `figma.mixed` unique symbol; ours are a plain symbol. Fills
-// and decoration colours read and take the paints OpenPencil models, as `fills` does, and Figma
+// and decoration colours can read OpenPencil's noise and custom paints, as `fills` can, and Figma
// types OpenType features as every feature while it returns only those set, so they stay out.
type WithoutMixed<T> = T extends (...args: infer A) => infer R
? (...args: A) => Exclude<R, symbol>
diff --git a/packages/core/src/figma-api/components.ts b/packages/core/src/figma-api/components.ts
index d1495868b..cb894b5e1 100644
--- a/packages/core/src/figma-api/components.ts
+++ b/packages/core/src/figma-api/components.ts
@@ -188,9 +188,16 @@ function componentProperties(
): FigmaComponentProperties {
const node = raw(target, internals)
if (node.type !== 'INSTANCE') return {}
+ // A variant value is the instance's own variant, as Figma reports it, not an assignment.
+ const variant = variantPropertiesOf(graph(target, internals), node)
return Object.fromEntries(
sharedComponentPropertyDefinitions(graph(target, internals), node).map((definition) => {
- const value = node.componentPropertyAssignments[definition.id] ?? definition.defaultValue
+ const own =
+ definition.type === 'VARIANT' && variant && Object.hasOwn(variant, definition.name)
+ ? variant[definition.name]
+ : undefined
+ const assigned = node.componentPropertyAssignments[definition.id] ?? definition.defaultValue
+ const value = own ?? assigned
return [
propertyName(definition),
{
diff --git a/packages/core/src/figma-api/effects.ts b/packages/core/src/figma-api/effects.ts
index 36ac75334..9efa0d9e5 100644
--- a/packages/core/src/figma-api/effects.ts
+++ b/packages/core/src/figma-api/effects.ts
@@ -24,7 +24,7 @@ const BLEND_MODE_KEYS = {
PASS_THROUGH: true
} satisfies Record<BlendMode, true>
-const BLEND_MODES = Object.keys(BLEND_MODE_KEYS) as BlendMode[]
+export const BLEND_MODES = Object.keys(BLEND_MODE_KEYS) as BlendMode[]
/** Effect kinds Figma's plugin API accepts that OpenPencil does not model yet. */
const UNSUPPORTED_EFFECT_TYPES = new Set(['NOISE', 'TEXTURE', 'GLASS', 'SHADER'])
@@ -70,8 +70,9 @@ const effectsSchema = v.array(effectSchema)
/** An effect as Figma's plugin API reads and writes it (`Effect` in `@figma/plugin-typings`). */
export type FigmaEffect = v.InferOutput<typeof effectSchema>
-function issuePath(issue: v.BaseIssue<unknown>): string {
- return (issue.path ?? [])
+/** Figma's spelling of a path into a value: `[0].color.r`. */
+export function issuePath(path: readonly v.IssuePathItem[] | undefined): string {
+ return (path ?? [])
.map((item) => (typeof item.key === 'number' ? `[${item.key}]` : `.${String(item.key)}`))
.join('')
}
@@ -101,7 +102,7 @@ export function parseFigmaEffects(value: unknown): Effect[] {
if (!result.success) {
const [issue] = result.issues
throw new Error(
- `Property "effects" failed validation: ${issue.message} at ${issuePath(issue) || 'effects'}`
+ `Property "effects" failed validation: ${issue.message} at ${issuePath(issue.path) || 'effects'}`
)
}
return result.output.map(toSceneEffect)
diff --git a/packages/core/src/figma-api/paints.ts b/packages/core/src/figma-api/paints.ts
index 30150000f..73dbcab28 100644
--- a/packages/core/src/figma-api/paints.ts
+++ b/packages/core/src/figma-api/paints.ts
@@ -1,22 +1,264 @@
-import type { Fill, GradientTransform } from '@open-pencil/scene-graph'
+import * as v from 'valibot'
+
+import type { BlendMode, Fill, GradientTransform, ImageScaleMode } from '@open-pencil/scene-graph'
+import { BLACK } from '@open-pencil/scene-graph/constants'
import {
gradientTransformRows,
IDENTITY_GRADIENT_TRANSFORM
} from '@open-pencil/scene-graph/gradient'
+import type { Color, Vector } from '@open-pencil/scene-graph/primitives'
+import { invalid, received } from './accessors/text/messages'
+import { BLEND_MODES, issuePath } from './effects'
import type { FigmaTransform } from './types'
+import { variableAlias, type FigmaVariableAlias } from './variables/values'
+
+/** The paint types Figma's `fills` and `strokes` take, in the order its message lists them. */
+const PAINT_TYPES = [
+ 'SOLID',
+ 'SHADER',
+ 'GRADIENT_LINEAR',
+ 'GRADIENT_RADIAL',
+ 'GRADIENT_ANGULAR',
+ 'GRADIENT_DIAMOND',
+ 'IMAGE',
+ 'VIDEO'
+] as const
+
+/** Paint types Figma's plugin API takes that OpenPencil does not model yet. */
+const UNSUPPORTED_PAINT_TYPES = new Set(['SHADER'])
+
+const GRADIENT_TYPES = [
+ 'GRADIENT_LINEAR',
+ 'GRADIENT_RADIAL',
+ 'GRADIENT_ANGULAR',
+ 'GRADIENT_DIAMOND'
+] as const
+
+const SCALE_MODES = ['FILL', 'FIT', 'CROP', 'TILE'] as const satisfies readonly ImageScaleMode[]
+
+type ImageFilters = Record<
+ 'exposure' | 'contrast' | 'saturation' | 'temperature' | 'tint' | 'highlights' | 'shadows',
+ number
+>
+
+/** OpenPencil keeps no image filters; Figma reads every slider at 0 until one moves. */
+const NO_FILTERS: ImageFilters = {
+ exposure: 0,
+ contrast: 0,
+ saturation: 0,
+ temperature: 0,
+ tint: 0,
+ highlights: 0,
+ shadows: 0
+}
+
+/** Figma's videos are named by the SHA-1 of their bytes. */
+const SHA1_HASH = /^[0-9a-f]{40}$/i
+
+/** Figma's message for a value that is none of `options`. */
+function invalidOption(options: readonly string[]): string {
+ return `Invalid option: expected one of ${options.map((option) => `"${option}"`).join('|')}`
+}
+
+const unitSchema = v.pipe(v.number(), v.minValue(0), v.maxValue(1))
+const aliasSchema = v.object({ type: v.literal('VARIABLE_ALIAS'), id: v.string() })
+const colorBindingSchema = v.optional(v.strictObject({ color: v.optional(aliasSchema) }))
+
+const paintEntries = {
+ visible: v.optional(v.boolean()),
+ opacity: v.optional(unitSchema),
+ blendMode: v.optional(v.picklist(BLEND_MODES, invalidOption(BLEND_MODES)))
+}
+
+// Figma checks a transform's rows itself, after the paint's other fields.
+const transformSchema = v.optional(v.unknown())
+
+// Image filter sliders run from -1 to 1.
+const filterSchema = v.optional(v.pipe(v.number(), v.minValue(-1), v.maxValue(1)))
+
+const mediaEntries = {
+ scaleMode: v.picklist(SCALE_MODES, invalidOption(SCALE_MODES)),
+ scalingFactor: v.optional(v.number()),
+ rotation: v.optional(v.number()),
+ filters: v.optional(
+ v.strictObject({
+ exposure: filterSchema,
+ contrast: filterSchema,
+ saturation: filterSchema,
+ temperature: filterSchema,
+ tint: filterSchema,
+ highlights: filterSchema,
+ shadows: filterSchema
+ })
+ ),
+ ...paintEntries
+}
+
+const paintSchema = v.variant('type', [
+ v.strictObject({
+ type: v.literal('SOLID'),
+ // A solid colour is RGB; Figma takes an alpha as the paint's opacity.
+ color: v.strictObject({
+ r: unitSchema,
+ g: unitSchema,
+ b: unitSchema,
+ a: v.optional(unitSchema)
+ }),
+ ...paintEntries,
+ boundVariables: colorBindingSchema
+ }),
+ v.strictObject({
+ type: v.picklist(GRADIENT_TYPES),
+ gradientTransform: transformSchema,
+ gradientStops: v.array(
+ v.strictObject({
+ position: unitSchema,
+ color: v.strictObject({ r: unitSchema, g: unitSchema, b: unitSchema, a: unitSchema }),
+ boundVariables: colorBindingSchema
+ })
+ ),
+ ...paintEntries
+ }),
+ v.strictObject({
+ type: v.literal('IMAGE'),
+ imageHash: v.nullable(v.string()),
+ imageTransform: transformSchema,
+ ...mediaEntries
+ }),
+ v.strictObject({
+ type: v.literal('VIDEO'),
+ videoHash: v.nullable(v.string()),
+ videoTransform: transformSchema,
+ ...mediaEntries
+ })
+])
-/** The transforms a paint carries: gradients map the layer onto gradient space, images crop. */
-const TRANSFORM_FIELDS = ['gradientTransform', 'imageTransform'] as const
+type ParsedPaint = v.InferOutput<typeof paintSchema>
-type TransformField = (typeof TRANSFORM_FIELDS)[number]
+type PaintBase = {
+ readonly visible?: boolean
+ readonly opacity?: number
+ readonly blendMode?: BlendMode
+}
+
+type ColorBinding = { readonly boundVariables?: { readonly color?: FigmaVariableAlias } }
+
+type MediaFields = PaintBase & {
+ readonly scaleMode: ImageScaleMode
+ readonly scalingFactor?: number
+ readonly rotation?: number
+ readonly filters?: Partial<ImageFilters>
+}
+
+/** A paint OpenPencil models that Figma's plugin API has no type for, read as the model holds it. */
+export type OpenPencilPaint = Omit<Fill, 'type' | 'gradientTransform' | 'imageTransform'> & {
+ readonly type: 'NOISE' | 'CUSTOM'
+ readonly gradientTransform?: FigmaTransform
+ readonly imageTransform?: FigmaTransform
+}
+
+/**
+ * A paint as Figma's plugin API gives and takes it (`Paint` in `@figma/plugin-typings`): a solid
+ * colour is RGB with its alpha in the opacity, transforms are two rows of three, and an image or
+ * video names its scale mode, rotation, and tile scaling as Figma does. Like Figma, the setters
+ * refuse a pattern; OpenPencil's own paints read as {@link OpenPencilPaint}.
+ */
+export type FigmaPaint =
+ | (PaintBase &
+ ColorBinding & {
+ readonly type: 'SOLID'
+ readonly color: Omit<Color, 'a'>
+ })
+ | (PaintBase & {
+ readonly type: (typeof GRADIENT_TYPES)[number]
+ readonly gradientTransform: FigmaTransform
+ readonly gradientStops: ReadonlyArray<
+ ColorBinding & { readonly position: number; readonly color: Color }
+ >
+ })
+ | (MediaFields & {
+ readonly type: 'IMAGE'
+ readonly imageHash: string | null
+ readonly imageTransform?: FigmaTransform
+ })
+ | (MediaFields & {
+ readonly type: 'VIDEO'
+ readonly videoHash: string | null
+ readonly videoTransform?: FigmaTransform
+ })
+ | (PaintBase & {
+ readonly type: 'PATTERN'
+ readonly sourceNodeId: string
+ readonly tileType: NonNullable<Fill['patternTileType']>
+ readonly scalingFactor: number
+ readonly spacing: Vector
+ readonly horizontalAlignment: NonNullable<Fill['horizontalAlignment']>
+ })
+ | OpenPencilPaint
+
+type ReadBase = Required<PaintBase>
+
+/** What Figma calls the value each Valibot schema expects. */
+const EXPECTED: Partial<Record<string, string>> = {
+ strict_object: 'object',
+ object: 'object',
+ variant: 'object',
+ array: 'array',
+ number: 'number',
+ string: 'string',
+ boolean: 'boolean'
+}
+
+/** Where Figma reports an issue: a paint itself by its index, a field by its path. */
+function where(path: readonly v.IssuePathItem[]): string {
+ if (path.length === 0) return ''
+ const [first] = path
+ if (path.length === 1 && typeof first.key === 'number') return ` at index ${first.key}`
+ return ` at ${issuePath(path)}`
+}
+
+/** One of Figma's lines for a Valibot issue, as its paint validation words it. */
+function issueProblem(issue: v.BaseIssue<unknown>): string {
+ const path = issue.path ?? []
+ const last = path.at(-1)
+ if (last?.origin === 'key') {
+ if (issue.expected === 'never') {
+ return `Unrecognized key: "${String(last.key)}"${where(path.slice(0, -1))}`
+ }
+ // Figma checks a missing field as undefined, which a choice refuses as an option.
+ const problem = last.key === 'scaleMode' ? invalidOption(SCALE_MODES) : 'Required value missing'
+ return `${problem}${where(path)}`
+ }
+ if (issue.type === 'picklist') return `${issue.message}${where(path)}`
+ if (issue.type === 'max_value') {
+ return `Too big: expected number to be <=${String(issue.requirement)}${where(path)}`
+ }
+ if (issue.type === 'min_value') {
+ return `Too small: expected number to be >=${String(issue.requirement)}${where(path)}`
+ }
+ if (issue.input === undefined) return `Required value missing${where(path)}`
+ const expected = EXPECTED[issue.type] ?? issue.expected ?? issue.type
+ return `Expected ${expected}, received ${received(issue.input)}${where(path)}`
+}
-/** A paint as Figma's plugin API gives and takes it, its transforms as two rows of three. */
-export type WithFigmaTransforms<T> = Omit<T, TransformField> & {
- gradientTransform?: FigmaTransform
- imageTransform?: FigmaTransform
+/** Figma's complaint about a paint type it does not take, or OpenPencil does not model. */
+function typeProblem(value: readonly unknown[]): string | null {
+ for (const [index, paint] of value.entries()) {
+ if (!v.is(v.object({ type: v.unknown() }), paint)) continue
+ const { type } = paint
+ if (typeof type === 'string' && UNSUPPORTED_PAINT_TYPES.has(type)) {
+ return `${type} paints are not supported at [${index}].type`
+ }
+ if (!(PAINT_TYPES as readonly unknown[]).includes(type)) {
+ return `Expected [${index}].type to be one of the following: ${PAINT_TYPES.join(', ')}`
+ }
+ }
+ return null
}
+type TransformField = 'gradientTransform' | 'imageTransform' | 'videoTransform'
+
function isRow(value: unknown): value is [number, number, number] {
return (
Array.isArray(value) &&
@@ -35,49 +277,167 @@ function transformProblem(value: unknown): string | null {
return value.every(isRow) ? null : 'Expected array of 3 numbers'
}
-/** Whether Figma requires `field` on a paint of `type`, as it does a gradient's transform. */
-function requires(type: Fill['type'], field: TransformField): boolean {
- return field === 'gradientTransform' && type.startsWith('GRADIENT_')
-}
+/** Where a paint at `index` in the list a script passes to `method` sets `property`. */
+type PaintSite = { index: number; method: string; property: string }
/**
- * The scene transforms of a paint a script passes to `method`, at `index` in `property`. Figma
+ * The scene transform `value` a paint holds in `field`, which Figma requires of a gradient. Figma
* takes only two rows of three numbers and throws the way its `fills` and `strokes` setters do.
*/
-export function sceneTransforms(
- paint: { type: Fill['type'] } & Partial<Record<TransformField, unknown>>,
- index: number,
- method = 'set_fills',
- property = 'fills'
-): Partial<Record<TransformField, GradientTransform>> {
- const transforms: Partial<Record<TransformField, GradientTransform>> = {}
- for (const field of TRANSFORM_FIELDS) {
- const value = paint[field]
- if (value === undefined && !requires(paint.type, field)) continue
- const problem = transformProblem(value)
- if (problem) {
- const at = `[${index}].${field}`
- throw new Error(
- `in ${method}: Property "${property}" failed validation: Expected ${at} to be one of ` +
- `the following, but none matched:\n ${problem} at ${at}`
- )
+function sceneTransform(
+ value: unknown,
+ field: TransformField,
+ site: PaintSite
+): GradientTransform | undefined {
+ if (value === undefined && field !== 'gradientTransform') return undefined
+ const problem = transformProblem(value)
+ if (problem) {
+ const at = `[${site.index}].${field}`
+ throw invalid(
+ site.method,
+ `Expected ${at} to be one of the following, but none matched:\n ${problem} at ${at}`,
+ site.property
+ )
+ }
+ const [[m00, m01, m02], [m10, m11, m12]] = value as FigmaTransform
+ return { m00, m01, m02, m10, m11, m12 }
+}
+
+function sceneFill(paint: ParsedPaint, site: PaintSite): Fill {
+ const base = {
+ visible: paint.visible ?? true,
+ opacity: paint.opacity ?? 1,
+ ...(paint.blendMode && { blendMode: paint.blendMode })
+ }
+ if (paint.type === 'SOLID') {
+ const { r, g, b, a } = paint.color
+ // Figma keeps a solid paint's alpha in its opacity, so a colour's alpha stands in for an
+ // opacity left out, as `figma.util.solidPaint` gives it.
+ return { type: 'SOLID', ...base, color: { r, g, b, a: 1 }, opacity: paint.opacity ?? a ?? 1 }
+ }
+ if (paint.type === 'IMAGE' || paint.type === 'VIDEO') {
+ const [hash, imageTransform] =
+ paint.type === 'IMAGE'
+ ? [paint.imageHash, sceneTransform(paint.imageTransform, 'imageTransform', site)]
+ : [paint.videoHash, sceneTransform(paint.videoTransform, 'videoTransform', site)]
+ return {
+ type: paint.type,
+ ...base,
+ color: { ...BLACK },
+ imageScaleMode: paint.scaleMode,
+ ...(hash !== null && { imageHash: hash }),
+ ...(imageTransform && { imageTransform }),
+ ...(paint.rotation !== undefined && { imageRotation: paint.rotation }),
+ ...(paint.scalingFactor !== undefined && { scale: paint.scalingFactor })
}
- const [[m00, m01, m02], [m10, m11, m12]] = value as FigmaTransform
- transforms[field] = { m00, m01, m02, m10, m11, m12 }
}
- return transforms
+ return {
+ type: paint.type,
+ ...base,
+ color: { ...BLACK },
+ gradientStops: paint.gradientStops.map(({ position, color }) => ({
+ position,
+ color: { ...color }
+ })),
+ gradientTransform: sceneTransform(paint.gradientTransform, 'gradientTransform', site)
+ }
}
/**
- * `paint` with its transforms as Figma gives them: two rows of three. An image paint reports the
- * identity when it has none, as Figma's do outside crop mode.
+ * Check `value` against Figma's paint shapes and convert it to scene paints. Throws Figma's
+ * message for `method` setting `property`, listing every problem on its own line.
*/
-export function toFigmaPaint<T extends Fill>(paint: T): WithFigmaTransforms<T> {
+export function parseFigmaPaints(value: unknown, method = 'set_fills', property = 'fills'): Fill[] {
+ if (!Array.isArray(value)) {
+ throw invalid(method, `Expected array, received ${received(value)}`, property)
+ }
+ const unsupported = typeProblem(value)
+ if (unsupported) throw invalid(method, unsupported, property)
+ const result = v.safeParse(v.array(paintSchema), value)
+ if (!result.success) throw invalid(method, result.issues.map(issueProblem).join('\n'), property)
+ for (const paint of result.output) {
+ if (paint.type === 'VIDEO' && paint.videoHash !== null && !SHA1_HASH.test(paint.videoHash)) {
+ throw new Error(`in ${method}: Invalid SHA1 hash`)
+ }
+ }
+ return result.output.map((paint, index) => sceneFill(paint, { index, method, property }))
+}
+
+function rows(transform: GradientTransform | undefined): FigmaTransform {
+ return gradientTransformRows(transform ?? IDENTITY_GRADIENT_TRANSFORM)
+}
+
+/**
+ * An image or video paint as Figma reads it. Outside crop mode it reads the identity transform, a
+ * scaling factor of 1 unless tiled, and its rotation; a crop holds its own rotation, so it reads
+ * none.
+ */
+function figmaMediaPaint(paint: Fill, type: 'IMAGE' | 'VIDEO', base: ReadBase): FigmaPaint {
+ const scaleMode = paint.imageScaleMode ?? 'FILL'
+ const crop = scaleMode === 'CROP'
+ const media = {
+ ...base,
+ scaleMode,
+ scalingFactor: scaleMode === 'TILE' ? (paint.scale ?? 1) : 1,
+ ...(!crop && { rotation: paint.imageRotation ?? 0 }),
+ filters: { ...NO_FILTERS }
+ }
+ const transform = rows(crop ? paint.imageTransform : undefined)
+ const hash = paint.imageHash ?? null
+ return type === 'IMAGE'
+ ? { type, ...media, imageTransform: transform, imageHash: hash }
+ : { type, ...media, videoTransform: transform, videoHash: hash }
+}
+
+function figmaPatternPaint(paint: Fill, base: ReadBase): FigmaPaint {
+ return {
+ type: 'PATTERN',
+ ...base,
+ sourceNodeId: paint.sourceNodeId ?? '',
+ tileType: paint.patternTileType ?? 'RECTANGULAR',
+ scalingFactor: paint.scale ?? 1,
+ spacing: { ...(paint.patternSpacing ?? { x: 0, y: 0 }) },
+ horizontalAlignment: paint.horizontalAlignment ?? 'START'
+ }
+}
+
+function openPencilPaint(paint: Fill, type: OpenPencilPaint['type']): OpenPencilPaint {
const { gradientTransform, imageTransform, ...rest } = paint
- const image = imageTransform ?? (paint.type === 'IMAGE' ? IDENTITY_GRADIENT_TRANSFORM : undefined)
return {
- ...rest,
- ...(gradientTransform && { gradientTransform: gradientTransformRows(gradientTransform) }),
- ...(image && { imageTransform: gradientTransformRows(image) })
+ ...structuredClone(rest),
+ type,
+ ...(gradientTransform && { gradientTransform: rows(gradientTransform) }),
+ ...(imageTransform && { imageTransform: rows(imageTransform) })
+ }
+}
+
+/** `paint` as Figma's plugin API reads it, its colour bound to `variableId` when given. */
+export function toFigmaPaint(paint: Fill, variableId?: string): FigmaPaint {
+ const base: ReadBase = {
+ visible: paint.visible,
+ opacity: paint.opacity,
+ blendMode: paint.blendMode ?? 'NORMAL'
+ }
+ const { type } = paint
+ if (type === 'SOLID') {
+ const { r, g, b } = paint.color
+ return {
+ type,
+ ...base,
+ color: { r, g, b },
+ boundVariables: variableId ? { color: variableAlias(variableId) } : {}
+ }
+ }
+ if (type === 'IMAGE' || type === 'VIDEO') return figmaMediaPaint(paint, type, base)
+ if (type === 'PATTERN') return figmaPatternPaint(paint, base)
+ if (type === 'NOISE' || type === 'CUSTOM') return openPencilPaint(paint, type)
+ return {
+ type,
+ ...base,
+ gradientStops: (paint.gradientStops ?? []).map(({ position, color }) => ({
+ position,
+ color: { ...color }
+ })),
+ gradientTransform: rows(paint.gradientTransform)
}
}
diff --git a/packages/core/src/figma-api/proxy.ts b/packages/core/src/figma-api/proxy.ts
index 08f7afbe9..dddb32650 100644
--- a/packages/core/src/figma-api/proxy.ts
+++ b/packages/core/src/figma-api/proxy.ts
@@ -4,8 +4,6 @@ import type {
SceneGraph,
SceneNode,
NodeType,
- Fill,
- Stroke,
LayoutGrid,
LayoutMode
} from '@open-pencil/scene-graph'
@@ -37,18 +35,14 @@ import {
type FigmaVectorNetwork,
type FigmaVectorPath
} from './accessors/vector'
-import {
- figmaPaintToFill,
- installVisualNodeProxyAccessors,
- type FigmaPaint
-} from './accessors/visual'
+import { installVisualNodeProxyAccessors } from './accessors/visual'
import { installComponentPropertyAccessors } from './components'
import { installDevStatusAccessors, type FigmaDevStatusValue } from './dev-status'
import type { FigmaFontName } from './fonts'
import type { FigmaFrameNode, FigmaInstanceNode } from './node-types'
import { installInstanceOverrideAccessors, type FigmaInstanceOverride } from './overrides'
import { getPageBackgrounds, setPageBackgrounds } from './page-backgrounds'
-import { toFigmaPaint, type WithFigmaTransforms } from './paints'
+import { parseFigmaPaints, toFigmaPaint, type FigmaPaint } from './paints'
import { installPluginDataMethods, type PluginDataMethods } from './plugin-data'
import { nodeProxyToJSON } from './serialization'
import { installShapeWithTextAccessors } from './shape-with-text'
@@ -110,8 +104,8 @@ export class FigmaNodeProxy {
declare readonly absoluteBoundingBox: Rect
declare readonly absoluteRenderBounds: Rect | null
- declare fills: readonly WithFigmaTransforms<Fill>[] | symbol
- declare strokes: readonly WithFigmaTransforms<Stroke>[]
+ declare fills: readonly FigmaPaint[] | symbol
+ declare strokes: readonly FigmaPaint[]
declare effects: readonly FigmaEffect[]
declare opacity: number
declare visible: boolean
@@ -342,14 +336,18 @@ export class FigmaNodeProxy {
// --- Components ---
- get backgrounds(): readonly WithFigmaTransforms<Fill>[] {
- return Object.freeze(getPageBackgrounds(this._raw()).map(toFigmaPaint))
+ get backgrounds(): readonly FigmaPaint[] {
+ // A page draws its background colour's alpha times the paint's opacity, which Figma reads as
+ // the opacity alone.
+ return Object.freeze(
+ getPageBackgrounds(this._raw()).map((paint) =>
+ toFigmaPaint({ ...paint, opacity: paint.opacity * paint.color.a })
+ )
+ )
}
set backgrounds(value: readonly FigmaPaint[]) {
- const fills = value.map((paint, index) =>
- figmaPaintToFill(paint, index, 'set_backgrounds', 'backgrounds')
- )
+ const fills = parseFigmaPaints(value, 'set_backgrounds', 'backgrounds')
setPageBackgrounds(this[INTERNAL_GRAPH], this._raw(), fills)
}
diff --git a/packages/core/src/figma-api/serialization.ts b/packages/core/src/figma-api/serialization.ts
index 79e627d5d..b4d7d5a33 100644
--- a/packages/core/src/figma-api/serialization.ts
+++ b/packages/core/src/figma-api/serialization.ts
@@ -29,7 +29,7 @@ function appendTextProps(obj: Record<string, unknown>, n: SceneNode): void {
obj.textAutoResize = n.textAutoResize
obj.textDirection = n.textDirection
if (n.lineHeight != null) obj.lineHeight = n.lineHeight
- if (n.letterSpacing !== 0) obj.letterSpacing = n.letterSpacing
+ if (n.letterSpacing.value !== 0) obj.letterSpacing = n.letterSpacing
if (n.textCase !== 'ORIGINAL') obj.textCase = n.textCase
if (n.textDecoration !== 'NONE') obj.textDecoration = n.textDecoration
if (n.maxLines != null) obj.maxLines = n.maxLines
diff --git a/packages/core/src/figma-api/text/index.ts b/packages/core/src/figma-api/text/index.ts
index 9e4671445..fc0ae5579 100644
--- a/packages/core/src/figma-api/text/index.ts
+++ b/packages/core/src/figma-api/text/index.ts
@@ -1,9 +1,11 @@
+import { compact } from 'es-toolkit/array'
import { upperFirst } from 'es-toolkit/string'
import type {
SceneGraph,
SceneNode,
StyleRun,
+ TextLength,
TextParagraphSpacingField,
TextParagraphStyle
} from '@open-pencil/scene-graph'
@@ -14,6 +16,7 @@ import {
paragraphStyleAt,
paragraphStylesAfterEdit,
paragraphStylesInRange,
+ pixelLength,
sharedParagraphSpacing,
textParagraphRanges,
trimParagraphStyles,
@@ -22,7 +25,7 @@ import {
withParagraphSpacing
} from '@open-pencil/scene-graph/text'
-import { invalid } from '#core/figma-api/accessors/text/messages'
+import { invalid, received } from '#core/figma-api/accessors/text/messages'
import { adjustRunsForDelete, getStyleAt, insertRunsWithStyle } from '#core/text/style-runs'
import { assertTextRange } from './style'
@@ -35,26 +38,58 @@ export interface FigmaLetterSpacing {
value: number
}
-/** The node keeps sizes in pixels; a percent is of its font size when set, as Figma resolves it. */
-function pixels(value: { unit: 'PIXELS' | 'PERCENT'; value: number }, fontSize: number) {
- return value.unit === 'PERCENT' ? (value.value / 100) * fontSize : value.value
+/** Figma's complaint about a length's `.value`, or null when it is a number. */
+function amountProblem(amount: unknown): string | null {
+ if (amount === undefined) return 'Required value missing at .value'
+ // NaN is a number to typeof, but not to Figma's check.
+ return typeof amount === 'number' && !Number.isNaN(amount)
+ ? null
+ : `Expected number, received ${received(amount)} at .value`
+}
+
+/** A length object a script passes to `method`, checked as Figma checks it. */
+function lengthObject(method: string, property: string, value: unknown) {
+ if (typeof value !== 'object' || value === null) {
+ throw invalid(method, `Expected object, received ${received(value)}`, property)
+ }
+ return value as { unit?: unknown; value?: unknown }
}
/**
- * Accepts Figma's object, or a bare number of pixels or `null` for automatic, as earlier
- * OpenPencil scripts wrote it.
+ * Accepts Figma's object, kept in its unit so a percent follows the font size as in Figma, or a
+ * bare number of pixels or `null` for automatic, as earlier OpenPencil scripts wrote it.
*/
-export function lineHeightValue(
- node: SceneNode,
- value: FigmaLineHeight | number | null
-): number | null {
- if (value === null || typeof value === 'number') return value
- return value.unit === 'AUTO' ? null : pixels(value, node.fontSize)
+export function lineHeightValue(value: unknown): TextLength | null {
+ if (value === null) return null
+ if (typeof value === 'number') return pixelLength(value)
+ const length = lengthObject('set_lineHeight', 'lineHeight', value)
+ if (length.unit === 'AUTO') return null
+ if (length.unit !== 'PIXELS' && length.unit !== 'PERCENT') {
+ throw invalid(
+ 'set_lineHeight',
+ 'Expected .unit to be one of the following: PIXELS, PERCENT, AUTO',
+ 'lineHeight'
+ )
+ }
+ const problem = amountProblem(length.value)
+ if (problem) throw invalid('set_lineHeight', problem, 'lineHeight')
+ return { unit: length.unit, value: length.value as number }
}
-/** Accepts Figma's object, or a bare number of pixels as earlier OpenPencil scripts wrote it. */
-export function letterSpacingValue(node: SceneNode, value: FigmaLetterSpacing | number): number {
- return typeof value === 'number' ? value : pixels(value, node.fontSize)
+/** Accepts Figma's object, in its unit, or a bare number of pixels as earlier scripts wrote it. */
+export function letterSpacingValue(value: unknown): TextLength {
+ if (typeof value === 'number') return pixelLength(value)
+ const length = lengthObject('set_letterSpacing', 'letterSpacing', value)
+ const unitKnown = length.unit === 'PIXELS' || length.unit === 'PERCENT'
+ // Figma lists every problem, the value's before the unit's.
+ const problems = compact([
+ amountProblem(length.value),
+ unitKnown ? null : 'Invalid option: expected one of "PIXELS"|"PERCENT" at .unit'
+ ])
+ if (problems.length > 0) {
+ throw invalid('set_letterSpacing', problems.join('\n'), 'letterSpacing')
+ }
+ return { unit: length.unit as TextLength['unit'], value: length.value as number }
}
/** Which neighbour inserted characters copy their style from, as Figma's `insertCharacters` takes it. */
diff --git a/packages/core/src/figma-api/text/style.ts b/packages/core/src/figma-api/text/style.ts
index 14a35706d..01b7abb30 100644
--- a/packages/core/src/figma-api/text/style.ts
+++ b/packages/core/src/figma-api/text/style.ts
@@ -1,8 +1,7 @@
import { mapValues, pickBy } from 'es-toolkit/object'
import { isEqual } from 'es-toolkit/predicate'
-import type { Fill, SceneNode } from '@open-pencil/scene-graph'
-import { copyFills } from '@open-pencil/scene-graph/copy'
+import type { SceneNode } from '@open-pencil/scene-graph'
import {
paragraphIndexAt,
paragraphSpacingAt,
@@ -10,7 +9,7 @@ import {
} from '@open-pencil/scene-graph/text'
import { readVariationSettings, weightToStyleName } from '#core/figma-api/fonts'
-import { toFigmaPaint, type WithFigmaTransforms } from '#core/figma-api/paints'
+import { toFigmaPaint, type FigmaPaint } from '#core/figma-api/paints'
import { variableAlias } from '#core/figma-api/variables/values'
import { characterStyles, nodeStyle, type CharacterStyle } from '#core/text/character-style'
@@ -60,7 +59,7 @@ function underlined(style: CharacterStyle): boolean {
/** Figma's paint for an underline colour of its own, or automatic, following the text. */
function decorationColor(style: CharacterStyle) {
const paint = style.textDecorationFills.at(0)
- return paint ? { value: toFigmaPaint(copyFills([paint])[0]) } : { value: 'AUTO' as const }
+ return paint ? { value: toFigmaPaint(paint) } : { value: 'AUTO' as const }
}
function fontFeatureMap(style: CharacterStyle): Record<string, boolean> {
@@ -69,6 +68,22 @@ function fontFeatureMap(style: CharacterStyle): Record<string, boolean> {
type FieldContext = { node: SceneNode; style: CharacterStyle; paragraph: number }
+/**
+ * A character's fills as Figma reads them. Fills a range sets draw at the colour's alpha times the
+ * paint's opacity, so a solid reads that product as its opacity; the layer's own fills, which
+ * characters without fills of their own share, draw at their opacity alone.
+ */
+function rangeFills(node: SceneNode, style: CharacterStyle): FigmaPaint[] {
+ if (style.fills === node.fills) return style.fills.map((paint) => toFigmaPaint(paint))
+ return style.fills.map((paint) =>
+ toFigmaPaint(
+ paint.type === 'SOLID'
+ ? { ...paint, opacity: paint.opacity * paint.color.a, color: { ...paint.color, a: 1 } }
+ : paint
+ )
+ )
+}
+
/** The decoration's own style reads null where the text is not underlined. */
function whenUnderlined(read: (style: CharacterStyle) => unknown) {
return ({ style }: FieldContext) => (underlined(style) ? read(style) : null)
@@ -107,9 +122,9 @@ const FIELD_READERS: Record<TextSegmentField, (context: FieldContext) => unknown
textDecorationThickness: whenUnderlined((style) => pixels(style.textDecorationThickness)),
textDecorationColor: whenUnderlined(decorationColor),
textCase: ({ style }) => style.textCase,
- lineHeight: ({ style }) => pixels(style.lineHeight),
- letterSpacing: ({ style }) => ({ unit: 'PIXELS', value: style.letterSpacing }),
- fills: ({ style }) => copyFills(style.fills).map(toFigmaPaint),
+ lineHeight: ({ style }) => (style.lineHeight ? { ...style.lineHeight } : { unit: 'AUTO' }),
+ letterSpacing: ({ style }) => ({ ...style.letterSpacing }),
+ fills: ({ node, style }) => rangeFills(node, style),
textStyleId: ({ style }) => style.textStyleId ?? '',
fillStyleId: ({ style }) => style.fillStyleId ?? '',
listOptions: ({ node, paragraph }) => ({
@@ -259,4 +274,4 @@ export function rangeHasUnderline(node: SceneNode, start: number, end: number):
return characterStyles(node, start, end).some(underlined)
}
-export type FigmaDecorationColor = { value: 'AUTO' } | { value: WithFigmaTransforms<Fill> }
+export type FigmaDecorationColor = { value: 'AUTO' } | { value: FigmaPaint }
diff --git a/packages/core/src/figma-api/variables/bindings.ts b/packages/core/src/figma-api/variables/bindings.ts
index ab89df015..71d119ba0 100644
--- a/packages/core/src/figma-api/variables/bindings.ts
+++ b/packages/core/src/figma-api/variables/bindings.ts
@@ -9,6 +9,7 @@ import {
type VariableType
} from '@open-pencil/scene-graph'
+import type { FigmaPaint } from '#core/figma-api/paints'
import { reconcileVariableLayouts } from '#core/layout/variables'
import { variableAlias, type FigmaVariableAlias } from './values'
@@ -206,12 +207,12 @@ export function setPaintBindings(
graph: SceneGraph,
node: SceneNode,
key: 'fills' | 'strokes',
- paints: readonly { boundVariables?: { color?: FigmaVariableAlias } }[]
+ paints: readonly FigmaPaint[]
): void {
const current = paintBindings(node, key)
const wanted = new Map<number, string>()
paints.forEach((paint, index) => {
- const id = paint.boundVariables?.color?.id
+ const id = 'boundVariables' in paint ? paint.boundVariables?.color?.id : undefined
if (id && graph.variables.get(id)?.type === 'COLOR') wanted.set(index, id)
})
for (const index of current.keys()) {
@@ -223,11 +224,6 @@ export function setPaintBindings(
if (current.size > 0 || wanted.size > 0) reconcileVariableLayouts(graph, { subtrees: [node.id] })
}
-/** A paint as Figma reads it, carrying the reference its colour is bound to. */
-export function withPaintBinding<T extends object>(paint: T, variableId: string | undefined): T {
- return variableId ? { ...paint, boundVariables: { color: variableAlias(variableId) } } : paint
-}
-
type FigmaBoundVariables = Record<string, FigmaVariableAlias | FigmaVariableAlias[]>
/**
diff --git a/packages/core/src/figma-api/variables/index.ts b/packages/core/src/figma-api/variables/index.ts
index 4efb087f9..7e49fba64 100644
--- a/packages/core/src/figma-api/variables/index.ts
+++ b/packages/core/src/figma-api/variables/index.ts
@@ -10,7 +10,6 @@ export {
paintBindings,
setLayerBinding,
setPaintBindings,
- withPaintBinding,
type FigmaBindableField
} from './bindings'
diff --git a/packages/core/src/io/formats/design-tokens/plan/styles.ts b/packages/core/src/io/formats/design-tokens/plan/styles.ts
index 957cb2898..04c69515b 100644
--- a/packages/core/src/io/formats/design-tokens/plan/styles.ts
+++ b/packages/core/src/io/formats/design-tokens/plan/styles.ts
@@ -1,9 +1,10 @@
import { isEqual, isPlainObject } from 'es-toolkit/predicate'
import * as v from 'valibot'
-import type { Effect, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import type { Effect, SceneGraph, SceneNode, TextLength } from '@open-pencil/scene-graph'
import type { Color } from '@open-pencil/scene-graph/primitives'
import { getSharedStyles } from '@open-pencil/scene-graph/shared-styles'
+import { percentLength, pixelLength, textLengthSchema } from '@open-pencil/scene-graph/text'
import { tryParseFigmaEffects } from '#core/figma-api/effects'
import {
@@ -44,8 +45,8 @@ const ownTextSchema = v.object({
fontWeight: v.number(),
italic: v.boolean(),
fontSize: v.number(),
- lineHeight: v.nullable(v.number()),
- letterSpacing: v.number(),
+ lineHeight: v.nullable(textLengthSchema),
+ letterSpacing: textLengthSchema,
textDecoration: v.picklist(['NONE', 'UNDERLINE', 'STRIKETHROUGH']),
textCase: v.picklist(['ORIGINAL', 'UPPER', 'LOWER', 'TITLE'])
}),
@@ -99,6 +100,12 @@ function textFields(token: ReadToken, resolve: Resolve): Partial<SceneNode> | nu
return fields && own ? { ...own.text, ...fields } : fields
}
+/** A token's line height: a multiple of the font size follows it as a percent, pixels stay. */
+function tokenLineHeight(multiplier: number | null, pixels: number | null): TextLength | null {
+ if (multiplier !== null) return percentLength(multiplier * 100)
+ return pixels === null ? null : pixelLength(pixels)
+}
+
function decodedTextFields(token: ReadToken, resolve: Resolve): Partial<SceneNode> | null {
if (!isPlainObject(token.value)) return null
const value = token.value
@@ -113,8 +120,9 @@ function decodedTextFields(token: ReadToken, resolve: Resolve): Partial<SceneNod
fontFamily,
fontSize,
fontWeight: fieldValue(value.fontWeight, resolve, decodeFontWeight) ?? 400,
- lineHeight: multiplier !== null ? multiplier * fontSize : lineHeightPx,
- letterSpacing: fieldValue(value.letterSpacing, resolve, pixels) ?? 0
+ // A unitless line height is a multiple of the font size, which follows the size as a percent.
+ lineHeight: tokenLineHeight(multiplier, lineHeightPx),
+ letterSpacing: pixelLength(fieldValue(value.letterSpacing, resolve, pixels) ?? 0)
}
}
diff --git a/packages/core/src/io/formats/design-tokens/styles.ts b/packages/core/src/io/formats/design-tokens/styles.ts
index c3bcfc892..27ac8b15b 100644
--- a/packages/core/src/io/formats/design-tokens/styles.ts
+++ b/packages/core/src/io/formats/design-tokens/styles.ts
@@ -1,6 +1,7 @@
import { isEmptyObject, isPlainObject } from 'es-toolkit/predicate'
import type { Effect, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import { lineHeightPixels, textLengthPixels } from '@open-pencil/scene-graph/text'
import { toFigmaEffect } from '#core/figma-api/effects'
@@ -38,16 +39,20 @@ export function typographyValue(
text: TypographyFields,
bound: Partial<Record<(typeof TEXT_BINDING_FIELDS)[number], string>>
) {
+ // A typography token writes a line height as a multiple of the font size.
+ const lineHeightPx = lineHeightPixels(text.lineHeight, text.fontSize)
const lineHeight =
- text.lineHeight === null || text.fontSize <= 0
+ lineHeightPx === null || text.fontSize <= 0
? AUTO_LINE_HEIGHT
- : trimNumber(text.lineHeight / text.fontSize)
+ : trimNumber(lineHeightPx / text.fontSize)
return {
fontFamily: bound.fontFamily ?? text.fontFamily,
fontSize: bound.fontSize ?? dimensionTokenValue(text.fontSize),
fontWeight: text.fontWeight,
lineHeight,
- letterSpacing: bound.letterSpacing ?? dimensionTokenValue(text.letterSpacing)
+ letterSpacing:
+ bound.letterSpacing ??
+ dimensionTokenValue(textLengthPixels(text.letterSpacing, text.fontSize))
}
}
diff --git a/packages/core/src/io/formats/pptx/export.ts b/packages/core/src/io/formats/pptx/export.ts
index c996d4fe7..4c95d8d78 100644
--- a/packages/core/src/io/formats/pptx/export.ts
+++ b/packages/core/src/io/formats/pptx/export.ts
@@ -4,6 +4,7 @@ import type PptxGenJS from 'pptxgenjs'
import type { Fill, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { getWorldMatrix } from '@open-pencil/scene-graph/coordinate'
import TransformMatrix, { type Mat3 } from '@open-pencil/scene-graph/matrix'
+import { lineHeightPixels, textLengthPixels } from '@open-pencil/scene-graph/text'
import {
hasUnsupportedTransform,
@@ -434,6 +435,7 @@ function addEditableText(ctx: ExportCtx, node: SceneNode, opacity: number): void
const singleLine = node.maxLines === 1 || node.textAutoResize === 'WIDTH_AND_HEIGHT'
const runs = buildTextRuns(ctx, node, opacity)
+ const lineHeightPx = lineHeightPixels(node.lineHeight, node.fontSize)
ctx.slide.addText(runs, {
x: box.x,
y: box.y,
@@ -448,7 +450,7 @@ function addEditableText(ctx: ExportCtx, node: SceneNode, opacity: number): void
// If the receiving app reflows text past the box, shrink to avoid layout
// breakage; otherwise this has no effect.
fit: 'shrink',
- lineSpacing: node.lineHeight != null ? pt(ctx, node.lineHeight) : undefined,
+ lineSpacing: lineHeightPx != null ? pt(ctx, lineHeightPx) : undefined,
shadow: mapShadow(node, opacity)
})
ctx.stats.editable += 1
@@ -492,7 +494,10 @@ function buildTextRuns(ctx: ExportCtx, node: SceneNode, opacity: number): PptxGe
italic: s.italic ?? node.italic,
color: fill ? hex(fill.color) : '000000',
transparency: transparency(opacity * (fill ? fill.opacity * fill.color.a : 1)),
- charSpacing: charSpacingPt(ctx, s.letterSpacing ?? node.letterSpacing),
+ charSpacing: charSpacingPt(
+ ctx,
+ textLengthPixels(s.letterSpacing ?? node.letterSpacing, fontSize)
+ ),
underline: deco === 'UNDERLINE' ? { style: 'sng' as const } : undefined,
strike: deco === 'STRIKETHROUGH' ? ('sngStrike' as const) : undefined
}
diff --git a/packages/core/src/io/formats/svg/text/export.ts b/packages/core/src/io/formats/svg/text/export.ts
index 0c2929062..efeaf9e7b 100644
--- a/packages/core/src/io/formats/svg/text/export.ts
+++ b/packages/core/src/io/formats/svg/text/export.ts
@@ -1,4 +1,5 @@
import type { CharacterStyleOverride, SceneNode } from '@open-pencil/scene-graph'
+import { textLengthPixels } from '@open-pencil/scene-graph/text'
import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text/direction'
import { formatColor, type SVGExportContext, type SVGFontAlias } from '#core/io/formats/svg/defs'
@@ -17,14 +18,26 @@ import { textFontFace } from '#core/text/requirements'
function styleOverrideToTspanAttrs(
style: CharacterStyleOverride,
colorSpace: 'srgb' | 'display-p3',
- parentFillOpacity: number | undefined
+ parentFillOpacity: number | undefined,
+ node: Pick<SceneNode, 'fontSize' | 'letterSpacing'>
): Record<string, string | number | undefined> {
const attrs: Record<string, string | number | undefined> = {}
if (style.fontFamily) attrs['font-family'] = style.fontFamily
if (style.fontSize) attrs['font-size'] = style.fontSize
if (style.fontWeight) attrs['font-weight'] = style.fontWeight
if (style.italic) attrs['font-style'] = 'italic'
- if (style.letterSpacing) attrs['letter-spacing'] = round(style.letterSpacing)
+ // A run's own spacing is written even at zero, or it would inherit the layer's. A percent the
+ // run inherits follows its own font size, so a larger or smaller run writes it again.
+ const inherited =
+ style.fontSize !== undefined &&
+ node.letterSpacing.unit === 'PERCENT' &&
+ node.letterSpacing.value !== 0
+ ? node.letterSpacing
+ : undefined
+ const spacing = style.letterSpacing ?? inherited
+ if (spacing) {
+ attrs['letter-spacing'] = round(textLengthPixels(spacing, style.fontSize ?? node.fontSize))
+ }
if (style.textDecoration === 'UNDERLINE') attrs['text-decoration'] = 'underline'
if (style.textDecoration === 'STRIKETHROUGH') attrs['text-decoration'] = 'line-through'
if (style.fills) {
@@ -128,6 +141,7 @@ export function renderTextNode(
let textDecoration: 'underline' | 'line-through' | undefined
if (node.textDecoration === 'UNDERLINE') textDecoration = 'underline'
else if (node.textDecoration === 'STRIKETHROUGH') textDecoration = 'line-through'
+ const letterSpacing = textLengthPixels(node.letterSpacing, node.fontSize)
const attrs: Record<string, string | number | undefined> = {
'font-family': node.fontFamily || undefined,
@@ -140,11 +154,11 @@ export function renderTextNode(
direction: direction === 'RTL' && !laidOut ? 'rtl' : undefined,
'text-anchor': laidOut ? undefined : textAnchorForNode(node, direction),
'text-decoration': textDecoration,
- 'letter-spacing': node.letterSpacing ? round(node.letterSpacing) : undefined,
+ 'letter-spacing': letterSpacing ? round(letterSpacing) : undefined,
...(fontAlias ? aliasedFontAttrs(textFontFace(node), fontAlias) : {})
}
const spanAttrs = (style: CharacterStyleOverride) => ({
- ...styleOverrideToTspanAttrs(style, colorSpace, fillOpacity),
+ ...styleOverrideToTspanAttrs(style, colorSpace, fillOpacity, node),
...(fontAlias ? aliasedFontAttrs(textFontFace(node, style), fontAlias) : {})
})
diff --git a/packages/core/src/io/formats/svg/text/import.ts b/packages/core/src/io/formats/svg/text/import.ts
index 93f703a36..cc6176932 100644
--- a/packages/core/src/io/formats/svg/text/import.ts
+++ b/packages/core/src/io/formats/svg/text/import.ts
@@ -9,6 +9,7 @@ import type {
import { localTransformFromWorld } from '@open-pencil/scene-graph/coordinate'
import { weightToStyle } from '@open-pencil/scene-graph/font-style'
import Matrix from '@open-pencil/scene-graph/matrix'
+import { pixelLength } from '@open-pencil/scene-graph/text'
import type { SVGElementLayer } from '#core/icons/types'
import { measureTextForLayout } from '#core/layout/text-measurement'
@@ -46,7 +47,7 @@ function runStyle(
fontSize: run.fontSize * scale,
fontWeight: run.fontWeight,
italic: run.italic,
- letterSpacing: run.letterSpacing * scale,
+ letterSpacing: pixelLength(run.letterSpacing * scale),
textDecoration: run.textDecoration,
fills: run.fills
}
diff --git a/packages/core/src/io/formats/svg/text/lines.ts b/packages/core/src/io/formats/svg/text/lines.ts
index 3814ddd49..32cc8299d 100644
--- a/packages/core/src/io/formats/svg/text/lines.ts
+++ b/packages/core/src/io/formats/svg/text/lines.ts
@@ -1,4 +1,5 @@
import type { CharacterStyleOverride, SceneNode } from '@open-pencil/scene-graph'
+import { lineHeightPixels } from '@open-pencil/scene-graph/text'
import { svg, type SVGNode } from '#core/io/formats/svg/node'
import { round } from '#core/io/formats/svg/paths'
@@ -126,7 +127,7 @@ function resolvedLineHeight(fontSize: number, lineHeight: number | null): number
function runLineHeight(node: SceneNode, style: CharacterStyleOverride | null): number {
const fontSize = style?.fontSize ?? node.fontSize
const lineHeight = style?.lineHeight !== undefined ? style.lineHeight : node.lineHeight
- return resolvedLineHeight(fontSize, lineHeight)
+ return resolvedLineHeight(fontSize, lineHeightPixels(lineHeight, fontSize))
}
/**
@@ -165,7 +166,9 @@ function explicitLineHeight(
covered = true
height = Math.max(height, runLineHeight(node, piece.style))
}
- return covered ? height : resolvedLineHeight(node.fontSize, node.lineHeight)
+ return covered
+ ? height
+ : resolvedLineHeight(node.fontSize, lineHeightPixels(node.lineHeight, node.fontSize))
}
/**
diff --git a/packages/core/src/layout/text-measurement.ts b/packages/core/src/layout/text-measurement.ts
index c1fe2021c..146e4bc84 100644
--- a/packages/core/src/layout/text-measurement.ts
+++ b/packages/core/src/layout/text-measurement.ts
@@ -1,5 +1,6 @@
import type { SceneNode } from '@open-pencil/scene-graph'
import { weightToStyle } from '@open-pencil/scene-graph/font-style'
+import { lineHeightPixels } from '@open-pencil/scene-graph/text'
import { measureTextWithOpenType } from '#core/text/opentype'
@@ -21,13 +22,14 @@ export function estimateTextSize(
const style = weightToStyle(node.fontWeight || 400, node.italic)
const text = node.text || ''
- const explicitLineH = (node.lineHeight ?? 0) > 0 ? (node.lineHeight as number) : undefined
+ const ownLineH = lineHeightPixels(node.lineHeight, fontSize) ?? 0
+ const explicitLineH = ownLineH > 0 ? ownLineH : undefined
const measured = measureTextWithOpenType(text, fontSize, family, style, maxWidth, explicitLineH)
if (measured) return measured
const charWidth = fontSize * GLYPH_WIDTH_FACTOR
const singleLineWidth = Math.ceil(text.length * charWidth)
- const lineH = (node.lineHeight ?? 0) > 0 ? (node.lineHeight as number) : Math.ceil(fontSize * 1.4)
+ const lineH = explicitLineH ?? Math.ceil(fontSize * 1.4)
if (maxWidth && maxWidth > 0 && singleLineWidth > maxWidth) {
const lines = Math.ceil(singleLineWidth / maxWidth)
diff --git a/packages/core/src/rpc/analyze-commands.ts b/packages/core/src/rpc/analyze-commands.ts
index f20df1168..4df7bbdd4 100644
--- a/packages/core/src/rpc/analyze-commands.ts
+++ b/packages/core/src/rpc/analyze-commands.ts
@@ -3,6 +3,7 @@ import { orderBy, sortBy } from 'es-toolkit/array'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { colorToHex, colorDistance as colorDist } from '@open-pencil/scene-graph/color'
import type { Color } from '@open-pencil/scene-graph/primitives'
+import { formatTextLength } from '@open-pencil/scene-graph/text'
import type { ColorUsageEntry } from '#core/tools/analyze/colors'
import {
@@ -156,7 +157,7 @@ export const analyzeTypographyCommand: RPCCommand<AnalyzeTypographyArgs, Analyze
if (node.type !== 'TEXT') continue
totalTextNodes++
- const lh = node.lineHeight === null ? 'auto' : `${node.lineHeight}px`
+ const lh = node.lineHeight === null ? 'auto' : formatTextLength(node.lineHeight)
const key = `${node.fontFamily}|${node.fontSize}|${node.fontWeight}|${lh}`
const existing = styleMap.get(key)
if (existing) {
diff --git a/packages/core/src/text/character-style.ts b/packages/core/src/text/character-style.ts
index c2a341e01..c03ad40ea 100644
--- a/packages/core/src/text/character-style.ts
+++ b/packages/core/src/text/character-style.ts
@@ -7,7 +7,8 @@ import {
type HyperlinkTarget,
type SceneNode,
type StyleRun,
- type TextBoundVariables
+ type TextBoundVariables,
+ type TextLength
} from '@open-pencil/scene-graph'
import {
SHARED_TEXT_STYLE_FIELDS,
@@ -33,7 +34,7 @@ export type CharacterStyle = Required<
| 'textCase'
>
> & {
- lineHeight: number | null
+ lineHeight: TextLength | null
textDecorationThickness: number | null
textUnderlineOffset: number | null
hyperlink: HyperlinkTarget | null
diff --git a/packages/core/src/text/outlines.ts b/packages/core/src/text/outlines.ts
index b68809b8c..c2cd4f88d 100644
--- a/packages/core/src/text/outlines.ts
+++ b/packages/core/src/text/outlines.ts
@@ -2,6 +2,7 @@ import { prepareWithSegments, layoutWithLines } from '@chenglou/pretext'
import type { CharacterStyleOverride, SceneNode } from '@open-pencil/scene-graph'
import { weightToStyle } from '@open-pencil/scene-graph/font-style'
+import { lineHeightPixels, textLengthPixels } from '@open-pencil/scene-graph/text'
import { fontManager } from '#core/text/fonts'
import {
@@ -57,7 +58,8 @@ function styleName(style: Pick<TextStyle, 'fontWeight' | 'italic'>): string {
}
function styleKey(style: TextStyle): string {
- return `${style.fontFamily}|${styleName(style)}|${style.fontSize}|${style.letterSpacing}`
+ const spacing = textLengthPixels(style.letterSpacing, style.fontSize)
+ return `${style.fontFamily}|${styleName(style)}|${style.fontSize}|${spacing}`
}
function textStyleAt(node: SceneNode, index: number): TextStyle {
@@ -122,7 +124,7 @@ export function getTextOutlineSupport(node: SceneNode): TextOutlineSupport {
}
function lineHeight(node: SceneNode): number {
- return node.lineHeight ?? Math.ceil(node.fontSize * 1.2)
+ return lineHeightPixels(node.lineHeight, node.fontSize) ?? Math.ceil(node.fontSize * 1.2)
}
interface TextLine {
@@ -151,7 +153,7 @@ function glyphAdvance(node: SceneNode, absoluteIndex: number): number | null {
style.fontSize
)
const glyph = metrics?.[0]
- return glyph ? glyph.advance + style.letterSpacing : null
+ return glyph ? glyph.advance + textLengthPixels(style.letterSpacing, style.fontSize) : null
}
function wrapStyledLine(node: SceneNode, line: TextLine): TextLine[] {
@@ -263,7 +265,7 @@ function lineGlyphs(
for (const glyph of metrics) {
glyphs.push({ commands: glyph.commands, x: cursorX, y: baseline })
- cursorX += glyph.advance + style.letterSpacing
+ cursorX += glyph.advance + textLengthPixels(style.letterSpacing, style.fontSize)
}
index = end
}
diff --git a/packages/core/src/tools/analyze/typography.ts b/packages/core/src/tools/analyze/typography.ts
index 4d3a81521..cffcf11d8 100644
--- a/packages/core/src/tools/analyze/typography.ts
+++ b/packages/core/src/tools/analyze/typography.ts
@@ -1,6 +1,8 @@
import { orderBy, sortBy } from 'es-toolkit/array'
import * as v from 'valibot'
+import { formatTextLength } from '@open-pencil/scene-graph/text'
+
import { defineTool } from '#core/tools/schema'
import { analysisLimitInputSchema } from './schema'
@@ -30,7 +32,7 @@ export const analyzeTypography = defineTool({
totalTextNodes++
const raw = figma.graph.getNode(node.id)
if (!raw) return false
- const lh = raw.lineHeight === null ? 'auto' : `${raw.lineHeight}`
+ const lh = raw.lineHeight === null ? 'auto' : formatTextLength(raw.lineHeight)
const key = `${raw.fontFamily}|${raw.fontSize}|${raw.fontWeight}|${lh}`
const entry = styleMap.get(key)
if (entry) {
diff --git a/packages/core/src/tools/create/vector.ts b/packages/core/src/tools/create/vector.ts
index 8451e0e50..5bafc2a8f 100644
--- a/packages/core/src/tools/create/vector.ts
+++ b/packages/core/src/tools/create/vector.ts
@@ -78,7 +78,7 @@ export const createVector = defineTool({
figma.graph.updateNode(node.id, { vectorNetwork: parsedPath.network })
}
if (args.fill) {
- node.fills = [{ type: 'SOLID', color: parseColor(args.fill), opacity: 1, visible: true }]
+ node.fills = [{ type: 'SOLID', color: parseColor(args.fill) }]
}
if (args.stroke) {
figma.graph.updateNode(node.id, {
diff --git a/packages/core/src/tools/modify/paint.ts b/packages/core/src/tools/modify/paint.ts
index 0cd1da589..8d0c25ecd 100644
--- a/packages/core/src/tools/modify/paint.ts
+++ b/packages/core/src/tools/modify/paint.ts
@@ -5,7 +5,6 @@ import { parseColor } from '@open-pencil/scene-graph/color'
import { gradientTransformRows, linearGradientTransform } from '@open-pencil/scene-graph/gradient'
import type { Vector } from '@open-pencil/scene-graph/primitives'
-import { BLACK } from '#core/constants'
import { storeImage } from '#core/figma-api/images'
import { defineTool, nodeIdInputSchema, toolNumber } from '#core/tools/schema'
@@ -59,9 +58,6 @@ export const setFill = defineTool({
node.fills = [
{
type: 'GRADIENT_LINEAR',
- color: c,
- opacity: 1,
- visible: true,
gradientStops: [
{ position: 0, color: c },
{ position: 1, color: cEnd }
@@ -72,7 +68,8 @@ export const setFill = defineTool({
return { id, gradient, start: c, end: cEnd }
}
- node.fills = [{ type: 'SOLID', color: c, opacity: 1, visible: true }]
+ // A colour's alpha becomes the paint's opacity, as Figma takes it.
+ node.fills = [{ type: 'SOLID', color: c }]
return { id, color: c }
}
})
@@ -99,16 +96,9 @@ export const setStroke = defineTool({
if (!node) return { error: `Node "${id}" not found` }
const c = parseColor(color)
- node.strokes = [
- {
- type: 'SOLID',
- color: c,
- weight: weight,
- opacity: 1,
- visible: true,
- align
- }
- ]
+ node.strokes = [{ type: 'SOLID', color: c }]
+ node.strokeWeight = weight
+ node.strokeAlign = align
return { id, color: c, weight: weight }
}
})
@@ -136,16 +126,7 @@ export const setImageFill = defineTool({
const bytes = toUint8Array(image_data)
const imageHash = storeImage(figma.graph, bytes)
const mode = scale_mode
- node.fills = [
- {
- type: 'IMAGE',
- color: BLACK,
- opacity: 1,
- visible: true,
- imageHash,
- imageScaleMode: mode
- }
- ]
+ node.fills = [{ type: 'IMAGE', imageHash, scaleMode: mode }]
return { id, imageHash, scaleMode: mode }
}
})
diff --git a/packages/core/src/tools/modify/text.ts b/packages/core/src/tools/modify/text.ts
index c117ddae1..02b39c094 100644
--- a/packages/core/src/tools/modify/text.ts
+++ b/packages/core/src/tools/modify/text.ts
@@ -143,9 +143,7 @@ export const setFontRange = defineTool({
)
}
if (args.color) {
- node.setRangeFills(start, end, [
- { type: 'SOLID', color: parseColor(args.color), opacity: 1, visible: true }
- ])
+ node.setRangeFills(start, end, [{ type: 'SOLID', color: parseColor(args.color) }])
}
} catch (error) {
return toolFailure(error)
diff --git a/packages/core/src/tools/stock-photo/apply.ts b/packages/core/src/tools/stock-photo/apply.ts
index 93eca4227..b094d8e25 100644
--- a/packages/core/src/tools/stock-photo/apply.ts
+++ b/packages/core/src/tools/stock-photo/apply.ts
@@ -87,16 +87,7 @@ export async function applyPhoto(
}
const imageHash = storeImage(figma.graph, imageBytes)
- node.fills = [
- {
- type: 'IMAGE',
- color: { r: 1, g: 1, b: 1, a: 1 },
- imageHash,
- imageScaleMode: 'FILL',
- visible: true,
- opacity: 1
- }
- ]
+ node.fills = [{ type: 'IMAGE', imageHash, scaleMode: 'FILL' }]
return {
id: node.id,
diff --git a/packages/core/src/xpath.ts b/packages/core/src/xpath.ts
index a265b2f93..b220e523d 100644
--- a/packages/core/src/xpath.ts
+++ b/packages/core/src/xpath.ts
@@ -1,6 +1,7 @@
import type * as FontoxpathModule from 'fontoxpath'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import { lineHeightPixels, textLengthPixels } from '@open-pencil/scene-graph/text'
const NODE_TYPES = {
ELEMENT_NODE: 1,
@@ -98,6 +99,13 @@ function createDocument(graph: SceneGraph, rootNode: SceneNode): XPathDocument {
return doc
}
+/** An attribute's value; text lengths compare in pixels, as `fontSize` does. */
+function attrValue(node: SceneNode, name: string): unknown {
+ if (name === 'lineHeight') return lineHeightPixels(node.lineHeight, node.fontSize)
+ if (name === 'letterSpacing') return textLengthPixels(node.letterSpacing, node.fontSize)
+ return Reflect.get(node, name)
+}
+
function getAttrs(wrapped: XPathNode): XPathAttr[] {
if (wrapped._attrs) return wrapped._attrs
@@ -106,7 +114,7 @@ function getAttrs(wrapped: XPathNode): XPathAttr[] {
for (const attrName of QUERYABLE_ATTRS) {
if (attrName in node) {
- const value = Reflect.get(node, attrName)
+ const value = attrValue(node, attrName)
if (value === undefined || value === null || typeof value === 'symbol') continue
const stringValue =
typeof value === 'object'
diff --git a/packages/core/tests/canvas/text/lines.test.ts b/packages/core/tests/canvas/text/lines.test.ts
index d0c96db10..f2e5dd8b2 100644
--- a/packages/core/tests/canvas/text/lines.test.ts
+++ b/packages/core/tests/canvas/text/lines.test.ts
@@ -4,6 +4,7 @@ import { expectDefined } from '#core-tests/helpers/assert'
import type { CanvasKit, TypefaceFontProvider } from 'canvaskit-wasm'
import { SceneGraph, type SceneNode, type StyleRun } from '@open-pencil/scene-graph'
+import { pixelLength } from '@open-pencil/scene-graph/text'
import type { TextLayout } from '#core/canvas/text/layout'
import { buildParagraph } from '#core/canvas/text/layout/build'
@@ -121,7 +122,10 @@ describe('lines of mixed sizes', () => {
})
test('gives a line the tallest line height on it, wrapped lines too', () => {
- const fixed = layOut({ text: 'one\ntwo\nthree', styleRuns: [run(4, 3, { lineHeight: 50 })] })
+ const fixed = layOut({
+ text: 'one\ntwo\nthree',
+ styleRuns: [run(4, 3, { lineHeight: pixelLength(50) })]
+ })
expectBaselines(fixed, [23.227, 73.227, 102.227])
expect(Math.ceil(fixed.getHeight())).toBe(108)
@@ -152,7 +156,7 @@ describe('lines of mixed sizes', () => {
test('centres the tallest font of a line in its line height', () => {
const layout = layOut({
text: 'Small LARGE\nsecond',
- lineHeight: 30,
+ lineHeight: pixelLength(30),
styleRuns: [run(6, 5, { fontSize: 40 })]
})
expectBaselines(layout, [29.545, 59.545])
diff --git a/packages/core/tests/canvas/text/placeholder.test.ts b/packages/core/tests/canvas/text/placeholder.test.ts
index b41bc75b5..295861bf9 100644
--- a/packages/core/tests/canvas/text/placeholder.test.ts
+++ b/packages/core/tests/canvas/text/placeholder.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, test } from 'bun:test'
import { expectDefined } from '#core-tests/helpers/assert'
import { SceneGraph } from '@open-pencil/scene-graph'
+import { percentLength } from '@open-pencil/scene-graph/text'
import { createConnector, connectorSublayers, freeEndpoint } from '@open-pencil/scene-graph/connectors'
import { createSticky, stickySublayers } from '@open-pencil/scene-graph/generated'
@@ -18,7 +19,7 @@ describe('sticky note placeholder', () => {
test("an empty body shows the canvas's placeholder, in the body's style at 30% black", () => {
const { graph, body } = emptyNote()
const drawn = expectDefined(stickyPlaceholderNode(graph, body, 'Пишите что угодно'))
- expect(drawn).toMatchObject({ text: 'Пишите что угодно', fontSize: 16, lineHeight: 24 })
+ expect(drawn).toMatchObject({ text: 'Пишите что угодно', fontSize: 16, lineHeight: percentLength(150) })
expect(drawn.fills[0]).toMatchObject({ opacity: 0.3, color: { r: 0, g: 0, b: 0 } })
expect(body.text).toBe('')
})
diff --git a/packages/core/tests/canvas/text/shape.test.ts b/packages/core/tests/canvas/text/shape.test.ts
index 3d7d0fdf5..3d65ac822 100644
--- a/packages/core/tests/canvas/text/shape.test.ts
+++ b/packages/core/tests/canvas/text/shape.test.ts
@@ -8,6 +8,7 @@ import type { TypefaceFontProvider } from 'canvaskit-wasm'
import type { ShapedText } from '@open-pencil/fig/node-change'
import { SceneGraph } from '@open-pencil/scene-graph'
import type { SceneNode } from '@open-pencil/scene-graph'
+import { pixelLength } from '@open-pencil/scene-graph/text'
import { withFigExportRuntime, withTextShaper } from '#core/canvas/text/shape'
import { getCanvasKit } from '#core/canvaskit'
@@ -24,7 +25,7 @@ async function shape(props: Partial<SceneNode>): Promise<ShapedText | null> {
const node = graph.createNode('TEXT', graph.getPages()[0].id, {
fontFamily: 'Inter',
fontSize: 13,
- lineHeight: 16,
+ lineHeight: pixelLength(16),
width: 230,
height: 32,
textAutoResize: 'HEIGHT',
diff --git a/packages/core/tests/editor/clipboard/import-nodes/text/metrics.test.ts b/packages/core/tests/editor/clipboard/import-nodes/text/metrics.test.ts
index 74371390e..4c79f47e9 100644
--- a/packages/core/tests/editor/clipboard/import-nodes/text/metrics.test.ts
+++ b/packages/core/tests/editor/clipboard/import-nodes/text/metrics.test.ts
@@ -5,6 +5,7 @@ import { createClipboardGraph } from '#core-tests/helpers/clipboard'
import { importClipboardNodes } from '@open-pencil/core/clipboard'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { percentLength, pixelLength } from '@open-pencil/scene-graph/text'
describe('importClipboardNodes: text metrics', () => {
it('imports fontWeight from fontName.style via styleToWeight', () => {
@@ -60,7 +61,7 @@ describe('importClipboardNodes: text metrics', () => {
expect(getNodeOrThrow(graph, created[2]).italic).toBe(true)
})
- it('converts letterSpacing object to pixels', () => {
+ it('keeps letter spacing in its unit', () => {
const { graph, pageId } = createClipboardGraph()
const nodeChanges = [
@@ -106,12 +107,12 @@ describe('importClipboardNodes: text metrics', () => {
] as NodeChange[]
const created = importClipboardNodes(nodeChanges, graph, pageId)
- expect(getNodeOrThrow(graph, created[0]).letterSpacing).toBe(2)
- expect(getNodeOrThrow(graph, created[1]).letterSpacing).toBe(2) // 10% of 20px
- expect(getNodeOrThrow(graph, created[2]).letterSpacing).toBe(0)
+ expect(getNodeOrThrow(graph, created[0]).letterSpacing).toEqual(pixelLength(2))
+ expect(getNodeOrThrow(graph, created[1]).letterSpacing).toEqual(percentLength(10))
+ expect(getNodeOrThrow(graph, created[2]).letterSpacing).toEqual(percentLength(0))
})
- it('converts RAW lineHeight to pixels', () => {
+ it('reads a RAW line height as the percent Figma writes it for', () => {
const { graph, pageId } = createClipboardGraph()
const nodeChanges = [
@@ -158,12 +159,12 @@ describe('importClipboardNodes: text metrics', () => {
] as NodeChange[]
const created = importClipboardNodes(nodeChanges, graph, pageId)
- expect(getNodeOrThrow(graph, created[0]).lineHeight).toBe(36) // 24 * 1.5
- expect(getNodeOrThrow(graph, created[1]).lineHeight).toBe(20)
- expect(getNodeOrThrow(graph, created[2]).lineHeight).toBe(24) // 120% of 20
+ expect(getNodeOrThrow(graph, created[0]).lineHeight).toEqual(percentLength(150))
+ expect(getNodeOrThrow(graph, created[1]).lineHeight).toEqual(pixelLength(20))
+ expect(getNodeOrThrow(graph, created[2]).lineHeight).toEqual(percentLength(120))
})
- it('converts letterSpacing and lineHeight in style overrides', () => {
+ it('keeps letter spacing and line height units in style overrides', () => {
const { graph, pageId } = createClipboardGraph()
const nodeChanges = [
@@ -201,8 +202,8 @@ describe('importClipboardNodes: text metrics', () => {
const created = importClipboardNodes(nodeChanges, graph, pageId)
const node = getNodeOrThrow(graph, created[0])
expect(node.styleRuns).toHaveLength(1)
- expect(node.styleRuns[0].style.lineHeight).toBe(30) // 20 * 1.5
- expect(node.styleRuns[0].style.letterSpacing).toBeCloseTo(-0.4) // 20 * -2/100
+ expect(node.styleRuns[0].style.lineHeight).toEqual(percentLength(150))
+ expect(node.styleRuns[0].style.letterSpacing).toEqual(percentLength(-2))
})
it('imports textAutoResize from clipboard data', () => {
diff --git a/packages/core/tests/editor/design-tokens.test.ts b/packages/core/tests/editor/design-tokens.test.ts
index f5113bc40..597ecc55a 100644
--- a/packages/core/tests/editor/design-tokens.test.ts
+++ b/packages/core/tests/editor/design-tokens.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, test } from 'bun:test'
import { createEditor } from '@open-pencil/core'
import { SceneGraph, type Variable } from '@open-pencil/scene-graph'
import { getSharedStyles } from '@open-pencil/scene-graph/shared-styles'
+import { pixelLength } from '@open-pencil/scene-graph/text'
import { parseVariableFormula } from '@open-pencil/scene-graph/variables'
import {
@@ -39,7 +40,7 @@ function designSystem() {
fontFamily: 'Inter',
fontWeight: 700,
fontSize: 32,
- lineHeight: 40,
+ lineHeight: pixelLength(40),
sharedStyleType: 'TEXT',
internalOnly: true,
boundVariables: { fontFamily: family.id }
@@ -100,7 +101,7 @@ describe('design token import', () => {
expect(node).toMatchObject({
name: 'Heading/H1',
fontSize: 32,
- lineHeight: 40,
+ lineHeight: pixelLength(40),
fontWeight: 700
})
expect(node?.boundVariables.fontFamily).toBe(variableNamed(graph, 'Font/Body').id)
@@ -210,7 +211,7 @@ describe('design token import', () => {
importInto(graph, exported(source))
const [style] = getSharedStyles(graph, 'text')
- expect(graph.getNode(style.nodeId)).toMatchObject({ textCase: 'UPPER', lineHeight: 40 })
+ expect(graph.getNode(style.nodeId)).toMatchObject({ textCase: 'UPPER', lineHeight: pixelLength(40) })
})
test('an edited shadow takes the place of the exact one, and the blur keeps its own', () => {
diff --git a/packages/core/tests/editor/page-backgrounds.test.ts b/packages/core/tests/editor/page-backgrounds.test.ts
index c173907c9..9e3f49148 100644
--- a/packages/core/tests/editor/page-backgrounds.test.ts
+++ b/packages/core/tests/editor/page-backgrounds.test.ts
@@ -15,6 +15,9 @@ const navy: Color = {
}
const red: Color = { r: 1, g: 0, b: 0, a: 1 }
+/** A colour as the plugin API reads a solid paint's: RGB, its alpha in the paint's opacity. */
+const rgb = ({ r, g, b }: Color) => ({ r, g, b })
+
function importedGraph() {
const graph = new SceneGraph()
const page = graph.getPages()[0]
@@ -46,13 +49,13 @@ describe('editor page backgrounds', () => {
editor.state.panX = 42
await editor.switchPage(second.id)
editor.setPageColor(red)
- api.currentPage.backgrounds = [
- { type: 'SOLID', color: { ...navy, a: 0.5 }, opacity: 0.5, visible: true }
- ]
+ // The paint's opacity wins over its colour's alpha.
+ const translucent = { type: 'SOLID' as const, color: { ...navy, a: 0.5 }, opacity: 0.5 }
+ api.currentPage.backgrounds = [translucent]
expect(editor.state.pageColor).toEqual(red)
await editor.switchPage(first.id)
expect(editor.state.panX).toBe(42)
- expect(editor.state.pageColor).toEqual({ ...navy, a: 0.25 })
+ expect(editor.state.pageColor).toEqual({ ...navy, a: 0.5 })
api.currentPage.backgrounds = []
expect(editor.state.pageColor).toEqual({ r: 0.96, g: 0.96, b: 0.96, a: 1 })
api.currentPage.backgrounds = [{ type: 'SOLID', color: red, opacity: 1, visible: false }]
@@ -69,7 +72,10 @@ describe('editor page backgrounds', () => {
try {
expect(graph.getPages()[0].source.fig.rawNodeFields.backgroundPaints).toBeUndefined()
expect(editor.state.pageColor).toEqual(navy)
- expect(new FigmaAPI(graph).currentPage.backgrounds[0]?.color).toEqual(navy)
+ expect(new FigmaAPI(graph).currentPage.backgrounds[0]).toMatchObject({
+ color: rgb(navy),
+ opacity: 1
+ })
} finally {
editor.dispose()
}
@@ -83,12 +89,15 @@ describe('editor page backgrounds', () => {
color.r = 0
expect(editor.state.pageColor).toEqual({ ...red, a: 0.5 })
const api = new FigmaAPI(editor.graph)
- expect(api.currentPage.backgrounds[0]?.color).toEqual({ ...red, a: 0.5 })
+ expect(api.currentPage.backgrounds[0]).toMatchObject({ color: rgb(red), opacity: 0.5 })
const bytes = await exportFigFile(editor.graph)
const reloaded = await parseFigFile(bytes.buffer as ArrayBuffer)
editor.replaceGraph(reloaded)
expect(editor.state.pageColor).toEqual({ ...red, a: 0.5 })
- expect(new FigmaAPI(reloaded).currentPage.backgrounds[0]?.color).toEqual({ ...red, a: 0.5 })
+ expect(new FigmaAPI(reloaded).currentPage.backgrounds[0]).toMatchObject({
+ color: rgb(red),
+ opacity: 0.5
+ })
} finally {
editor.dispose()
}
@@ -132,6 +141,6 @@ describe('new page backgrounds follow the interface theme', () => {
test('pages made by scripts', () => {
const figma = new FigmaAPI(new SceneGraph())
figma.theme = 'dark'
- expect(figma.createPage().backgrounds[0]?.color).toEqual(dark)
+ expect(figma.createPage().backgrounds[0]).toMatchObject({ color: rgb(dark) })
})
})
diff --git a/packages/core/tests/editor/shapes/with-text.test.ts b/packages/core/tests/editor/shapes/with-text.test.ts
index 266252a33..056cb8a91 100644
--- a/packages/core/tests/editor/shapes/with-text.test.ts
+++ b/packages/core/tests/editor/shapes/with-text.test.ts
@@ -2,10 +2,11 @@ import { afterEach, beforeEach, describe, expect, test } from 'bun:test'
import { expectDefined } from '#core-tests/helpers/assert'
-import { setTextMeasurer } from '@open-pencil/core/layout'
import { createEditor } from '@open-pencil/core'
-import { shapeWithTextLabel } from '@open-pencil/scene-graph/generated'
+import { setTextMeasurer } from '@open-pencil/core/layout'
import { colorToHex } from '@open-pencil/scene-graph/color'
+import { shapeWithTextLabel } from '@open-pencil/scene-graph/generated'
+import { lineHeightPixels } from '@open-pencil/scene-graph/text'
import { applyGeneratedTextNameEdit } from '#core/editor/text/name'
@@ -17,7 +18,9 @@ function setup() {
beforeEach(() => {
setTextMeasurer((node, maxWidth) => ({
width: maxWidth ?? node.width,
- height: node.text.split('\n').length * (node.lineHeight ?? node.fontSize)
+ height:
+ node.text.split('\n').length *
+ (lineHeightPixels(node.lineHeight, node.fontSize) ?? node.fontSize)
}))
})
afterEach(() => setTextMeasurer(null))
diff --git a/packages/core/tests/editor/stickies.test.ts b/packages/core/tests/editor/stickies.test.ts
index d77033128..759b03d85 100644
--- a/packages/core/tests/editor/stickies.test.ts
+++ b/packages/core/tests/editor/stickies.test.ts
@@ -4,6 +4,7 @@ import { createEditor } from '@open-pencil/core'
import { setTextMeasurer } from '@open-pencil/core/layout'
import type { SceneNode } from '@open-pencil/scene-graph'
import { STICKY_COLORS, stickySublayers } from '@open-pencil/scene-graph/generated'
+import { lineHeightPixels, percentLength } from '@open-pencil/scene-graph/text'
import { applyGeneratedTextNameEdit } from '#core/editor/text/name'
@@ -21,7 +22,9 @@ function sublayers(editor: ReturnType<typeof setup>['editor'], sticky: SceneNode
beforeEach(() => {
setTextMeasurer((node, maxWidth) => ({
width: maxWidth ?? node.width,
- height: node.text.split('\n').length * (node.lineHeight ?? node.fontSize)
+ height:
+ node.text.split('\n').length *
+ (lineHeightPixels(node.lineHeight, node.fontSize) ?? node.fontSize)
}))
})
afterEach(() => setTextMeasurer(null))
@@ -54,7 +57,7 @@ describe('sticky notes', () => {
const { editor, pageId } = setup()
const sticky = editor.createStickyNote(pageId, { x: 0, y: 0 })
editor.setStickyTextSize([sticky.id], 'large')
- expect(sublayers(editor, sticky).body).toMatchObject({ fontSize: 40, lineHeight: 60 })
+ expect(sublayers(editor, sticky).body).toMatchObject({ fontSize: 40, lineHeight: percentLength(150) })
editor.setStickyAuthorVisible([sticky.id], false)
expect(sublayers(editor, sticky).author.visible).toBe(false)
@@ -94,7 +97,7 @@ describe('sticky notes', () => {
const sticky = editor.createStickyNote(pageId, { x: 0, y: 0 })
editor.graph.updateNode(sublayers(editor, sticky).body.id, { fontFamily: 'Figma Hand' })
editor.setStickyTextSize([sticky.id], 'large')
- expect(sublayers(editor, sticky).body).toMatchObject({ fontSize: 40, letterSpacing: 0 })
+ expect(sublayers(editor, sticky).body).toMatchObject({ fontSize: 40, letterSpacing: percentLength(0) })
})
test("typing in a note's body renames a note that was never renamed", () => {
diff --git a/packages/core/tests/editor/text/auto-resize.test.ts b/packages/core/tests/editor/text/auto-resize.test.ts
index 09043635d..86c8a87fc 100644
--- a/packages/core/tests/editor/text/auto-resize.test.ts
+++ b/packages/core/tests/editor/text/auto-resize.test.ts
@@ -4,6 +4,7 @@ import { getNodeOrThrow } from '#core-tests/helpers/assert'
import { createEditor } from '@open-pencil/core'
import { setTextMeasurer } from '@open-pencil/core/layout'
+import { lineHeightPixels, pixelLength } from '@open-pencil/scene-graph/text'
afterEach(() => {
setTextMeasurer(null)
@@ -11,7 +12,10 @@ afterEach(() => {
describe('editor text auto-resize updates', () => {
test('lineHeight changes resize auto-height text', () => {
- setTextMeasurer((node) => ({ width: node.width, height: node.lineHeight ?? 20 }))
+ setTextMeasurer((node) => ({
+ width: node.width,
+ height: lineHeightPixels(node.lineHeight, node.fontSize) ?? 20
+ }))
const editor = createEditor()
const text = editor.graph.createNode('TEXT', editor.state.currentPageId, {
@@ -19,17 +23,20 @@ describe('editor text auto-resize updates', () => {
textAutoResize: 'HEIGHT',
width: 120,
height: 20,
- lineHeight: 20
+ lineHeight: pixelLength(20)
})
- editor.updateNode(text.id, { lineHeight: 48 })
+ editor.updateNode(text.id, { lineHeight: pixelLength(48) })
- expect(getNodeOrThrow(editor.graph, text.id).lineHeight).toBe(48)
+ expect(getNodeOrThrow(editor.graph, text.id).lineHeight).toEqual(pixelLength(48))
expect(getNodeOrThrow(editor.graph, text.id).height).toBe(48)
})
test('lineHeight changes on auto-height text are undoable with height', () => {
- setTextMeasurer((node) => ({ width: node.width, height: node.lineHeight ?? 20 }))
+ setTextMeasurer((node) => ({
+ width: node.width,
+ height: lineHeightPixels(node.lineHeight, node.fontSize) ?? 20
+ }))
const editor = createEditor()
const text = editor.graph.createNode('TEXT', editor.state.currentPageId, {
@@ -37,17 +44,17 @@ describe('editor text auto-resize updates', () => {
textAutoResize: 'HEIGHT',
width: 120,
height: 20,
- lineHeight: 20
+ lineHeight: pixelLength(20)
})
- editor.updateNodeWithUndo(text.id, { lineHeight: 48 }, 'Change lineHeight')
+ editor.updateNodeWithUndo(text.id, { lineHeight: pixelLength(48) }, 'Change lineHeight')
expect(getNodeOrThrow(editor.graph, text.id).height).toBe(48)
editor.undo.undo()
- expect(getNodeOrThrow(editor.graph, text.id).lineHeight).toBe(20)
+ expect(getNodeOrThrow(editor.graph, text.id).lineHeight).toEqual(pixelLength(20))
expect(getNodeOrThrow(editor.graph, text.id).height).toBe(20)
editor.undo.redo()
- expect(getNodeOrThrow(editor.graph, text.id).lineHeight).toBe(48)
+ expect(getNodeOrThrow(editor.graph, text.id).lineHeight).toEqual(pixelLength(48))
expect(getNodeOrThrow(editor.graph, text.id).height).toBe(48)
})
@@ -55,7 +62,10 @@ describe('editor text auto-resize updates', () => {
// A mutation outside the font-gated canvas edit session cannot reflow the
// glyphs. It must clear stale outlines/path identity without applying
// paragraph auto-resize to the imported path-text box.
- setTextMeasurer((node) => ({ width: node.width, height: node.lineHeight ?? 20 }))
+ setTextMeasurer((node) => ({
+ width: node.width,
+ height: lineHeightPixels(node.lineHeight, node.fontSize) ?? 20
+ }))
const editor = createEditor()
const glyphs = [
diff --git a/packages/core/tests/figma-api/accessors/basic/properties.test.ts b/packages/core/tests/figma-api/accessors/basic/properties.test.ts
index eecf32011..ddd2acd96 100644
--- a/packages/core/tests/figma-api/accessors/basic/properties.test.ts
+++ b/packages/core/tests/figma-api/accessors/basic/properties.test.ts
@@ -32,8 +32,7 @@ describe('property access', () => {
const api = createAPI()
const rect = api.createRectangle()
rect.fills = [solidFill({ r: 1, g: 0, b: 0, a: 1 })]
- expect(rect.fills.length).toBe(1)
- expect(rect.fills[0].color.r).toBe(1)
+ expect(rect.fills).toEqual([expect.objectContaining({ color: { r: 1, g: 0, b: 0 } })])
})
test('paints default to full opacity and visible, as in Figma', () => {
diff --git a/packages/core/tests/figma-api/accessors/basic/rescale.test.ts b/packages/core/tests/figma-api/accessors/basic/rescale.test.ts
index 55bd7fc68..7f5470850 100644
--- a/packages/core/tests/figma-api/accessors/basic/rescale.test.ts
+++ b/packages/core/tests/figma-api/accessors/basic/rescale.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, test } from 'bun:test'
import { expectDefined } from '#core-tests/helpers/assert'
-import { solidStroke } from '#core-tests/helpers/figma-api'
+import { solidFill } from '#core-tests/helpers/figma-api'
import { FigmaAPI, type FigmaNodeProxy } from '@open-pencil/core/figma-api'
import { SceneGraph } from '@open-pencil/scene-graph'
@@ -24,7 +24,9 @@ describe('rescale', () => {
frame.paddingBottom = 8
frame.itemSpacing = 5
frame.cornerRadius = 7
- frame.strokes = [solidStroke({ r: 0, g: 0, b: 0, a: 1 }, { weight: 3, align: 'CENTER' })]
+ frame.strokes = [solidFill({ r: 0, g: 0, b: 0, a: 1 })]
+ frame.strokeWeight = 3
+ frame.strokeAlign = 'CENTER'
frame.effects = [
{
type: 'DROP_SHADOW',
diff --git a/packages/core/tests/figma-api/accessors/strokes/geometry.test.ts b/packages/core/tests/figma-api/accessors/strokes/geometry.test.ts
index 02c4a2ec5..aff3ef889 100644
--- a/packages/core/tests/figma-api/accessors/strokes/geometry.test.ts
+++ b/packages/core/tests/figma-api/accessors/strokes/geometry.test.ts
@@ -38,10 +38,11 @@ describe('plugin API stroke geometry', () => {
})
test('the weight applies to every stroke and outlasts them', () => {
- const rect = api().createRectangle()
+ const graph = new SceneGraph()
+ const rect = new FigmaAPI(graph).createRectangle()
Reflect.set(rect, 'strokes', [...red, ...red])
rect.strokeWeight = 4
- expect(rect.strokes.map((stroke) => stroke.weight)).toEqual([4, 4])
+ expect(graph.getNode(rect.id)?.strokes.map((stroke) => stroke.weight)).toEqual([4, 4])
rect.strokes = []
expect(rect.strokeWeight).toBe(4)
Reflect.set(rect, 'strokes', red)
@@ -50,12 +51,27 @@ describe('plugin API stroke geometry', () => {
test('a node keeps its own copy of the strokes a script sets', () => {
const rect = api().createRectangle()
- const paint = { type: 'SOLID', color: { r: 1, g: 0, b: 0 }, dashPattern: [4, 2] }
+ const stops = [
+ { position: 0, color: { r: 1, g: 0, b: 0, a: 1 } },
+ { position: 1, color: { r: 0, g: 0, b: 1, a: 1 } }
+ ]
+ const paint = {
+ type: 'GRADIENT_LINEAR',
+ gradientStops: stops,
+ gradientTransform: [
+ [1, 0, 0],
+ [0, 1, 0]
+ ]
+ }
Reflect.set(rect, 'strokes', [paint])
- paint.color.g = 1
- paint.dashPattern.push(9)
- expect(rect.strokes[0]?.color).toMatchObject({ r: 1, g: 0, b: 0 })
- expect(rect.strokes[0]?.dashPattern).toEqual([4, 2])
+ stops[0].color.g = 1
+ stops.push({ position: 0.5, color: { r: 0, g: 1, b: 0, a: 1 } })
+ expect(rect.strokes[0]).toMatchObject({
+ gradientStops: [
+ { position: 0, color: { r: 1, g: 0, b: 0, a: 1 } },
+ { position: 1, color: { r: 0, g: 0, b: 1, a: 1 } }
+ ]
+ })
})
test('rescale scales the weight a node keeps without strokes', () => {
diff --git a/packages/core/tests/figma-api/accessors/strokes/individual-weights.test.ts b/packages/core/tests/figma-api/accessors/strokes/individual-weights.test.ts
index 2f579b873..036e690c0 100644
--- a/packages/core/tests/figma-api/accessors/strokes/individual-weights.test.ts
+++ b/packages/core/tests/figma-api/accessors/strokes/individual-weights.test.ts
@@ -1,7 +1,7 @@
import { describe, test, expect } from 'bun:test'
import { expectDefined, getNodeOrThrow } from '#core-tests/helpers/assert'
-import { solidStroke } from '#core-tests/helpers/figma-api'
+import { solidFill } from '#core-tests/helpers/figma-api'
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { sceneNodeToKiwi } from '@open-pencil/fig/node-change'
@@ -283,7 +283,9 @@ describe('FigmaAPI stroke properties', () => {
test('strokeTopWeight sets independentStrokeWeights', () => {
const api = new FigmaAPI(new SceneGraph())
const rect = api.createRectangle()
- rect.strokes = [solidStroke({ r: 0, g: 0, b: 0, a: 1 }, { weight: 2, align: 'CENTER' })]
+ rect.strokes = [solidFill({ r: 0, g: 0, b: 0, a: 1 })]
+ rect.strokeWeight = 2
+ rect.strokeAlign = 'CENTER'
rect.strokeTopWeight = 5
const raw = getNodeOrThrow(api.graph, rect.id)
@@ -301,14 +303,18 @@ describe('FigmaAPI stroke properties', () => {
test('strokeAlign getter returns first stroke align', () => {
const api = new FigmaAPI(new SceneGraph())
const rect = api.createRectangle()
- rect.strokes = [solidStroke({ r: 0, g: 0, b: 0, a: 1 }, { weight: 2, align: 'INSIDE' })]
+ rect.strokes = [solidFill({ r: 0, g: 0, b: 0, a: 1 })]
+ rect.strokeWeight = 2
+ rect.strokeAlign = 'INSIDE'
expect(rect.strokeAlign).toBe('INSIDE')
})
test('strokeAlign setter updates stroke', () => {
const api = new FigmaAPI(new SceneGraph())
const rect = api.createRectangle()
- rect.strokes = [solidStroke({ r: 0, g: 0, b: 0, a: 1 }, { weight: 2, align: 'CENTER' })]
+ rect.strokes = [solidFill({ r: 0, g: 0, b: 0, a: 1 })]
+ rect.strokeWeight = 2
+ rect.strokeAlign = 'CENTER'
rect.strokeAlign = 'OUTSIDE'
const raw = getNodeOrThrow(api.graph, rect.id)
diff --git a/packages/core/tests/figma-api/accessors/strokes/properties.test.ts b/packages/core/tests/figma-api/accessors/strokes/properties.test.ts
index 9c17f5d74..e52e26c44 100644
--- a/packages/core/tests/figma-api/accessors/strokes/properties.test.ts
+++ b/packages/core/tests/figma-api/accessors/strokes/properties.test.ts
@@ -1,12 +1,14 @@
import { describe, expect, test } from 'bun:test'
-import { createAPI, solidStroke } from '#core-tests/helpers/figma-api'
+import { createAPI, solidFill } from '#core-tests/helpers/figma-api'
describe('stroke details', () => {
test('strokeWeight and strokeAlign', () => {
const api = createAPI()
const rect = api.createRectangle()
- rect.strokes = [solidStroke({ r: 0, g: 0, b: 0, a: 1 }, { weight: 2, align: 'CENTER' })]
+ rect.strokes = [solidFill({ r: 0, g: 0, b: 0, a: 1 })]
+ rect.strokeWeight = 2
+ rect.strokeAlign = 'CENTER'
expect(rect.strokeWeight).toBe(2)
expect(rect.strokeAlign).toBe('CENTER')
rect.strokeWeight = 4
@@ -16,14 +18,16 @@ describe('stroke details', () => {
test('strokeCap and strokeJoin', () => {
const api = createAPI()
const line = api.createLine()
- line.strokes = [solidStroke({ r: 0, g: 0, b: 0, a: 1 }, { weight: 2, align: 'CENTER' })]
+ line.strokes = [solidFill({ r: 0, g: 0, b: 0, a: 1 })]
+ line.strokeWeight = 2
+ line.strokeAlign = 'CENTER'
expect(line.strokeCap).toBe('NONE')
expect(line.strokeJoin).toBe('MITER')
line.strokeCap = 'ROUND'
line.strokeJoin = 'BEVEL'
expect(line.strokeCap).toBe('ROUND')
expect(line.strokeJoin).toBe('BEVEL')
- expect(line.strokes[0]).toMatchObject({ cap: 'ROUND', join: 'BEVEL' })
+ expect(api.graph.getNode(line.id)?.strokes[0]).toMatchObject({ cap: 'ROUND', join: 'BEVEL' })
})
test('strokeMiterLimit', () => {
diff --git a/packages/core/tests/figma-api/accessors/vector.test.ts b/packages/core/tests/figma-api/accessors/vector.test.ts
index 22203a0f1..8845b07f8 100644
--- a/packages/core/tests/figma-api/accessors/vector.test.ts
+++ b/packages/core/tests/figma-api/accessors/vector.test.ts
@@ -114,7 +114,7 @@ describe('vector paths', () => {
const network = vector.vectorNetwork
expect(vector.x).toBe(10)
expect(vector.y).toBe(20)
- expect(network.regions?.[0]?.fills?.[0]?.color).toEqual({ r: 1, g: 0, b: 0, a: 1 })
+ expect(network.regions?.[0]?.fills?.[0]).toMatchObject({ color: { r: 1, g: 0, b: 0 } })
expect(Object.isFrozen(network.vertices)).toBe(true)
expect(Object.isFrozen(network.vertices[0])).toBe(true)
expect(Object.isFrozen(network.segments[0]?.tangentStart)).toBe(true)
diff --git a/packages/core/tests/figma-api/accessors/visual/frozen-paints.test.ts b/packages/core/tests/figma-api/accessors/visual/frozen-paints.test.ts
index ab10e641c..34b1dc67f 100644
--- a/packages/core/tests/figma-api/accessors/visual/frozen-paints.test.ts
+++ b/packages/core/tests/figma-api/accessors/visual/frozen-paints.test.ts
@@ -26,6 +26,6 @@ describe('frozen arrays', () => {
} catch (error) {
expect(error).toBeInstanceOf(TypeError)
}
- expect(rect.fills[0].color.r).toBe(1)
+ expect(rect.fills).toEqual([expect.objectContaining({ color: { r: 1, g: 0, b: 0 } })])
})
})
diff --git a/packages/core/tests/figma-api/components/from-node.test.ts b/packages/core/tests/figma-api/components/from-node.test.ts
index 06fc62891..99c7f82b0 100644
--- a/packages/core/tests/figma-api/components/from-node.test.ts
+++ b/packages/core/tests/figma-api/components/from-node.test.ts
@@ -99,7 +99,7 @@ describe('createComponentFromNode like Figma', () => {
expect(component.type).toBe('COMPONENT')
expect(component.name).toBe('r')
expect([component.x, component.y, component.width, component.height]).toEqual([100, 0, 50, 50])
- expect(expectFills(component.fills)[0]?.color).toMatchObject({ r: 1, g: 1, b: 1 })
+ expect(expectFills(component.fills)[0]).toMatchObject({ color: { r: 1, g: 1, b: 1 } })
expect(order()).toEqual(['a', 'r', 'z'])
expect(r.removed).toBe(false)
expect(component.children[0]?.id).toBe(r.id)
diff --git a/packages/core/tests/figma-api/page-backgrounds.test.ts b/packages/core/tests/figma-api/page-backgrounds.test.ts
index 1f15d11ee..0c99a84e0 100644
--- a/packages/core/tests/figma-api/page-backgrounds.test.ts
+++ b/packages/core/tests/figma-api/page-backgrounds.test.ts
@@ -11,9 +11,18 @@ describe('page backgrounds in the plugin API', () => {
figma.currentPage.backgrounds = [
{ type: 'SOLID', color: { r: 30 / 255, g: 30 / 255, b: 30 / 255 } }
]
- const [background] = figma.currentPage.backgrounds
- expect(background).toMatchObject({ type: 'SOLID', opacity: 1, visible: true })
- expect(background?.color.r).toBeCloseTo(30 / 255, 6)
+ expect(figma.currentPage.backgrounds).toEqual([
+ expect.objectContaining({
+ type: 'SOLID',
+ opacity: 1,
+ visible: true,
+ color: {
+ r: expect.closeTo(30 / 255, 6),
+ g: expect.closeTo(30 / 255, 6),
+ b: expect.closeTo(30 / 255, 6)
+ }
+ })
+ ])
})
test('page backgrounds expose imported canvas paints and support assignment', () => {
@@ -35,23 +44,27 @@ describe('page backgrounds in the plugin API', () => {
expect(api.currentPage.backgrounds).toEqual([
{
type: 'SOLID',
- color: { r: 0.5, g: 0.75, b: 1, a: 1 },
+ color: { r: 0.5, g: 0.75, b: 1 },
opacity: 1,
visible: true,
- blendMode: 'NORMAL'
+ blendMode: 'NORMAL',
+ boundVariables: {}
}
])
api.currentPage.backgrounds = [
{
type: 'SOLID',
- color: { r: 1, g: 0, b: 0, a: 1 },
+ color: { r: 1, g: 0, b: 0 },
opacity: 0.5,
visible: true,
blendMode: 'NORMAL'
}
]
- expect(api.currentPage.backgrounds[0]?.color).toEqual({ r: 1, g: 0, b: 0, a: 1 })
+ expect(api.currentPage.backgrounds[0]).toMatchObject({
+ color: { r: 1, g: 0, b: 0 },
+ opacity: 0.5
+ })
expect(page.source.fig.rawNodeFields.backgroundColor).toEqual({ r: 1, g: 0, b: 0, a: 1 })
})
})
diff --git a/packages/core/tests/figma-api/paints.test.ts b/packages/core/tests/figma-api/paints.test.ts
index 9135d8737..cb8e1c7b8 100644
--- a/packages/core/tests/figma-api/paints.test.ts
+++ b/packages/core/tests/figma-api/paints.test.ts
@@ -9,8 +9,8 @@ const STOPS = [
{ position: 1, color: { r: 0, g: 0, b: 1, a: 1 } }
]
-/** What the proxies' paint types ask of a gradient beside its stops and transform. */
-const GRADIENT = { color: { r: 0, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }
+/** What every scene paint holds beside the fields of its type. */
+const SCENE_PAINT = { color: { r: 0, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }
const SWAPPED = [
[0, 1, 0],
@@ -29,15 +29,12 @@ describe('a gradient transform', () => {
const { graph, figma } = api()
const rectangle = figma.createRectangle()
const paint = {
- ...GRADIENT,
type: 'GRADIENT_LINEAR' as const,
gradientTransform: SWAPPED,
gradientStops: STOPS
}
- // Strokes carry the node's weight and alignment too, which Figma's paint type leaves out.
- const stroke = { ...paint, weight: 1, align: 'CENTER' as const }
rectangle.fills = [paint]
- rectangle.strokes = [stroke]
+ rectangle.strokes = [paint]
expect(rectangle.fills).toEqual([expect.objectContaining({ gradientTransform: SWAPPED })])
expect(rectangle.strokes).toEqual([expect.objectContaining({ gradientTransform: SWAPPED })])
const stored = { m00: 0, m01: 1, m02: 0, m10: -1, m11: 0, m12: 1 }
@@ -48,9 +45,7 @@ describe('a gradient transform', () => {
test('round-trips from one layer to another', () => {
const { figma } = api()
const source = figma.createRectangle()
- source.fills = [
- { ...GRADIENT, type: 'GRADIENT_RADIAL', gradientTransform: SWAPPED, gradientStops: STOPS }
- ]
+ source.fills = [{ type: 'GRADIENT_RADIAL', gradientTransform: SWAPPED, gradientStops: STOPS }]
const target = figma.createEllipse()
target.fills = source.fills
expect(target.fills).toEqual(source.fills)
@@ -108,16 +103,7 @@ describe('an image transform', () => {
const { graph, figma } = api()
const rectangle = figma.createRectangle()
graph.updateNode(rectangle.id, {
- fills: [
- {
- type: 'IMAGE',
- color: { r: 0, g: 0, b: 0, a: 1 },
- opacity: 1,
- visible: true,
- imageHash: 'hash',
- imageScaleMode: 'FILL'
- }
- ]
+ fills: [{ ...SCENE_PAINT, type: 'IMAGE', imageHash: 'hash', imageScaleMode: 'FILL' }]
})
expect(rectangle.fills).toEqual([
expect.objectContaining({
@@ -140,7 +126,7 @@ describe('a layer printed as JSON', () => {
const blue = figma.variables.createVariable('blue', collection, 'COLOR')
blue.setValueForMode(collection.defaultModeId, { r: 0, g: 0, b: 1 })
const gradient: Fill = {
- ...GRADIENT,
+ ...SCENE_PAINT,
type: 'GRADIENT_LINEAR',
gradientStops: STOPS,
gradientTransform: { m00: 0, m01: 1, m02: 0, m10: -1, m11: 0, m12: 1 }
@@ -149,8 +135,8 @@ describe('a layer printed as JSON', () => {
graph.updateNode(rectangle.id, {
fills: [
gradient,
- { ...GRADIENT, type: 'IMAGE', imageHash: 'hash', imageScaleMode: 'FILL' },
- { ...GRADIENT, type: 'SOLID' }
+ { ...SCENE_PAINT, type: 'IMAGE', imageHash: 'hash', imageScaleMode: 'FILL' },
+ { ...SCENE_PAINT, type: 'SOLID' }
],
strokes: [{ ...gradient, weight: 1, align: 'CENTER' }]
})
@@ -171,7 +157,7 @@ describe('a layer printed as JSON', () => {
[0, 1, 0]
]
}),
- expect.objectContaining({ color: { r: 0, g: 0, b: 1, a: 1 } })
+ expect.objectContaining({ color: { r: 0, g: 0, b: 1 } })
])
})
@@ -188,3 +174,220 @@ describe('a layer printed as JSON', () => {
expect(copy.boundVariables).toEqual(rectangle.boundVariables)
})
})
+
+const HASH = 'a'.repeat(40)
+const IDENTITY: [[number, number, number], [number, number, number]] = [
+ [1, 0, 0],
+ [0, 1, 0]
+]
+const NO_FILTERS = {
+ exposure: 0,
+ contrast: 0,
+ saturation: 0,
+ temperature: 0,
+ tint: 0,
+ highlights: 0,
+ shadows: 0
+}
+
+/** Assigns `fills` as an untyped script would, so the checks see what Figma's types refuse. */
+function setFills(target: object, fills: unknown[]) {
+ Reflect.set(target, 'fills', fills)
+}
+
+function failure(problem: string, method = 'set_fills', property = 'fills') {
+ return `in ${method}: Property "${property}" failed validation: ${problem}`
+}
+
+// Recorded in Figma 126 with the same scripts.
+describe('a solid paint', () => {
+ test('reads an RGB colour, its alpha as the opacity, and no bound variables', () => {
+ const { graph, figma } = api()
+ const rectangle = figma.createRectangle()
+ rectangle.fills = [{ type: 'SOLID', color: { r: 1, g: 0, b: 0 }, opacity: 0.5 }]
+ expect(rectangle.fills).toEqual([
+ {
+ type: 'SOLID',
+ visible: true,
+ opacity: 0.5,
+ blendMode: 'NORMAL',
+ color: { r: 1, g: 0, b: 0 },
+ boundVariables: {}
+ }
+ ])
+ expect(graph.getNode(rectangle.id)?.fills[0]).toMatchObject({
+ color: { r: 1, g: 0, b: 0, a: 1 },
+ opacity: 0.5
+ })
+ })
+
+ test("takes a colour's alpha as the opacity it leaves out, on fills and strokes alike", () => {
+ const { figma } = api()
+ const rectangle = figma.createRectangle()
+ setFills(rectangle, [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 0.5 } }])
+ Reflect.set(rectangle, 'strokes', [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 0.5 } }])
+ const read = { color: { r: 1, g: 0, b: 0 }, opacity: 0.5 }
+ expect(rectangle.fills).toEqual([expect.objectContaining(read)])
+ expect(rectangle.strokes).toEqual([expect.objectContaining(read)])
+ // A paint giving both keeps its opacity.
+ setFills(rectangle, [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 0.5 }, opacity: 0.8 }])
+ expect(rectangle.fills).toEqual([expect.objectContaining({ opacity: 0.8 })])
+ })
+
+ test('refuses what Figma refuses, with its messages', () => {
+ const rectangle = api().figma.createRectangle()
+ const solid = (fields: object) => [{ type: 'SOLID', color: { r: 1, g: 0, b: 0 }, ...fields }]
+ expect(() => setFills(rectangle, solid({ color: '#FF0000' }))).toThrow(
+ failure('Expected object, received string at [0].color')
+ )
+ expect(() => setFills(rectangle, solid({ color: { r: 2, g: 0, b: 0 } }))).toThrow(
+ failure('Too big: expected number to be <=1 at [0].color.r')
+ )
+ expect(() => setFills(rectangle, solid({ opacity: 2 }))).toThrow(
+ failure('Too big: expected number to be <=1 at [0].opacity')
+ )
+ expect(() => setFills(rectangle, solid({ color: { r: 1, g: 0, b: 0, x: 1 } }))).toThrow(
+ failure('Unrecognized key: "x" at [0].color')
+ )
+ expect(() => setFills(rectangle, solid({ foo: 1 }))).toThrow(
+ failure('Unrecognized key: "foo" at index 0')
+ )
+ expect(() => Reflect.set(rectangle, 'strokes', solid({ opacity: 2 }))).toThrow(
+ failure('Too big: expected number to be <=1 at [0].opacity', 'set_strokes', 'strokes')
+ )
+ })
+})
+
+describe('an image paint', () => {
+ test('reads its scale mode, rotation, scaling, filters, and transform as Figma does', () => {
+ const { graph, figma } = api()
+ const rectangle = figma.createRectangle()
+ rectangle.fills = [{ type: 'IMAGE', imageHash: HASH, scaleMode: 'FIT', rotation: 90 }]
+ expect(rectangle.fills).toEqual([
+ {
+ type: 'IMAGE',
+ visible: true,
+ opacity: 1,
+ blendMode: 'NORMAL',
+ scaleMode: 'FIT',
+ scalingFactor: 1,
+ rotation: 90,
+ filters: NO_FILTERS,
+ imageTransform: IDENTITY,
+ imageHash: HASH
+ }
+ ])
+ // The renderer reads OpenPencil's names, so the image draws fitted and turned.
+ expect(graph.getNode(rectangle.id)?.fills[0]).toMatchObject({
+ imageScaleMode: 'FIT',
+ imageRotation: 90
+ })
+ })
+
+ test('tiles by its scaling factor', () => {
+ const { graph, figma } = api()
+ const rectangle = figma.createRectangle()
+ rectangle.fills = [{ type: 'IMAGE', imageHash: HASH, scaleMode: 'TILE', scalingFactor: 0.5 }]
+ expect(rectangle.fills).toEqual([
+ expect.objectContaining({
+ scaleMode: 'TILE',
+ scalingFactor: 0.5,
+ rotation: 0,
+ filters: NO_FILTERS,
+ imageTransform: IDENTITY
+ })
+ ])
+ expect(graph.getNode(rectangle.id)?.fills[0]).toMatchObject({
+ imageScaleMode: 'TILE',
+ scale: 0.5
+ })
+ })
+
+ test('crops by its transform and reads no rotation', () => {
+ const { figma } = api()
+ const rectangle = figma.createRectangle()
+ const crop = [
+ [0.5, 0, 0.25],
+ [0, 0.5, 0.25]
+ ] as [[number, number, number], [number, number, number]]
+ rectangle.fills = [{ type: 'IMAGE', imageHash: HASH, scaleMode: 'CROP', imageTransform: crop }]
+ const [fill] = rectangle.fills as readonly object[]
+ expect(fill).toEqual({
+ type: 'IMAGE',
+ visible: true,
+ opacity: 1,
+ blendMode: 'NORMAL',
+ scaleMode: 'CROP',
+ scalingFactor: 1,
+ filters: NO_FILTERS,
+ imageTransform: crop,
+ imageHash: HASH
+ })
+ expect(fill).not.toHaveProperty('rotation')
+ })
+
+ test('refuses a missing or unknown scale mode, OpenPencil names, and a missing hash', () => {
+ const rectangle = api().figma.createRectangle()
+ const scaleMode = 'Invalid option: expected one of "FILL"|"FIT"|"CROP"|"TILE" at [0].scaleMode'
+ expect(() => setFills(rectangle, [{ type: 'IMAGE', imageHash: HASH }])).toThrow(
+ failure(scaleMode)
+ )
+ expect(() =>
+ setFills(rectangle, [{ type: 'IMAGE', imageHash: HASH, scaleMode: 'COVER' }])
+ ).toThrow(failure(scaleMode))
+ expect(() =>
+ setFills(rectangle, [{ type: 'IMAGE', imageHash: HASH, imageScaleMode: 'FIT' }])
+ ).toThrow(failure(`${scaleMode}\nUnrecognized key: "imageScaleMode" at index 0`))
+ expect(() => setFills(rectangle, [{ type: 'IMAGE', scaleMode: 'FILL' }])).toThrow(
+ failure('Required value missing at [0].imageHash')
+ )
+ })
+})
+
+describe('paint types', () => {
+ test('a gradient stop colour needs its alpha, unlike a solid colour', () => {
+ const rectangle = api().figma.createRectangle()
+ expect(() =>
+ setFills(rectangle, [
+ {
+ type: 'GRADIENT_LINEAR',
+ gradientTransform: IDENTITY,
+ gradientStops: [{ position: 0, color: { r: 1, g: 0, b: 0 } }]
+ }
+ ])
+ ).toThrow(failure('Required value missing at [0].gradientStops[0].color.a'))
+ })
+
+ test('fills refuse a pattern, and a video names its hash by SHA-1', () => {
+ const rectangle = api().figma.createRectangle()
+ expect(() => setFills(rectangle, [{ type: 'PATTERN' }])).toThrow(
+ failure(
+ 'Expected [0].type to be one of the following: SOLID, SHADER, GRADIENT_LINEAR, ' +
+ 'GRADIENT_RADIAL, GRADIENT_ANGULAR, GRADIENT_DIAMOND, IMAGE, VIDEO'
+ )
+ )
+ expect(() =>
+ setFills(rectangle, [{ type: 'VIDEO', videoHash: 'not a hash', scaleMode: 'FILL' }])
+ ).toThrow('in set_fills: Invalid SHA1 hash')
+ })
+
+ test('a video reads as Figma names its fields', () => {
+ const { figma } = api()
+ const rectangle = figma.createRectangle()
+ rectangle.fills = [{ type: 'VIDEO', videoHash: HASH, scaleMode: 'FILL' }]
+ expect(rectangle.fills).toEqual([
+ {
+ type: 'VIDEO',
+ visible: true,
+ opacity: 1,
+ blendMode: 'NORMAL',
+ scaleMode: 'FILL',
+ scalingFactor: 1,
+ rotation: 0,
+ filters: NO_FILTERS,
+ videoTransform: IDENTITY,
+ videoHash: HASH
+ }
+ ])
+ })
+})
diff --git a/packages/core/tests/figma-api/proxy/clone.test.ts b/packages/core/tests/figma-api/proxy/clone.test.ts
index a1bc6348c..ddeb24631 100644
--- a/packages/core/tests/figma-api/proxy/clone.test.ts
+++ b/packages/core/tests/figma-api/proxy/clone.test.ts
@@ -16,7 +16,7 @@ describe('clone', () => {
const cloned = frame.clone()
expect(cloned.id).not.toBe(frame.id)
expect(cloned.name).toBe('Original')
- expect(expectFills(cloned.fills)[0].color.r).toBe(1)
+ expect(expectFills(cloned.fills)[0]).toMatchObject({ color: { r: 1 } })
expect(cloned.children.length).toBe(1)
expect(cloned.children[0].name).toBe('Child')
expect(cloned.children[0].id).not.toBe(child.id)
diff --git a/packages/core/tests/figma-api/render-bounds.test.ts b/packages/core/tests/figma-api/render-bounds.test.ts
index ef18fdcf2..929cd9110 100644
--- a/packages/core/tests/figma-api/render-bounds.test.ts
+++ b/packages/core/tests/figma-api/render-bounds.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import { solidStroke } from '#core-tests/helpers/figma-api'
+import { solidFill } from '#core-tests/helpers/figma-api'
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { SceneGraph } from '@open-pencil/scene-graph'
@@ -12,7 +12,9 @@ describe('absoluteRenderBounds', () => {
rect.x = 3
rect.y = 4
rect.resize(10, 20)
- rect.strokes = [solidStroke({ r: 1, g: 0, b: 0, a: 1 }, { weight: 4, align: 'OUTSIDE' })]
+ rect.strokes = [solidFill({ r: 1, g: 0, b: 0, a: 1 })]
+ rect.strokeWeight = 4
+ rect.strokeAlign = 'OUTSIDE'
rect.effects = [
{
type: 'DROP_SHADOW',
diff --git a/packages/core/tests/figma-api/text/references.test.ts b/packages/core/tests/figma-api/text/references.test.ts
index ba4d303dd..ab7156f70 100644
--- a/packages/core/tests/figma-api/text/references.test.ts
+++ b/packages/core/tests/figma-api/text/references.test.ts
@@ -168,7 +168,7 @@ describe('style ranges', () => {
await text.setRangeFillStyleIdAsync(0, 5, '1:30')
expect(text.getRangeFillStyleId(0, 5)).toBe('1:30')
- expect(text.getRangeFills(0, 5)).toMatchObject([{ type: 'SOLID', color: RED }])
+ expect(text.getRangeFills(0, 5)).toMatchObject([{ type: 'SOLID', color: { r: 1, g: 0, b: 0 } }])
expect(typeof text.fillStyleId).toBe('symbol')
text.setRangeFills(0, 5, [{ type: 'SOLID', color: { r: 0, g: 0, b: 1 } }])
diff --git a/packages/core/tests/figma-api/text/styles.test.ts b/packages/core/tests/figma-api/text/styles.test.ts
index 4b67b3621..de92aef54 100644
--- a/packages/core/tests/figma-api/text/styles.test.ts
+++ b/packages/core/tests/figma-api/text/styles.test.ts
@@ -167,19 +167,23 @@ describe('character style ranges', () => {
expect(expectFills(text.fills)[0]).toMatchObject({ color: { r: 0, g: 0, b: 1 } })
})
+ // Recorded in Figma 126: a range keeps the unit it is given, and the text reads Mixed.
test('take letter spacing and line height in pixels or percent of the font size', () => {
const { api, text } = styledText('Abc')
text.fontSize = 20
text.setRangeLetterSpacing(0, 1, { value: 10, unit: 'PERCENT' })
- expect(text.getRangeLetterSpacing(0, 1)).toEqual({ unit: 'PIXELS', value: 2 })
+ expect(text.getRangeLetterSpacing(0, 1)).toEqual({ unit: 'PERCENT', value: 10 })
expect<unknown>(text.letterSpacing).toBe(api.mixed)
text.setRangeLineHeight(0, 2, { value: 150, unit: 'PERCENT' })
+ expect(text.getRangeLineHeight(0, 1)).toEqual({ unit: 'PERCENT', value: 150 })
+ text.setRangeLineHeight(0, 2, { unit: 'PIXELS', value: 30 })
expect(text.getRangeLineHeight(0, 1)).toEqual({ unit: 'PIXELS', value: 30 })
+ expect<unknown>(text.lineHeight).toBe(api.mixed)
text.setRangeLineHeight(0, 2, { unit: 'AUTO' })
expect(text.getRangeLineHeight(0, 1)).toEqual({ unit: 'AUTO' })
})
- test('resolve a percent against the size of each character it styles', () => {
+ test('keep a percent for characters of every size, as Figma does', () => {
const { text } = styledText('Small Large')
text.fontSize = 10
text.setRangeFontSize(6, 11, 20)
@@ -189,20 +193,16 @@ describe('character style ranges', () => {
.map((segment) => [segment.start, segment.end, segment.letterSpacing])
text.letterSpacing = { value: 10, unit: 'PERCENT' }
- expect(spacing()).toEqual([
- [0, 6, { unit: 'PIXELS', value: 1 }],
- [6, 11, { unit: 'PIXELS', value: 2 }]
- ])
+ expect(spacing()).toEqual([[0, 11, { unit: 'PERCENT', value: 10 }]])
text.setRangeLetterSpacing(4, 8, { value: 50, unit: 'PERCENT' })
expect(spacing()).toEqual([
- [0, 4, { unit: 'PIXELS', value: 1 }],
- [4, 6, { unit: 'PIXELS', value: 5 }],
- [6, 8, { unit: 'PIXELS', value: 10 }],
- [8, 11, { unit: 'PIXELS', value: 2 }]
+ [0, 4, { unit: 'PERCENT', value: 10 }],
+ [4, 8, { unit: 'PERCENT', value: 50 }],
+ [8, 11, { unit: 'PERCENT', value: 10 }]
])
text.lineHeight = { value: 150, unit: 'PERCENT' }
- expect(text.getRangeLineHeight(0, 1)).toEqual({ unit: 'PIXELS', value: 15 })
- expect(text.getRangeLineHeight(6, 7)).toEqual({ unit: 'PIXELS', value: 30 })
+ expect(text.getRangeLineHeight(0, 1)).toEqual({ unit: 'PERCENT', value: 150 })
+ expect(text.getRangeLineHeight(6, 7)).toEqual({ unit: 'PERCENT', value: 150 })
})
test('style decorations of underlined ranges only, keeping them when the underline returns', () => {
@@ -363,3 +363,23 @@ describe('character style ranges', () => {
).toThrow(color('Number must be greater than or equal to 0 at .value.color.r'))
})
})
+
+// A range's own solid draws at its colour's alpha times its opacity; the layer's draws at opacity.
+test('a range reads the alpha its own fills draw at, and the layer keeps its opacity', () => {
+ const graph = new SceneGraph()
+ const text = new FigmaAPI(graph).createText()
+ text.characters = 'ab'
+ const half = { r: 1, g: 0, b: 0, a: 0.5 }
+ graph.updateNode(text.id, {
+ fills: [{ type: 'SOLID', color: half, opacity: 0.5, visible: true }],
+ styleRuns: [
+ {
+ start: 1,
+ length: 1,
+ style: { fills: [{ type: 'SOLID', color: half, opacity: 0.5, visible: true }] }
+ }
+ ]
+ })
+ expect(text.getRangeFills(0, 1)).toMatchObject([{ opacity: 0.5, color: { r: 1, g: 0, b: 0 } }])
+ expect(text.getRangeFills(1, 2)).toMatchObject([{ opacity: 0.25, color: { r: 1, g: 0, b: 0 } }])
+})
diff --git a/packages/core/tests/figma-api/text/units.test.ts b/packages/core/tests/figma-api/text/units.test.ts
index ef0893bde..43753aa57 100644
--- a/packages/core/tests/figma-api/text/units.test.ts
+++ b/packages/core/tests/figma-api/text/units.test.ts
@@ -4,47 +4,80 @@ import { expectDefined } from '#core-tests/helpers/assert'
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { SceneGraph } from '@open-pencil/scene-graph'
+import { lineHeightPixels, percentLength, pixelLength } from '@open-pencil/scene-graph/text'
function text() {
const graph = new SceneGraph()
const node = new FigmaAPI(graph).createText()
node.fontSize = 20
- return { graph, node }
+ return { graph, node, raw: () => expectDefined(graph.getNode(node.id)) }
}
-// Figma's plugin API reads and writes line height and letter spacing as { unit, value }. Scripts
-// written for Figma assigned those objects straight onto the node, which left the text
-// unmeasured and undrawn.
+// Recorded in Figma 126: line height and letter spacing read and write as { unit, value }, and a
+// percent stays a percent of the font size when the size changes.
describe('text units in the plugin API', () => {
test('line height takes pixels, percent of the font size, and auto', () => {
- const { graph, node } = text()
+ const { node, raw } = text()
node.lineHeight = { unit: 'PIXELS', value: 22 }
- expect(expectDefined(graph.getNode(node.id)).lineHeight).toBe(22)
+ expect(raw().lineHeight).toEqual(pixelLength(22))
expect(node.lineHeight).toEqual({ unit: 'PIXELS', value: 22 })
node.lineHeight = { unit: 'PERCENT', value: 150 }
- expect(expectDefined(graph.getNode(node.id)).lineHeight).toBe(30)
+ expect(node.lineHeight).toEqual({ unit: 'PERCENT', value: 150 })
+ node.fontSize = 40
+ expect(node.lineHeight).toEqual({ unit: 'PERCENT', value: 150 })
+ expect(lineHeightPixels(raw().lineHeight, raw().fontSize)).toBe(60)
node.lineHeight = { unit: 'AUTO' }
- expect(expectDefined(graph.getNode(node.id)).lineHeight).toBeNull()
+ expect(raw().lineHeight).toBeNull()
expect(node.lineHeight).toEqual({ unit: 'AUTO' })
})
- test('letter spacing takes pixels and percent of the font size', () => {
- const { graph, node } = text()
+ test('letter spacing takes pixels and percent of the font size, and keeps the percent', () => {
+ const { node, raw } = text()
node.letterSpacing = { unit: 'PERCENT', value: 10 }
- expect(expectDefined(graph.getNode(node.id)).letterSpacing).toBe(2)
+ node.fontSize = 40
+ expect(raw().letterSpacing).toEqual(percentLength(10))
+ expect(node.letterSpacing).toEqual({ unit: 'PERCENT', value: 10 })
+ node.letterSpacing = { unit: 'PIXELS', value: 2 }
expect(node.letterSpacing).toEqual({ unit: 'PIXELS', value: 2 })
})
+ test('a new text has no letter spacing, in percent', () => {
+ expect(text().node.letterSpacing).toEqual({ unit: 'PERCENT', value: 0 })
+ })
+
+ test('lengths Figma refuses throw its messages', () => {
+ const { node } = text()
+ const set = (field: 'lineHeight' | 'letterSpacing', value: unknown) => () =>
+ Reflect.set(node, field, value)
+ expect(set('lineHeight', { unit: 'RAW', value: 1.5 })).toThrow(
+ 'in set_lineHeight: Property "lineHeight" failed validation: Expected .unit to be one of the following: PIXELS, PERCENT, AUTO'
+ )
+ expect(set('lineHeight', { unit: 'PIXELS' })).toThrow(
+ 'in set_lineHeight: Property "lineHeight" failed validation: Required value missing at .value'
+ )
+ expect(set('lineHeight', '24')).toThrow(
+ 'in set_lineHeight: Property "lineHeight" failed validation: Expected object, received string'
+ )
+ expect(set('letterSpacing', { unit: 'AUTO' })).toThrow(
+ 'in set_letterSpacing: Property "letterSpacing" failed validation: Required value missing at .value\nInvalid option: expected one of "PIXELS"|"PERCENT" at .unit'
+ )
+ expect(set('lineHeight', { unit: 'PIXELS', value: Number.NaN })).toThrow(
+ 'in set_lineHeight: Property "lineHeight" failed validation: Expected number, received nan at .value'
+ )
+ expect(set('letterSpacing', { unit: 'RAW', value: 1 })).toThrow(
+ 'in set_letterSpacing: Property "letterSpacing" failed validation: Invalid option: expected one of "PIXELS"|"PERCENT" at .unit'
+ )
+ })
+
// Plugin typings allow only the object; untyped eval scripts may still pass a number.
test('a bare number still sets pixels and null automatic, as earlier OpenPencil scripts wrote them', () => {
- const { graph, node } = text()
+ const { node, raw } = text()
Reflect.set(node, 'lineHeight', 18)
Reflect.set(node, 'letterSpacing', 1)
- expect(expectDefined(graph.getNode(node.id))).toMatchObject({
- lineHeight: 18,
- letterSpacing: 1
- })
+ expect(raw()).toMatchObject({ lineHeight: pixelLength(18), letterSpacing: pixelLength(1) })
+ Reflect.set(node, 'lineHeight', null)
+ expect(raw().lineHeight).toBeNull()
})
})
diff --git a/packages/core/tests/figma-api/variables/collections.test.ts b/packages/core/tests/figma-api/variables/collections.test.ts
index 481811f72..74e283cba 100644
--- a/packages/core/tests/figma-api/variables/collections.test.ts
+++ b/packages/core/tests/figma-api/variables/collections.test.ts
@@ -289,7 +289,7 @@ describe('node variable bindings', () => {
rect.fills = [paint]
expect(rect.boundVariables).toEqual({ fills: [{ type: 'VARIABLE_ALIAS', id: color.id }] })
const [fill] = rect.fills as readonly { color: unknown; boundVariables?: unknown }[]
- expect(fill.color).toEqual({ r: 0, g: 0, b: 1, a: 1 })
+ expect(fill.color).toEqual({ r: 0, g: 0, b: 1 })
expect(fill.boundVariables).toEqual({ color: { type: 'VARIABLE_ALIAS', id: color.id } })
rect.fills = [solid]
expect(rect.boundVariables).toEqual({})
diff --git a/packages/core/tests/figma-api/variants/axes.test.ts b/packages/core/tests/figma-api/variants/axes.test.ts
index 8c4cf4457..9ed47c955 100644
--- a/packages/core/tests/figma-api/variants/axes.test.ts
+++ b/packages/core/tests/figma-api/variants/axes.test.ts
@@ -118,3 +118,14 @@ describe('variant properties through the Plugin API', () => {
expect(names(set)).toEqual(['State=Default, Size=sm', 'State=Hover, Size=sm'])
})
})
+
+// Recorded in Figma 126: an instance reads its own variant, as its main component names it.
+test("an instance's componentProperties report its own variant", () => {
+ const { hover } = variants()
+ const instance = hover.createInstance()
+ expect(instance.componentProperties.State?.value).toBe('Hover')
+ expect(instance.componentProperties.State?.type).toBe('VARIANT')
+
+ instance.setProperties({ State: 'Default' })
+ expect(instance.componentProperties.State?.value).toBe('Default')
+})
diff --git a/packages/core/tests/helpers/figma-api.ts b/packages/core/tests/helpers/figma-api.ts
index aee2e9c89..93c55e3b1 100644
--- a/packages/core/tests/helpers/figma-api.ts
+++ b/packages/core/tests/helpers/figma-api.ts
@@ -1,5 +1,5 @@
import { FigmaAPI, type FigmaNodeProxy } from '@open-pencil/core/figma-api'
-import { SceneGraph, type Fill, type Stroke } from '@open-pencil/scene-graph'
+import { SceneGraph, type Fill } from '@open-pencil/scene-graph'
import type { Color } from '@open-pencil/scene-graph/primitives'
export function createAPI(): FigmaAPI {
@@ -48,18 +48,6 @@ export function solidFill(
}
}
-/** The stroke counterpart of {@link solidFill}. */
-export function solidStroke(
- color: Color,
- stroke: { weight: number; align: Stroke['align']; opacity?: number; visible?: boolean }
-): SolidFill & Pick<Stroke, 'weight' | 'align'> {
- return {
- ...solidFill(color, stroke),
- weight: stroke.weight,
- align: stroke.align
- }
-}
-
/** A white 800×600 frame and a way to add named 50 px squares to it and read their stack order. */
export function createStackHost() {
const figma = new FigmaAPI(new SceneGraph())
diff --git a/packages/core/tests/helpers/property-cases.ts b/packages/core/tests/helpers/property-cases.ts
index 0e364f117..b98182a89 100644
--- a/packages/core/tests/helpers/property-cases.ts
+++ b/packages/core/tests/helpers/property-cases.ts
@@ -1,4 +1,5 @@
import type { SceneGraph, Fill, SceneNode, Stroke } from '@open-pencil/scene-graph'
+import { pixelLength } from '@open-pencil/scene-graph/text'
import { expectDefined } from './assert'
@@ -258,8 +259,8 @@ export const PROPERTY_CASES: RoundTripCase[] = [
textAlignHorizontal: 'CENTER',
textAlignVertical: 'BOTTOM',
textAutoResize: 'NONE',
- letterSpacing: 1,
- lineHeight: 28,
+ letterSpacing: pixelLength(1),
+ lineHeight: pixelLength(28),
textCase: 'UPPER',
textDecoration: 'UNDERLINE'
}),
diff --git a/packages/core/tests/io/formats/design-tokens/export.test.ts b/packages/core/tests/io/formats/design-tokens/export.test.ts
index 11c2a9aaf..2042a3f20 100644
--- a/packages/core/tests/io/formats/design-tokens/export.test.ts
+++ b/packages/core/tests/io/formats/design-tokens/export.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, test } from 'bun:test'
import { SceneGraph } from '@open-pencil/scene-graph'
+import { pixelLength } from '@open-pencil/scene-graph/text'
import { exportDesignTokens, RESOLVER_FILE, STYLES_FILE } from '#core/io/formats/design-tokens'
@@ -34,8 +35,8 @@ function designSystem() {
fontFamily: 'Inter',
fontWeight: 700,
fontSize: 32,
- lineHeight: 40,
- letterSpacing: -0.5,
+ lineHeight: pixelLength(40),
+ letterSpacing: pixelLength(-0.5),
sharedStyleType: 'TEXT',
internalOnly: true,
boundVariables: { fontFamily: family.id }
diff --git a/packages/core/tests/io/formats/fig/roundtrip/glyph-blob.test.ts b/packages/core/tests/io/formats/fig/roundtrip/glyph-blob.test.ts
index 3744da89b..c05d64168 100644
--- a/packages/core/tests/io/formats/fig/roundtrip/glyph-blob.test.ts
+++ b/packages/core/tests/io/formats/fig/roundtrip/glyph-blob.test.ts
@@ -12,6 +12,7 @@ import { fontManager } from '@open-pencil/core/text'
import { parseFigBuffer } from '@open-pencil/fig'
import { initCodec } from '@open-pencil/kiwi/fig/codec'
import { SceneGraph } from '@open-pencil/scene-graph'
+import { pixelLength } from '@open-pencil/scene-graph/text'
const INTER_ASSETS = corePackagePath('assets')
@@ -125,7 +126,7 @@ heavy('roundtrip: text glyph blobs', () => {
fontFamily: 'Inter',
fontWeight: 400,
fontSize: 13,
- lineHeight: 16,
+ lineHeight: pixelLength(16),
textAutoResize: 'HEIGHT'
})
diff --git a/packages/core/tests/io/formats/fig/roundtrip/helpers.ts b/packages/core/tests/io/formats/fig/roundtrip/helpers.ts
index cd7a76e0b..2a5a140b5 100644
--- a/packages/core/tests/io/formats/fig/roundtrip/helpers.ts
+++ b/packages/core/tests/io/formats/fig/roundtrip/helpers.ts
@@ -2,6 +2,7 @@ import { isEqual } from 'es-toolkit/predicate'
import type { SceneGraph, SceneNode, ComponentPropertyDefinition } from '@open-pencil/scene-graph'
import type { JSONObject } from '@open-pencil/scene-graph/primitives'
+import { textLengthPixels } from '@open-pencil/scene-graph/text'
import { verifyComponentPropDefs, verifyDerivedTextData } from './raw-verifiers/helpers'
@@ -374,7 +375,7 @@ export const RAW_VERIFIERS = new Map<string, Verifier>([
const g1raw = ctx.b as JSONObject | undefined
const node = ctx.aNodes.get(ctx.path)
if (!node || node.fontSize == null) return true
- const expected = node.letterSpacing
+ const expected = textLengthPixels(node.letterSpacing, node.fontSize)
const value = g1raw?.value
let actual = typeof value === 'number' ? value : undefined
if (actual !== undefined && g1raw?.units === 'PERCENT') {
diff --git a/packages/core/tests/io/formats/fig/roundtrip/instance-overrides.test.ts b/packages/core/tests/io/formats/fig/roundtrip/instance-overrides.test.ts
index a9fa21bba..a9199d5ac 100644
--- a/packages/core/tests/io/formats/fig/roundtrip/instance-overrides.test.ts
+++ b/packages/core/tests/io/formats/fig/roundtrip/instance-overrides.test.ts
@@ -6,6 +6,7 @@ import { exportFigFile, parseFigFile } from '@open-pencil/core/io/formats/fig'
import { initCodec } from '@open-pencil/kiwi/fig/codec'
import { SceneGraph } from '@open-pencil/scene-graph'
import { hasInstanceOverride, recordInstanceOverride } from '@open-pencil/scene-graph/instances'
+import { pixelLength } from '@open-pencil/scene-graph/text'
beforeAll(async () => {
await initCodec()
@@ -22,7 +23,7 @@ test('instance style overrides come back as overrides after saving and reopening
graph.updateNode(bar.id, { strokeWeight: 6, cornerSmoothing: 0.6 })
recordInstanceOverride(graph, bar.id, ['strokeWeight', 'cornerSmoothing'])
graph.updateNode(label.id, {
- letterSpacing: 2,
+ letterSpacing: pixelLength(2),
styleRuns: [{ start: 0, length: 5, style: { fontSize: 30 } }]
})
recordInstanceOverride(graph, label.id, ['letterSpacing', 'styleRuns'])
@@ -38,7 +39,7 @@ test('instance style overrides come back as overrides after saving and reopening
expect(reopenedBar.strokeWeight).toBe(6)
// Kiwi stores it as a 32-bit float, as Figma does.
expect(reopenedBar.cornerSmoothing).toBeCloseTo(0.6)
- expect(reopenedLabel.letterSpacing).toBe(2)
+ expect(reopenedLabel.letterSpacing).toEqual(pixelLength(2))
expect(reopenedLabel.styleRuns).toEqual([
expect.objectContaining({
start: 0,
@@ -57,10 +58,10 @@ test('instance style overrides come back as overrides after saving and reopening
// The reopened overrides hold through an edit to the component; the rest follows it.
const [componentBar, componentLabel] = reopened.getChildren(component.id)
reopened.updateNode(componentBar.id, { strokeWeight: 3, strokeAlign: 'OUTSIDE' })
- reopened.updateNode(componentLabel.id, { letterSpacing: 5, textCase: 'UPPER' })
+ reopened.updateNode(componentLabel.id, { letterSpacing: pixelLength(5), textCase: 'UPPER' })
reopened.syncInstances(component.id)
expect([reopenedBar.strokeWeight, reopenedBar.strokeAlign]).toEqual([6, 'OUTSIDE'])
- expect([reopenedLabel.letterSpacing, reopenedLabel.textCase]).toEqual([2, 'UPPER'])
+ expect([reopenedLabel.letterSpacing, reopenedLabel.textCase]).toEqual([pixelLength(2), 'UPPER'])
})
test('an instance that clears its component’s fill style keeps it cleared after reopening', async () => {
diff --git a/packages/core/tests/io/formats/fig/roundtrip/verifier-contracts.test.ts b/packages/core/tests/io/formats/fig/roundtrip/verifier-contracts.test.ts
index ef3f40583..ca5752ffa 100644
--- a/packages/core/tests/io/formats/fig/roundtrip/verifier-contracts.test.ts
+++ b/packages/core/tests/io/formats/fig/roundtrip/verifier-contracts.test.ts
@@ -1,6 +1,7 @@
import { expect, test } from 'bun:test'
import { SceneGraph } from '@open-pencil/scene-graph'
+import { pixelLength } from '@open-pencil/scene-graph/text'
import { RAW_VERIFIERS, SCENE_VERIFIERS, type VerifierContext } from './helpers'
@@ -51,7 +52,7 @@ test('raw letter-spacing comparison uses the saved unit and still rejects wrong
const context = referenceContext('asset', 'asset')
const text = context.aGraph.createNode('TEXT', context.aGraph.getPages()[0].id, {
fontSize: 20,
- letterSpacing: 0.1
+ letterSpacing: pixelLength(0.1)
})
context.aNodes.set(context.path, text)
context.key = 'letterSpacing'
diff --git a/packages/core/tests/io/formats/pdf/text-layout.test.ts b/packages/core/tests/io/formats/pdf/text-layout.test.ts
index 52b6969fa..f2bff85c4 100644
--- a/packages/core/tests/io/formats/pdf/text-layout.test.ts
+++ b/packages/core/tests/io/formats/pdf/text-layout.test.ts
@@ -3,6 +3,7 @@ import { beforeAll, expect, test } from 'bun:test'
import { expectDefined } from '#core-tests/helpers/assert'
import { SceneGraph } from '@open-pencil/scene-graph'
+import { pixelLength } from '@open-pencil/scene-graph/text'
import { withPDFTextLayout } from '#core/io/formats/pdf/prepare'
import { renderNodesToSVG } from '#core/io/formats/svg'
@@ -22,7 +23,7 @@ test('a paragraph wrapped on the canvas keeps its lines in the SVG drawn into a
text: SENTENCE,
fontFamily: 'Inter',
fontSize: 13,
- lineHeight: 16,
+ lineHeight: pixelLength(16),
width: 230,
height: 32,
textAutoResize: 'HEIGHT'
@@ -51,7 +52,7 @@ test('a style run that starts mid-word is placed where the canvas draws its firs
fontSize: 20,
width: 200,
height: 24,
- styleRuns: [{ start: 1, length: 3, style: { letterSpacing: 4 } }]
+ styleRuns: [{ start: 1, length: 3, style: { letterSpacing: pixelLength(4) } }]
})
const svg = await withPDFTextLayout(async (textLayout) => {
diff --git a/packages/core/tests/io/formats/svg/text/lines.test.ts b/packages/core/tests/io/formats/svg/text/lines.test.ts
index b83fa5d3e..86eba39c4 100644
--- a/packages/core/tests/io/formats/svg/text/lines.test.ts
+++ b/packages/core/tests/io/formats/svg/text/lines.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, test } from 'bun:test'
import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
+import { percentLength, pixelLength } from '@open-pencil/scene-graph/text'
import { renderNodesToSVG, type SVGTextLine } from '#core/io/formats/svg'
@@ -31,7 +32,7 @@ describe('SVG text with laid-out lines', () => {
test('without a measured layout, each explicit newline keeps its own baseline', () => {
for (const lines of [undefined, null, []]) {
const svg = exportText(
- { text: 'First line\nSecond line', fontSize: 16, lineHeight: 24, width: 100 },
+ { text: 'First line\nSecond line', fontSize: 16, lineHeight: pixelLength(24), width: 100 },
lines
)
const text = textElement(svg)
@@ -151,7 +152,12 @@ describe('SVG text with laid-out lines', () => {
describe('SVG text lines without a measured layout', () => {
test('a single line stays one text element', () => {
- const svg = exportText({ text: 'First line', fontSize: 16, lineHeight: 24, width: 100 })
+ const svg = exportText({
+ text: 'First line',
+ fontSize: 16,
+ lineHeight: pixelLength(24),
+ width: 100
+ })
expect(textElement(svg)).toBe(
'<text x="0" y="16" font-family="Inter" font-size="16" fill="#000000">First line</text>'
)
@@ -199,7 +205,7 @@ describe('SVG text lines without a measured layout', () => {
const svg = exportText({
text: 'Aa\nBb',
fontSize: 16,
- lineHeight: 24,
+ lineHeight: pixelLength(24),
width: 100,
styleRuns: [{ start: 3, length: 2, style: { fontSize: 40 } }]
})
@@ -214,7 +220,7 @@ describe('SVG text lines without a measured layout', () => {
fontSize: 16,
lineHeight: null,
width: 100,
- styleRuns: [{ start: 4, length: 3, style: { lineHeight: 50 } }]
+ styleRuns: [{ start: 4, length: 3, style: { lineHeight: pixelLength(50) } }]
})
const text = textElement(svg)
expect(text).toContain('<tspan x="0" y="16">one</tspan>')
@@ -281,7 +287,7 @@ describe('SVG text lines without a measured layout', () => {
text: 'First line\nSecond line',
fontSize: 10,
// 120% of 10px is stored on the node as 12px.
- lineHeight: 12,
+ lineHeight: pixelLength(12),
width: 100
})
const text = textElement(svg)
@@ -293,7 +299,7 @@ describe('SVG text lines without a measured layout', () => {
const center = exportText({
text: 'First line\nSecond line',
fontSize: 16,
- lineHeight: 24,
+ lineHeight: pixelLength(24),
width: 100,
textAlignHorizontal: 'CENTER'
})
@@ -304,7 +310,7 @@ describe('SVG text lines without a measured layout', () => {
const right = exportText({
text: 'First line\nSecond line',
fontSize: 16,
- lineHeight: 24,
+ lineHeight: pixelLength(24),
width: 100,
textAlignHorizontal: 'RIGHT'
})
@@ -317,7 +323,7 @@ describe('SVG text lines without a measured layout', () => {
const svg = exportText({
text: 'أول\nثان',
fontSize: 16,
- lineHeight: 24,
+ lineHeight: pixelLength(24),
width: 180,
textDirection: 'RTL',
textAlignHorizontal: 'LEFT'
@@ -332,7 +338,7 @@ describe('SVG text lines without a measured layout', () => {
const styled = exportText({
text: 'abcd\nefgh',
fontSize: 16,
- lineHeight: 24,
+ lineHeight: pixelLength(24),
width: 100,
styleRuns: [{ start: 2, length: 4, style: { fontWeight: 700 } }]
})
@@ -340,7 +346,12 @@ describe('SVG text lines without a measured layout', () => {
'<tspan x="0" y="16">ab</tspan><tspan font-weight="700">cd</tspan><tspan x="0" y="40" font-weight="700">e</tspan><tspan>fgh</tspan>'
)
- const blank = exportText({ text: 'A\n\nC', fontSize: 16, lineHeight: 24, width: 100 })
+ const blank = exportText({
+ text: 'A\n\nC',
+ fontSize: 16,
+ lineHeight: pixelLength(24),
+ width: 100
+ })
const text = textElement(blank)
expect(text).toContain('<tspan x="0" y="16">A</tspan>')
expect(text).toContain('<tspan x="0" y="64">C</tspan>')
@@ -349,20 +360,20 @@ describe('SVG text lines without a measured layout', () => {
test('a carriage return is dropped only when it belongs to a CRLF', () => {
const crlf = textElement(
- exportText({ text: 'A\r\nB', fontSize: 16, lineHeight: 24, width: 100 })
+ exportText({ text: 'A\r\nB', fontSize: 16, lineHeight: pixelLength(24), width: 100 })
)
expect(crlf).toContain('<tspan x="0" y="16">A</tspan>')
expect(crlf).toContain('<tspan x="0" y="40">B</tspan>')
expect(crlf).not.toContain('\r')
const trailing = textElement(
- exportText({ text: 'A\nB\r', fontSize: 16, lineHeight: 24, width: 100 })
+ exportText({ text: 'A\nB\r', fontSize: 16, lineHeight: pixelLength(24), width: 100 })
)
expect(trailing).toContain('<tspan x="0" y="16">A</tspan>')
expect(trailing).toContain('>B\r</tspan>')
const middle = textElement(
- exportText({ text: 'A\rB\nC', fontSize: 16, lineHeight: 24, width: 100 })
+ exportText({ text: 'A\rB\nC', fontSize: 16, lineHeight: pixelLength(24), width: 100 })
)
expect(middle).toContain('>A\rB</tspan>')
expect(middle).toContain('<tspan x="0" y="40">C</tspan>')
@@ -372,7 +383,7 @@ describe('SVG text lines without a measured layout', () => {
const svg = exportText({
text: ' First\nSecond ',
fontSize: 16,
- lineHeight: 24,
+ lineHeight: pixelLength(24),
width: 100
})
const text = textElement(svg)
@@ -400,7 +411,7 @@ describe('SVG text case', () => {
text: 'straße\nnext',
textCase: 'UPPER',
fontSize: 16,
- lineHeight: 24,
+ lineHeight: pixelLength(24),
width: 100
})
const text = textElement(svg)
@@ -422,3 +433,25 @@ describe('SVG text case', () => {
expect(runs).toContain('>case</tspan>')
})
})
+
+// A run that changes the size spaces its characters at its own size, as the canvas does.
+test('a larger run resolves the percent spacing it inherits at its own size', () => {
+ const svg = exportText({
+ text: 'ab',
+ fontSize: 20,
+ letterSpacing: percentLength(10),
+ styleRuns: [{ start: 1, length: 1, style: { fontSize: 40 } }]
+ })
+ expect(svg).toContain('letter-spacing="2"')
+ expect(svg).toContain('<tspan font-size="40" letter-spacing="4">b</tspan>')
+})
+
+test("a run's own zero spacing is written, so it does not inherit the layer's", () => {
+ const svg = exportText({
+ text: 'ab',
+ fontSize: 20,
+ letterSpacing: pixelLength(2),
+ styleRuns: [{ start: 1, length: 1, style: { letterSpacing: percentLength(0) } }]
+ })
+ expect(svg).toContain('<tspan letter-spacing="0">b</tspan>')
+})
diff --git a/packages/core/tests/layout/generated/sticky.test.ts b/packages/core/tests/layout/generated/sticky.test.ts
index 22da7fe34..87ee265f7 100644
--- a/packages/core/tests/layout/generated/sticky.test.ts
+++ b/packages/core/tests/layout/generated/sticky.test.ts
@@ -5,12 +5,15 @@ import { expectDefined } from '#core-tests/helpers/assert'
import { computeAllLayouts, setTextMeasurer } from '@open-pencil/core/layout'
import { SceneGraph } from '@open-pencil/scene-graph'
import { createSticky, stickySublayers } from '@open-pencil/scene-graph/generated'
+import { lineHeightPixels } from '@open-pencil/scene-graph/text'
/** One line per line break, each as tall as the text's line height. */
function measureLines(): void {
setTextMeasurer((node, maxWidth) => ({
width: maxWidth ?? node.width,
- height: node.text.split('\n').length * (node.lineHeight ?? node.fontSize)
+ height:
+ node.text.split('\n').length *
+ (lineHeightPixels(node.lineHeight, node.fontSize) ?? node.fontSize)
}))
}
diff --git a/packages/core/tests/tools/analyze/diff/visual.test.ts b/packages/core/tests/tools/analyze/diff/visual.test.ts
index e69437063..491bcab49 100644
--- a/packages/core/tests/tools/analyze/diff/visual.test.ts
+++ b/packages/core/tests/tools/analyze/diff/visual.test.ts
@@ -73,9 +73,7 @@ describe('diff_visual', () => {
const copy = card.clone()
copy.x = 300
const copiedSwatch = expectDefined(copy.children[0], 'copied swatch')
- copiedSwatch.fills = [
- { type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }
- ]
+ copiedSwatch.fills = [{ type: 'SOLID', color: { r: 1, g: 0, b: 0 }, opacity: 1, visible: true }]
const result = await visualDiff(figma, { from: card.id, to: copy.id, scale: 2 })
expect(result.width).toBe(200)
diff --git a/packages/design-jsx/src/export/props.ts b/packages/design-jsx/src/export/props.ts
index ec041e986..398e87d13 100644
--- a/packages/design-jsx/src/export/props.ts
+++ b/packages/design-jsx/src/export/props.ts
@@ -7,6 +7,7 @@ import { createDefaultNode } from '@open-pencil/scene-graph/node-defaults'
import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text/direction'
import { BLEND_MODE, TEXT_ALIGN, TEXT_ALIGN_VERTICAL, TEXT_CASE, TEXT_DECORATION } from '../enums'
+import { textLengthJSX } from '../overrides/text'
import { collectDecorationProps } from './decoration'
import {
collectCornerRadii,
@@ -252,8 +253,10 @@ function collectTextNodeProps(node: SceneNode, props: JSXProp[]): void {
if (node.textAlignVertical !== 'TOP') {
props.push(['textAlignVertical', TEXT_ALIGN_VERTICAL.print(node.textAlignVertical)])
}
- if (node.lineHeight != null) props.push(['lineHeight', node.lineHeight])
- if (node.letterSpacing !== 0) props.push(['letterSpacing', node.letterSpacing])
+ if (node.lineHeight != null) props.push(['lineHeight', textLengthJSX(node.lineHeight)])
+ if (node.letterSpacing.value !== 0) {
+ props.push(['letterSpacing', textLengthJSX(node.letterSpacing)])
+ }
if (node.textDecoration !== 'NONE')
props.push(['textDecoration', TEXT_DECORATION.print(node.textDecoration)])
collectDecorationProps(
diff --git a/packages/design-jsx/src/export/text.ts b/packages/design-jsx/src/export/text.ts
index 836eb0a7f..f57fb2a4f 100644
--- a/packages/design-jsx/src/export/text.ts
+++ b/packages/design-jsx/src/export/text.ts
@@ -15,7 +15,7 @@ import {
} from '@open-pencil/scene-graph/text'
import { TEXT_CASE, TEXT_DECORATION } from '../enums'
-import { AUTO } from '../overrides/text'
+import { AUTO, textLengthJSX } from '../overrides/text'
import { SPAN_STYLE_FIELDS, type SpanStyle } from '../text-content'
import { collectDecorationProps } from './decoration'
import { collectFillProps } from './paint'
@@ -55,8 +55,12 @@ function spanProps(style: SpanStyle, node: SceneNode): JSXProp[] {
if (style.fontWeight !== undefined) props.push(['weight', fontWeightValue(style.fontWeight)])
if (style.italic !== undefined) props.push(['italic', style.italic])
if (style.fills) collectFillProps({ ...node, fills: style.fills }, props)
- if (style.lineHeight !== undefined) props.push(['lineHeight', style.lineHeight ?? AUTO])
- if (style.letterSpacing !== undefined) props.push(['letterSpacing', style.letterSpacing])
+ if (style.lineHeight !== undefined) {
+ props.push(['lineHeight', style.lineHeight ? textLengthJSX(style.lineHeight) : AUTO])
+ }
+ if (style.letterSpacing !== undefined) {
+ props.push(['letterSpacing', textLengthJSX(style.letterSpacing)])
+ }
if (style.textDecoration !== undefined)
props.push(['textDecoration', TEXT_DECORATION.print(style.textDecoration)])
collectDecorationProps(style, node, props)
diff --git a/packages/design-jsx/src/overrides/text.ts b/packages/design-jsx/src/overrides/text.ts
index 8620f375c..e02d6d2f2 100644
--- a/packages/design-jsx/src/overrides/text.ts
+++ b/packages/design-jsx/src/overrides/text.ts
@@ -1,7 +1,8 @@
import * as v from 'valibot'
-import type { Fill, SceneNode } from '@open-pencil/scene-graph'
+import type { Fill, SceneNode, TextLength } from '@open-pencil/scene-graph'
import type { Color } from '@open-pencil/scene-graph/primitives'
+import { percentLength, pixelLength } from '@open-pencil/scene-graph/text'
import { TEXT_DECORATION_STYLE } from '../enums'
import { parseScriptInput } from '../schema'
@@ -12,6 +13,21 @@ export const AUTO = 'auto'
/** The decoration colour that follows the text's, as in CSS. */
export const CURRENT_COLOR = 'currentColor'
+/** A percent of the font size, such as `'150%'`, which follows the size as in Figma. */
+const PERCENT_LENGTH = /^(-?\d+(?:\.\d+)?)%$/
+
+/** A line height or letter spacing a prop gives: pixels as a number, or a percent string. */
+export function textLengthProp(value: unknown): TextLength | undefined {
+ if (typeof value === 'number' && Number.isFinite(value)) return pixelLength(value)
+ const match = typeof value === 'string' ? PERCENT_LENGTH.exec(value.trim()) : null
+ return match ? percentLength(Number(match[1])) : undefined
+}
+
+/** A line height or letter spacing as a prop writes it. */
+export function textLengthJSX(length: TextLength): number | `${number}%` {
+ return length.unit === 'PIXELS' ? length.value : `${length.value}%`
+}
+
const lengthSchema = v.pipe(v.number(), v.finite())
const autoLengthSchema = v.union([lengthSchema, v.literal(AUTO)])
diff --git a/packages/design-jsx/src/props-overrides.ts b/packages/design-jsx/src/props-overrides.ts
index ede3add84..08d9ba0ad 100644
--- a/packages/design-jsx/src/props-overrides.ts
+++ b/packages/design-jsx/src/props-overrides.ts
@@ -25,7 +25,7 @@ import { applyEffectOverrides } from './overrides/effects'
import { fillFromValue, isColor, isFillValue } from './overrides/fills'
import { applyStateOverrides } from './overrides/state'
import { applyStrokeOverrides } from './overrides/strokes'
-import { applyTextDetailOverrides, AUTO } from './overrides/text'
+import { applyTextDetailOverrides, AUTO, textLengthProp } from './overrides/text'
import { isShaderFill } from './paints'
const WEIGHT_MAP: Record<string, number> = {
@@ -349,9 +349,11 @@ function applyTextStyleOverrides(props: Record<string, unknown>, o: Partial<Scen
o.fills = [colorToFill(props.color)]
}
- if (props.lineHeight === AUTO) o.lineHeight = null
- else if (props.lineHeight !== undefined) o.lineHeight = props.lineHeight as number
- if (props.letterSpacing !== undefined) o.letterSpacing = props.letterSpacing as number
+ // A value it cannot read is left out, so the text keeps its own.
+ const lineHeight = props.lineHeight === AUTO ? null : textLengthProp(props.lineHeight)
+ if (lineHeight !== undefined) o.lineHeight = lineHeight
+ const letterSpacing = textLengthProp(props.letterSpacing)
+ if (letterSpacing) o.letterSpacing = letterSpacing
const textDecoration = TEXT_DECORATION.parse(props.textDecoration)
if (textDecoration) o.textDecoration = textDecoration
applyTextDetailOverrides(props, o)
diff --git a/packages/design-jsx/src/reference/authoring.md b/packages/design-jsx/src/reference/authoring.md
index fc38e3e09..085e1d55f 100644
--- a/packages/design-jsx/src/reference/authoring.md
+++ b/packages/design-jsx/src/reference/authoring.md
@@ -34,7 +34,7 @@ This reference describes scene creation, not React DOM output. Use the `render`
## Variables and components
- Create document variables before referencing them with `designVar('id-or-name')`. `defineVars` groups references; it does not create variable collections.
-- COLOR references work in paint props. FLOAT references work in `w`, `h`, `gap`, padding, corner radii, `strokeWidth`, `opacity`, text `size`/`fontSize`, `lineHeight`, and `letterSpacing`. Grid `columnGap`/`rowGap` and wrapped flex `rowGap` also support FLOAT references; grid `gap` overrides both axis-specific gaps. Use numbers or FLOAT references for these scalar props, not CSS unit strings.
+- COLOR references work in paint props. FLOAT references work in `w`, `h`, `gap`, padding, corner radii, `strokeWidth`, `opacity`, text `size`/`fontSize`, `lineHeight`, and `letterSpacing`. Grid `columnGap`/`rowGap` and wrapped flex `rowGap` also support FLOAT references; grid `gap` overrides both axis-specific gaps. Use numbers or FLOAT references for these scalar props, not CSS unit strings; the one exception is `lineHeight` and `letterSpacing`, which also take a percent of the font size such as `"150%"` that follows the size when it changes.
- References preserve real graph bindings, not just copied values. Set the intended collection mode on the parent before creating scalar-bound content: initial scalar layout resolves that inherited mode. This does not guarantee automatic scalar layout recomputation after a later mode switch. Verify resulting geometry as well as paint when changing modes. Missing or incorrectly typed scalar variables are errors.
- `bind` maps supported scene-field paths to variable IDs or references when no shorthand exists. Use semantic tokens consistently rather than declaring unused collections.
- Build repeated or computed content with JavaScript inside `{}` rather than writing each item out: `{days.map((day) => <Text>{day}</Text>)}`, `{Array.from({ length: 35 }, (_, i) => <Frame>…</Frame>)}`, and conditionals. Statements such as `const weeks = …` may come first and then end with `return` and the JSX, as a component's body does: `const weeks = 5` on one line, `return <Frame>…</Frame>` on the next.
diff --git a/packages/design-jsx/src/tree.ts b/packages/design-jsx/src/tree.ts
index fa4bd0aec..0fc7fae98 100644
--- a/packages/design-jsx/src/tree.ts
+++ b/packages/design-jsx/src/tree.ts
@@ -170,8 +170,10 @@ export type StyleProps = {
size?: number | DesignVariable
fontSize?: number | DesignVariable
- lineHeight?: number | 'auto' | DesignVariable
- letterSpacing?: number | DesignVariable
+ /** Pixels, or a percent of the font size such as `'150%'`. */
+ lineHeight?: number | `${number}%` | 'auto' | DesignVariable
+ /** Pixels, or a percent of the font size such as `'5%'`. */
+ letterSpacing?: number | `${number}%` | DesignVariable
font?: string
fontFamily?: string
weight?: number | 'bold' | 'medium' | 'normal'
diff --git a/packages/design-jsx/tests/export/text.test.ts b/packages/design-jsx/tests/export/text.test.ts
index 1d790f30c..7880370f4 100644
--- a/packages/design-jsx/tests/export/text.test.ts
+++ b/packages/design-jsx/tests/export/text.test.ts
@@ -4,6 +4,7 @@ import { designJSXElement, sceneNodeToJSX } from '#design-jsx/index'
import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
import { colorToFill } from '@open-pencil/scene-graph/color'
+import { percentLength, pixelLength } from '@open-pencil/scene-graph/text'
function exportText(fields: Partial<SceneNode>): string {
const graph = new SceneGraph()
@@ -56,8 +57,8 @@ describe('rich text export', () => {
fontFamily: 'Roboto',
fontWeight: 500,
italic: true,
- lineHeight: 30,
- letterSpacing: 1,
+ lineHeight: pixelLength(30),
+ letterSpacing: pixelLength(1),
textDecoration: 'STRIKETHROUGH'
}
},
@@ -113,10 +114,22 @@ describe('rich text export', () => {
)
})
+ test('writes a percent of the font size as a percent string', () => {
+ const code = exportText({
+ text: 'ab',
+ lineHeight: percentLength(150),
+ letterSpacing: percentLength(5),
+ styleRuns: [{ start: 1, length: 1, style: { letterSpacing: percentLength(-2) } }]
+ })
+ expect(code).toBe(
+ '<Text name="Note" color="#000000" lineHeight="150%" letterSpacing="5%">a<Span letterSpacing="-2%">b</Span></Text>'
+ )
+ })
+
test('writes auto line height and no fills in a span', () => {
const code = exportText({
text: 'ab',
- lineHeight: 20,
+ lineHeight: pixelLength(20),
styleRuns: [{ start: 1, length: 1, style: { lineHeight: null, fills: [] } }]
})
expect(code).toBe(
diff --git a/packages/design-jsx/tests/text-content.test.ts b/packages/design-jsx/tests/text-content.test.ts
index 40ea59fc9..0057e33e6 100644
--- a/packages/design-jsx/tests/text-content.test.ts
+++ b/packages/design-jsx/tests/text-content.test.ts
@@ -4,6 +4,7 @@ import { createDesignJSXRenderer } from '#design-jsx/index'
import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
import { colorToFill } from '@open-pencil/scene-graph/color'
+import { percentLength, pixelLength } from '@open-pencil/scene-graph/text'
const renderer = createDesignJSXRenderer<never>({
icon: () => Promise.resolve(null),
@@ -66,13 +67,27 @@ describe('Span', () => {
fontSize: 20,
fontWeight: 600,
italic: true,
- lineHeight: 30,
- letterSpacing: 1,
+ lineHeight: pixelLength(30),
+ letterSpacing: pixelLength(1),
textDecoration: 'UNDERLINE'
})
expect(warnings).toEqual([])
})
+ test('takes a line height and letter spacing as a percent of the font size', async () => {
+ const { node, warnings } = await renderText(
+ '<Text lineHeight="150%" letterSpacing="5%">a<Span letterSpacing="-2%">b</Span></Text>'
+ )
+ expect(node).toMatchObject({ lineHeight: percentLength(150), letterSpacing: percentLength(5) })
+ expect(node.styleRuns[0]?.style.letterSpacing).toEqual(percentLength(-2))
+ expect(warnings).toEqual([])
+ })
+
+ test('leaves out a line height or letter spacing it cannot read', async () => {
+ const { node } = await renderText('<Text lineHeight="tall" letterSpacing="wide">a</Text>')
+ expect(node).toMatchObject({ lineHeight: null, letterSpacing: percentLength(0) })
+ })
+
test('takes decoration details, auto lengths, and no fills', async () => {
const { node, warnings } = await renderText(
'<Text lineHeight={20} textDecoration="underline" textDecorationColor="#EE2222" textDecorationThickness={2}>a<Span lineHeight="auto" fills={[]} textDecorationStyle="wavy" textDecorationColor="currentColor" textDecorationThickness="auto" textUnderlineOffset={4} textDecorationSkipInk={false}>b</Span></Text>'
diff --git a/packages/docs/programmable/cli/scripting.md b/packages/docs/programmable/cli/scripting.md
index 89879a538..b425bf311 100644
--- a/packages/docs/programmable/cli/scripting.md
+++ b/packages/docs/programmable/cli/scripting.md
@@ -231,10 +231,10 @@ The API is intentionally close to Figma's Plugin API, but it maps to OpenPencil'
Common node properties are readable/writable through the proxy, including:
- Geometry: `x`, `y`, `width`, `height`, `rotation`, `resize(width, height)`
-- Appearance: `fills`, `strokes`, `effects`, `opacity`, `visible`, `locked`, `blendMode`, `clipsContent`
+- Appearance: `fills`, `strokes`, `effects`, `opacity`, `visible`, `locked`, `blendMode`, `clipsContent`. Paints take Figma's shape here, on page `backgrounds`, text ranges, and vector regions: a solid `color` is RGB with its alpha in `opacity`, and an image names `scaleMode`, `rotation`, and `scalingFactor`; a paint Figma refuses throws Figma's message
- Radius: `cornerRadius`, `topLeftRadius`, `topRightRadius`, `bottomRightRadius`, `bottomLeftRadius`
- Text: `characters`, `fontSize`, `fontName` (with `variationSettings`, every axis of a variable font), `fontWeight` (a variable font's `wght`), `fills`, `letterSpacing`, `lineHeight`, and `textDecoration`, which read `figma.mixed` while characters differ and restyle every character when set, and alignment
-- Text ranges: `getStyledTextSegments(fields, start?, end?)`, and `getRange…` / `setRange…` for `FontSize`, `FontName`, `Fills`, `LetterSpacing`, `LineHeight`, `TextDecoration` with its `Style`, `Offset`, `Thickness`, `Color`, and `SkipInk`, `TextCase`, `Hyperlink` (a `{ type: 'URL' | 'NODE', value }` link, or `null`), `TextStyleId` and `FillStyleId` (set with `setRangeTextStyleIdAsync` and `setRangeFillStyleIdAsync`, which give the range the style's fields), and `getRangeBoundVariable` / `setRangeBoundVariable` for the text fields Figma binds, plus `getRangeFontWeight`, `getRangeAllFontNames`, and `getRangeOpenTypeFeatures`. Lengths read in pixels; a percent given to a setter is of the font size
+- Text ranges: `getStyledTextSegments(fields, start?, end?)`, and `getRange…` / `setRange…` for `FontSize`, `FontName`, `Fills`, `LetterSpacing`, `LineHeight`, `TextDecoration` with its `Style`, `Offset`, `Thickness`, `Color`, and `SkipInk`, `TextCase`, `Hyperlink` (a `{ type: 'URL' | 'NODE', value }` link, or `null`), `TextStyleId` and `FillStyleId` (set with `setRangeTextStyleIdAsync` and `setRangeFillStyleIdAsync`, which give the range the style's fields), and `getRangeBoundVariable` / `setRangeBoundVariable` for the text fields Figma binds, plus `getRangeFontWeight`, `getRangeAllFontNames`, and `getRangeOpenTypeFeatures`. Line height and letter spacing keep the unit they are set in, pixels or a percent of the font size that follows the size, as in Figma; other lengths read in pixels, and a percent given to their setters is of the font size
- Text lists and paragraphs: `getRangeListOptions` / `setRangeListOptions` for bulleted (`UNORDERED`) and numbered (`ORDERED`) items, `getRangeIndentation` / `setRangeIndentation` for nesting (1–5 for list items), `listSpacing`, `paragraphSpacing`, and `paragraphIndent` for the whole text (`figma.mixed` when paragraphs differ) or per paragraph with `getRangeListSpacing` / `setRangeListSpacing`, `getRangeParagraphSpacing` / `setRangeParagraphSpacing`, and `getRangeParagraphIndent` / `setRangeParagraphIndent`, and `hangingList`
- Auto-layout: `layoutMode`, `primaryAxisAlignItems`, `counterAxisAlignItems`, `itemSpacing`, padding, sizing, and layout positioning fields
- Stroke helpers: `strokeWeight`, `strokeAlign`, `dashPattern`
diff --git a/packages/docs/reference/design-authoring.md b/packages/docs/reference/design-authoring.md
index 0963cc453..289b6c1db 100644
--- a/packages/docs/reference/design-authoring.md
+++ b/packages/docs/reference/design-authoring.md
@@ -36,7 +36,7 @@ This reference describes scene creation, not React DOM output. Use the `render`
## Variables and components
- Create document variables before referencing them with `designVar('id-or-name')`. `defineVars` groups references; it does not create variable collections.
-- COLOR references work in paint props. FLOAT references work in `w`, `h`, `gap`, padding, corner radii, `strokeWidth`, `opacity`, text `size`/`fontSize`, `lineHeight`, and `letterSpacing`. Grid `columnGap`/`rowGap` and wrapped flex `rowGap` also support FLOAT references; grid `gap` overrides both axis-specific gaps. Use numbers or FLOAT references for these scalar props, not CSS unit strings.
+- COLOR references work in paint props. FLOAT references work in `w`, `h`, `gap`, padding, corner radii, `strokeWidth`, `opacity`, text `size`/`fontSize`, `lineHeight`, and `letterSpacing`. Grid `columnGap`/`rowGap` and wrapped flex `rowGap` also support FLOAT references; grid `gap` overrides both axis-specific gaps. Use numbers or FLOAT references for these scalar props, not CSS unit strings; the one exception is `lineHeight` and `letterSpacing`, which also take a percent of the font size such as `"150%"` that follows the size when it changes.
- References preserve real graph bindings, not just copied values. Set the intended collection mode on the parent before creating scalar-bound content: initial scalar layout resolves that inherited mode. This does not guarantee automatic scalar layout recomputation after a later mode switch. Verify resulting geometry as well as paint when changing modes. Missing or incorrectly typed scalar variables are errors.
- `bind` maps supported scene-field paths to variable IDs or references when no shorthand exists. Use semantic tokens consistently rather than declaring unused collections.
- Build repeated or computed content with JavaScript inside `{}` rather than writing each item out: `{days.map((day) => <Text>{day}</Text>)}`, `{Array.from({ length: 35 }, (_, i) => <Frame>…</Frame>)}`, and conditionals. Statements such as `const weeks = …` may come first and then end with `return` and the JSX, as a component's body does: `const weeks = 5` on one line, `return <Frame>…</Frame>` on the next.
diff --git a/packages/docs/reference/dom-css-mapping.md b/packages/docs/reference/dom-css-mapping.md
index b979bf673..28a2e939b 100644
--- a/packages/docs/reference/dom-css-mapping.md
+++ b/packages/docs/reference/dom-css-mapping.md
@@ -42,8 +42,8 @@ OpenPencil maps browser-computed DOM/CSS styles into SceneGraph fields through `
| `font-size` | `fontSize` | Pixel/rem-ish numeric values. |
| `font-weight` | `fontWeight` | Numeric values. |
| `font-style: italic` | `italic` | Other styles ignored. |
-| `line-height` | `lineHeight` | Numeric computed values. |
-| `letter-spacing` | `letterSpacing` | Numeric computed values. |
+| `line-height` | `lineHeight` | Pixels stay pixels; a unitless multiple or a percent becomes a percent of the font size, which export writes back as a unitless multiple. |
+| `letter-spacing` | `letterSpacing` | Pixels stay pixels; `em` becomes a percent of the font size, which export writes back in `em`. |
| `text-align` | horizontal text alignment | Supports center, right, justified; defaults left. |
| `text-decoration-line` | underline / strikethrough | Decoration style/thickness are not mapped yet. |
| `text-transform` | `textCase` | Uppercase, lowercase, and capitalize map to SceneGraph text case. |
diff --git a/packages/dom-css/src/export/css.ts b/packages/dom-css/src/export/css.ts
index 1b2c56713..fab09d858 100644
--- a/packages/dom-css/src/export/css.ts
+++ b/packages/dom-css/src/export/css.ts
@@ -1,4 +1,4 @@
-import type { Effect, Fill, Stroke } from '@open-pencil/scene-graph'
+import type { Effect, Fill, Stroke, TextLength } from '@open-pencil/scene-graph'
import { colorToCSS, colorToHex } from '@open-pencil/scene-graph/color'
import type { Color } from '@open-pencil/scene-graph/primitives'
@@ -44,3 +44,13 @@ export function effectsToCSS(effects: Effect[]): DesignStyleDeclaration {
}
return style
}
+
+/** A line height as CSS writes it: a percent as the unitless multiple that follows the font size. */
+export function lineHeightToCSS(length: TextLength): string {
+ return length.unit === 'PIXELS' ? `${length.value}px` : String(length.value / 100)
+}
+
+/** A letter spacing as CSS writes it: a percent of the font size in `em`. */
+export function letterSpacingToCSS(length: TextLength): string {
+ return length.unit === 'PIXELS' ? `${length.value}px` : `${length.value / 100}em`
+}
diff --git a/packages/dom-css/src/export/projection.ts b/packages/dom-css/src/export/projection.ts
index 2cb6d502d..c53a705d9 100644
--- a/packages/dom-css/src/export/projection.ts
+++ b/packages/dom-css/src/export/projection.ts
@@ -10,7 +10,15 @@ import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text/directio
import { DesignTokens, type CSSModes } from '../tokens/references'
import type { DesignDocument, DesignElement, DesignNode, DesignStyleDeclaration } from '../types'
-import { cssColor, dropShadowToCSS, effectsToCSS, fillToCSS, strokeColorToCSS } from './css'
+import {
+ cssColor,
+ dropShadowToCSS,
+ effectsToCSS,
+ fillToCSS,
+ letterSpacingToCSS,
+ lineHeightToCSS,
+ strokeColorToCSS
+} from './css'
import { addGridContainer, addGridPlacement } from './grid'
import { textCaseToCSS, textElementContent } from './text'
@@ -357,9 +365,12 @@ function styleFromTextNode(
style['font-size'] = css('fontSize', px(node.fontSize))
style['font-weight'] = String(node.fontWeight)
if (node.italic) style['font-style'] = 'italic'
- if (node.lineHeight !== null) style['line-height'] = css('lineHeight', px(node.lineHeight))
- if (node.letterSpacing !== 0)
- style['letter-spacing'] = css('letterSpacing', px(node.letterSpacing))
+ if (node.lineHeight !== null) {
+ style['line-height'] = css('lineHeight', lineHeightToCSS(node.lineHeight))
+ }
+ if (node.letterSpacing.value !== 0) {
+ style['letter-spacing'] = css('letterSpacing', letterSpacingToCSS(node.letterSpacing))
+ }
if (node.textAlignHorizontal !== 'LEFT')
style['text-align'] = node.textAlignHorizontal.toLowerCase()
if (node.opacity < 1) style.opacity = css('opacity', String(node.opacity))
diff --git a/packages/dom-css/src/export/text.ts b/packages/dom-css/src/export/text.ts
index e7c727545..ba02620a2 100644
--- a/packages/dom-css/src/export/text.ts
+++ b/packages/dom-css/src/export/text.ts
@@ -13,7 +13,7 @@ import {
} from '@open-pencil/scene-graph/text'
import type { DesignElement, DesignNode, DesignStyleDeclaration } from '../types'
-import { fillToCSS } from './css'
+import { fillToCSS, letterSpacingToCSS, lineHeightToCSS } from './css'
/** The character styles CSS writes, as a text layer and its runs hold them. */
type CharacterStyle = Pick<
@@ -155,8 +155,8 @@ function characterCSS(style: CharacterStyle, decorated: boolean): DesignStyleDec
'font-size': px(style.fontSize),
'font-weight': String(style.fontWeight),
'font-style': style.italic ? 'italic' : 'normal',
- 'letter-spacing': px(style.letterSpacing),
- 'line-height': style.lineHeight === null ? 'normal' : px(style.lineHeight),
+ 'letter-spacing': letterSpacingToCSS(style.letterSpacing),
+ 'line-height': style.lineHeight === null ? 'normal' : lineHeightToCSS(style.lineHeight),
'text-transform': textCaseToCSS(style.textCase) ?? 'none',
...(decorated ? decorationCSS(style) : {})
}
diff --git a/packages/dom-css/src/import/text.ts b/packages/dom-css/src/import/text.ts
index 13088af91..53f29e2d7 100644
--- a/packages/dom-css/src/import/text.ts
+++ b/packages/dom-css/src/import/text.ts
@@ -8,7 +8,12 @@ import type {
StyleRun,
TextParagraphStyle
} from '@open-pencil/scene-graph'
-import { parseCSSColor, parseCSSNumber } from '@open-pencil/scene-graph/css'
+import {
+ parseCSSColor,
+ parseCSSLetterSpacing,
+ parseCSSLineHeight,
+ parseCSSNumber
+} from '@open-pencil/scene-graph/css'
import type { DesignElement, DesignNode, DesignStyleDeclaration } from '../types'
import { colorToFillFromCSS, mergedStyle, pickStyle } from './css-values'
@@ -111,14 +116,16 @@ export function characterStyleFromCSS(
const line = pickStyle(style, 'text-decoration-line')
const fontStyle = pickStyle(style, 'font-style')
const lineHeight = pickStyle(style, 'line-height')
+ // `normal` is automatic, a null; a value CSS writes some other way keeps the base.
+ const parsedLineHeight = parseCSSLineHeight(lineHeight)
const textTransform = pickStyle(style, 'text-transform')
return {
fontFamily: family || base.fontFamily,
fontSize: parseCSSNumber(pickStyle(style, 'font-size')) ?? base.fontSize,
fontWeight: parseCSSNumber(pickStyle(style, 'font-weight')) ?? base.fontWeight,
italic: fontStyle === undefined ? base.italic : fontStyle === 'italic',
- letterSpacing: pixels(pickStyle(style, 'letter-spacing')) ?? base.letterSpacing,
- lineHeight: lineHeight === 'normal' ? null : (pixels(lineHeight) ?? base.lineHeight),
+ letterSpacing: parseCSSLetterSpacing(pickStyle(style, 'letter-spacing')) ?? base.letterSpacing,
+ lineHeight: parsedLineHeight === undefined ? base.lineHeight : parsedLineHeight,
fills: fills.length > 0 ? fills : base.fills,
textDecoration: line === undefined ? base.textDecoration : decorationLine(line),
textDecorationStyle:
diff --git a/packages/dom-css/tests/import/conversion.test.ts b/packages/dom-css/tests/import/conversion.test.ts
index 817882dc6..e114ecc39 100644
--- a/packages/dom-css/tests/import/conversion.test.ts
+++ b/packages/dom-css/tests/import/conversion.test.ts
@@ -8,6 +8,7 @@ import type { DesignElement, DesignNode } from '#dom-css/index'
import { createHeadlessCSSRuntime, htmlToDesignDocument, htmlToSceneGraph } from '#dom-css/index'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import { pixelLength } from '@open-pencil/scene-graph/text'
import { TEST_COLORS, cardCSS, cardHTML, fixtureCSS, fixtureHTML } from '../helpers'
@@ -107,8 +108,8 @@ function expectStyleRoundTripText(graph: SceneGraph, panel: SceneNode) {
const heading = expectText(graph.getChildren(panel.id)[0])
expect(heading.fontSize).toBe(18)
expect(heading.fontWeight).toBe(700)
- expect(heading.lineHeight).toBe(24)
- expect(heading.letterSpacing).toBe(0.2)
+ expect(heading.lineHeight).toEqual(pixelLength(24))
+ expect(heading.letterSpacing).toEqual(pixelLength(0.2))
expect(heading.textAlignHorizontal).toBe('CENTER')
expect(heading.textCase).toBe('UPPER')
expect(heading.maxLines).toBe(1)
diff --git a/packages/dom-css/tests/import/text.test.ts b/packages/dom-css/tests/import/text.test.ts
index ec7245b23..e05804e8e 100644
--- a/packages/dom-css/tests/import/text.test.ts
+++ b/packages/dom-css/tests/import/text.test.ts
@@ -6,7 +6,12 @@ import { designDocumentToSceneGraph } from '#dom-css/import/scene-graph'
import { createHeadlessCSSRuntime, htmlToDesignDocument } from '#dom-css/index'
import { SceneGraph, type SceneNode, type TextParagraphStyle } from '@open-pencil/scene-graph'
-import { paragraphSpacingAt, textParagraphRanges } from '@open-pencil/scene-graph/text'
+import {
+ paragraphSpacingAt,
+ percentLength,
+ pixelLength,
+ textParagraphRanges
+} from '@open-pencil/scene-graph/text'
async function texts(html: string): Promise<SceneNode[]> {
const document = await htmlToDesignDocument(html, { runtime: createHeadlessCSSRuntime() })
@@ -190,3 +195,32 @@ describe('rich text import', () => {
expect(back?.styleRuns).toEqual(styleRuns)
})
})
+
+// CSS keeps a line height relative as a unitless multiple and letter spacing in em, so a percent
+// of the font size survives the trip, as it does in Figma.
+describe('relative text lengths', () => {
+ test('a unitless or percent line height and an em letter spacing read as percents', async () => {
+ const [unitless, percent] = await texts(
+ '<p style="font-size:20px;line-height:1.5;letter-spacing:0.1em">One</p>' +
+ '<p style="font-size:20px;line-height:120%;letter-spacing:2px">Two</p>'
+ )
+ expect(unitless).toMatchObject({
+ lineHeight: percentLength(150),
+ letterSpacing: percentLength(10)
+ })
+ expect(percent).toMatchObject({ lineHeight: percentLength(120), letterSpacing: pixelLength(2) })
+ })
+
+ test('reads back the percents it writes, for the text and its runs', async () => {
+ const { back } = await roundTrip({
+ text: 'Hello world',
+ lineHeight: percentLength(150),
+ letterSpacing: percentLength(5),
+ styleRuns: [
+ { start: 6, length: 5, style: { fontWeight: 700, letterSpacing: pixelLength(1) } }
+ ]
+ })
+ expect(back).toMatchObject({ lineHeight: percentLength(150), letterSpacing: percentLength(5) })
+ expect(back.styleRuns.at(-1)?.style.letterSpacing).toEqual(pixelLength(1))
+ })
+})
diff --git a/packages/fig/src/node-change/convert.ts b/packages/fig/src/node-change/convert.ts
index 0b056c137..3b965e41d 100644
--- a/packages/fig/src/node-change/convert.ts
+++ b/packages/fig/src/node-change/convert.ts
@@ -12,6 +12,7 @@ import { createDefaultSourceMetadata } from '@open-pencil/scene-graph/node-defau
import { OPEN_PENCIL_PLUGIN_DATA } from '@open-pencil/scene-graph/plugin-data'
import { POINT_COUNT_RANGE } from '@open-pencil/scene-graph/polygon'
import { isShapeWithTextType } from '@open-pencil/scene-graph/shape-with-text'
+import { pixelLength } from '@open-pencil/scene-graph/text'
import { parseVariantName } from '@open-pencil/scene-graph/variant-name'
/* eslint-disable max-lines -- kiwi↔scene conversion helpers are tightly coupled */
@@ -50,12 +51,19 @@ import { decodeVectorNetworkBlob, textPathStartSegment, type StyleOverride } fro
export { convertEffects, convertFills, convertStrokes, setVariableColorResolver } from './paint'
export { importStyleRuns } from './style/runs'
-export { convertLetterSpacing, convertLineHeight, mapTextDecoration } from './text/values'
+export {
+ convertLetterSpacing,
+ convertLineHeight,
+ figmaLetterSpacing,
+ figmaLineHeight,
+ mapTextDecoration
+} from './text/values'
export { resolveGeometryPaths } from './vector/geometry'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import type {
SceneNode,
+ TextLength,
NodeType,
Fill,
StrokeCap,
@@ -326,7 +334,7 @@ function convertPolygonProps(
* larger of its line height and its tallest font's height, so a first line shorter than the
* text's height in pixels was laid out at another one, which a style the text uses set.
*/
-function importedTextLineHeight(nc: NodeChange): number | null {
+function importedTextLineHeight(nc: NodeChange): TextLength | null {
if (!nc.lineHeight || isFigmaAutoLineHeight(nc.lineHeight)) return null
const derivedLineHeight = nc.derivedTextData?.baselines?.[0]?.lineHeight
if (
@@ -335,8 +343,8 @@ function importedTextLineHeight(nc: NodeChange): number | null {
Number.isFinite(derivedLineHeight) &&
derivedLineHeight < nc.lineHeight.value
)
- return derivedLineHeight
- return convertLineHeight(nc.lineHeight, nc.fontSize)
+ return pixelLength(derivedLineHeight)
+ return convertLineHeight(nc.lineHeight)
}
type TextProps = Pick<
@@ -448,7 +456,7 @@ function convertTextProps(nc: NodeChange, blobs: Uint8Array[]): TextProps {
...convertTextDecorationProps(nc),
leadingTrim: (nc.leadingTrim ?? 'NONE') as SceneNode['leadingTrim'],
lineHeight: importedTextLineHeight(nc),
- letterSpacing: convertLetterSpacing(nc.letterSpacing, nc.fontSize),
+ letterSpacing: convertLetterSpacing(nc.letterSpacing),
maxLines: (nc.maxLines ?? null) as number | null,
...convertParagraphProps(nc),
styleRuns: importStyleRuns(nc),
diff --git a/packages/fig/src/node-change/derived-text/build.ts b/packages/fig/src/node-change/derived-text/build.ts
index 397b1808b..d9433ca07 100644
--- a/packages/fig/src/node-change/derived-text/build.ts
+++ b/packages/fig/src/node-change/derived-text/build.ts
@@ -3,7 +3,12 @@ import { groupBy } from 'es-toolkit/array'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import type { DerivedTextGlyph, SceneNode } from '@open-pencil/scene-graph'
import { normalizeFontFamily, weightToStyle } from '@open-pencil/scene-graph/font-style'
-import { hasTextList, paragraphIndexAt, textParagraphRanges } from '@open-pencil/scene-graph/text'
+import {
+ hasTextList,
+ lineHeightPixels,
+ paragraphIndexAt,
+ textParagraphRanges
+} from '@open-pencil/scene-graph/text'
import { bytesToHex } from '../bytes'
import type { PlacedTextGlyph, TextDecorationRecord } from '../export/runtime'
@@ -162,7 +167,8 @@ function savedGlyphLayout(
node: SceneNode,
glyphs: DerivedTextGlyph[]
): Pick<ShapedText, 'baselines' | 'logicalIndexToCharacterOffsetMap'> {
- const lineHeight = node.lineHeight ?? Math.ceil(node.fontSize * 1.2)
+ const lineHeight =
+ lineHeightPixels(node.lineHeight, node.fontSize) ?? Math.ceil(node.fontSize * 1.2)
const offsets = Array.from({ length: node.text.length }, () => 0)
const characters = savedGlyphCharacters(node, glyphs)
const lines = savedGlyphLines(
diff --git a/packages/fig/src/node-change/serialize.ts b/packages/fig/src/node-change/serialize.ts
index 6846f9b06..53198f5e3 100644
--- a/packages/fig/src/node-change/serialize.ts
+++ b/packages/fig/src/node-change/serialize.ts
@@ -27,7 +27,7 @@ import { applyFontFeaturesToKiwi } from './font/features'
import { weightToFigmaStyle } from './font/style'
import { fillToKiwiPaint, safeColor } from './paint'
import { exportTextData, fontVariationToKiwi } from './text/data-export'
-import { FIGMA_AUTO_LINE_HEIGHT } from './text/values'
+import { figmaLetterSpacing, figmaLineHeight } from './text/values'
import {
exportedVariableConsumptionEntries,
mergeVariableConsumptionMaps
@@ -133,11 +133,8 @@ function serializeTextProps(
})
}
if (node.leadingTrim !== 'NONE') nc.leadingTrim = node.leadingTrim
- nc.lineHeight =
- node.lineHeight === null
- ? { ...FIGMA_AUTO_LINE_HEIGHT }
- : { value: node.lineHeight, units: 'PIXELS' }
- nc.letterSpacing = { value: node.letterSpacing, units: 'PIXELS' }
+ nc.lineHeight = figmaLineHeight(node.lineHeight)
+ nc.letterSpacing = figmaLetterSpacing(node.letterSpacing)
if (node.textDecoration !== 'NONE') {
nc.textDecoration = node.textDecoration === 'UNDERLINE' ? 'UNDERLINE' : 'STRIKETHROUGH'
}
diff --git a/packages/fig/src/node-change/style/runs.ts b/packages/fig/src/node-change/style/runs.ts
index ee79d881a..5231f27a8 100644
--- a/packages/fig/src/node-change/style/runs.ts
+++ b/packages/fig/src/node-change/style/runs.ts
@@ -72,7 +72,6 @@ function applyTextDecorationOverride(style: CharacterStyleOverride, override: No
}
function convertStyleOverride(override: NodeChange, text: NodeChange): CharacterStyleOverride {
- const fallbackFontSize = text.fontSize
const style: CharacterStyleOverride = {}
if (override.fontName) {
style.fontFamily = override.fontName.family
@@ -84,15 +83,10 @@ function convertStyleOverride(override: NodeChange, text: NodeChange): Character
if (fontVariations.length > 0) style.fontVariations = fontVariations
const fontFeatures = convertFontFeatures(override)
if (fontFeatures.length > 0) style.fontFeatures = fontFeatures
- if (override.letterSpacing) {
- style.letterSpacing = convertLetterSpacing(
- override.letterSpacing,
- override.fontSize ?? fallbackFontSize
- )
- }
+ if (override.letterSpacing) style.letterSpacing = convertLetterSpacing(override.letterSpacing)
if (override.lineHeight) {
// A run in auto lines up at its own font's height, even in text with a fixed one.
- style.lineHeight = convertLineHeight(override.lineHeight, override.fontSize ?? fallbackFontSize)
+ style.lineHeight = convertLineHeight(override.lineHeight)
}
applyTextDecorationOverride(style, override)
if (override.fillPaints) {
diff --git a/packages/fig/src/node-change/text/data-export.ts b/packages/fig/src/node-change/text/data-export.ts
index 7dad66958..83b47ba11 100644
--- a/packages/fig/src/node-change/text/data-export.ts
+++ b/packages/fig/src/node-change/text/data-export.ts
@@ -6,7 +6,7 @@ import { applyFontFeaturesToKiwi } from '../font/features'
import { weightToFigmaStyle } from '../font/style'
import { stringToFigmaAxisTag } from '../font/variations'
import { exportTextLines } from './lines'
-import { FIGMA_AUTO_LINE_HEIGHT } from './values'
+import { figmaLetterSpacing, figmaLineHeight } from './values'
export function fontVariationToKiwi(variation: SceneNode['fontVariations'][number]) {
const axisTag = stringToFigmaAxisTag(variation.axis)
@@ -57,14 +57,9 @@ function textStyleOverrideToKiwi(
applyFontFeaturesToKiwi(override as NodeChange, style.fontFeatures)
}
if (style.letterSpacing !== undefined) {
- override.letterSpacing = { value: style.letterSpacing, units: 'PIXELS' }
- }
- if (style.lineHeight !== undefined) {
- override.lineHeight =
- style.lineHeight === null
- ? { ...FIGMA_AUTO_LINE_HEIGHT }
- : { value: style.lineHeight, units: 'PIXELS' }
+ override.letterSpacing = figmaLetterSpacing(style.letterSpacing)
}
+ if (style.lineHeight !== undefined) override.lineHeight = figmaLineHeight(style.lineHeight)
applyTextDecorationOverrideFields(override, style, fillToKiwiPaint)
if (style.textCase) override.textCase = style.textCase
if (style.fills && style.fills.length > 0) {
diff --git a/packages/fig/src/node-change/text/values.ts b/packages/fig/src/node-change/text/values.ts
index b20a8b4dc..5c41099b5 100644
--- a/packages/fig/src/node-change/text/values.ts
+++ b/packages/fig/src/node-change/text/values.ts
@@ -1,4 +1,5 @@
-import type { TextDecoration } from '@open-pencil/scene-graph'
+import type { TextDecoration, TextLength } from '@open-pencil/scene-graph'
+import { NO_LETTER_SPACING, percentLength, pixelLength } from '@open-pencil/scene-graph/text'
export function mapTextDecoration(d?: string): TextDecoration {
switch (d) {
@@ -18,23 +19,33 @@ export function isFigmaAutoLineHeight(lh?: { value: number; units: string }): bo
return lh?.units === FIGMA_AUTO_LINE_HEIGHT.units && lh.value === FIGMA_AUTO_LINE_HEIGHT.value
}
-export function convertLineHeight(
- lh?: { value: number; units: string },
- fontSize?: number
-): number | null {
+/**
+ * A line height as the scene keeps it: null for auto, pixels as pixels, and a percent or the
+ * multiplier Figma writes for one as a percent, so it follows the font size as in Figma.
+ */
+export function convertLineHeight(lh?: { value: number; units: string }): TextLength | null {
if (!lh || isFigmaAutoLineHeight(lh)) return null
- if (lh.units === 'PIXELS') return lh.value
- if (lh.units === 'PERCENT') return (lh.value / 100) * (fontSize ?? 14)
- if (lh.units === 'RAW') return lh.value * (fontSize ?? 14)
+ if (lh.units === 'PIXELS') return pixelLength(lh.value)
+ if (lh.units === 'PERCENT') return percentLength(lh.value)
+ if (lh.units === 'RAW') return percentLength(lh.value * 100)
return null
}
-export function convertLetterSpacing(
- ls?: { value: number; units: string },
- fontSize?: number
-): number {
- if (!ls) return 0
- if (ls.units === 'PIXELS') return ls.value
- if (ls.units === 'PERCENT') return (ls.value / 100) * (fontSize ?? 14)
- return ls.value
+/** A letter spacing as the scene keeps it, in pixels or a percent of the font size. */
+export function convertLetterSpacing(ls?: { value: number; units: string }): TextLength {
+ if (!ls) return NO_LETTER_SPACING
+ return ls.units === 'PIXELS' ? pixelLength(ls.value) : percentLength(ls.value)
+}
+
+/** A line height as Figma writes it: auto as 100 percent, and a percent as a `RAW` multiplier. */
+export function figmaLineHeight(lineHeight: TextLength | null): { value: number; units: string } {
+ if (!lineHeight) return { ...FIGMA_AUTO_LINE_HEIGHT }
+ return lineHeight.unit === 'PIXELS'
+ ? { value: lineHeight.value, units: 'PIXELS' }
+ : { value: lineHeight.value / 100, units: 'RAW' }
+}
+
+/** A letter spacing as Figma writes it. */
+export function figmaLetterSpacing(letterSpacing: TextLength): { value: number; units: string } {
+ return { value: letterSpacing.value, units: letterSpacing.unit }
}
diff --git a/packages/fig/tests/instance-overrides/style-claims.test.ts b/packages/fig/tests/instance-overrides/style-claims.test.ts
index 1a004a864..0b3fe4f73 100644
--- a/packages/fig/tests/instance-overrides/style-claims.test.ts
+++ b/packages/fig/tests/instance-overrides/style-claims.test.ts
@@ -9,6 +9,7 @@ import { mapInstanceSourceChildren } from '#fig/instance-overrides/source-childr
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import { SceneGraph } from '@open-pencil/scene-graph'
import { copyStyleRuns } from '@open-pencil/scene-graph/copy'
+import { pixelLength } from '@open-pencil/scene-graph/text'
test('style claims read from a file survive edits to the component, as in Figma', () => {
const changes: NodeChange[] = [
@@ -56,7 +57,11 @@ test('style claims read from a file survive edits to the component, as in Figma'
if (!component) throw new Error('Missing component')
const [rect, text] = graph.getChildren(component.materialized.root.id)
graph.updateNode(rect.id, { cornerRadius: 4, strokeWeight: 2, strokeAlign: 'OUTSIDE' })
- graph.updateNode(text.id, { fontWeight: 300, lineHeight: 24, letterSpacing: 1 })
+ graph.updateNode(text.id, {
+ fontWeight: 300,
+ lineHeight: pixelLength(24),
+ letterSpacing: pixelLength(1)
+ })
graph.syncInstances(component.materialized.root.id)
const [copyRect, copyText] = graph.getChildren(result.root.id)
@@ -65,7 +70,11 @@ test('style claims read from a file survive edits to the component, as in Figma'
3,
'OUTSIDE'
])
- expect([copyText.fontWeight, copyText.lineHeight, copyText.letterSpacing]).toEqual([700, 32, 1])
+ expect([copyText.fontWeight, copyText.lineHeight, copyText.letterSpacing]).toEqual([
+ 700,
+ pixelLength(32),
+ pixelLength(1)
+ ])
})
test('styled ranges claimed with the characters stay when the component restyles its text', () => {
diff --git a/packages/fig/tests/node-change/export.test.ts b/packages/fig/tests/node-change/export.test.ts
index 47bfc9777..43ef7fbac 100644
--- a/packages/fig/tests/node-change/export.test.ts
+++ b/packages/fig/tests/node-change/export.test.ts
@@ -13,6 +13,7 @@ import {
import { SceneGraph } from '@open-pencil/scene-graph'
import { fractionalPosition } from '@open-pencil/scene-graph/order-keys'
import type { GUID } from '@open-pencil/scene-graph/primitives'
+import { percentLength, pixelLength } from '@open-pencil/scene-graph/text'
describe('@open-pencil/fig SceneGraph export policy', () => {
test('maps node types deterministically', () => {
@@ -115,6 +116,24 @@ describe('@open-pencil/fig SceneGraph export policy', () => {
])
})
+ // Recorded in Figma 126's clipboard: 150% line height as RAW 1.5, 10% letter spacing as PERCENT.
+ test('writes percent lengths as Figma does, on the text and its ranges', () => {
+ const graph = new SceneGraph()
+ const text = graph.createNode('TEXT', graph.getPages()[0].id, {
+ text: 'Hello',
+ fontSize: 20,
+ lineHeight: percentLength(150),
+ letterSpacing: percentLength(10),
+ styleRuns: [{ start: 0, length: 2, style: { lineHeight: pixelLength(30) } }]
+ })
+ const [change] = sceneNodeToKiwi(text, { sessionID: 1, localID: 1 }, 0, { value: 2 }, graph, [])
+ expect(change.lineHeight).toEqual({ value: 1.5, units: 'RAW' })
+ expect(change.letterSpacing).toEqual({ value: 10, units: 'PERCENT' })
+ expect(change.textData?.styleOverrideTable).toEqual([
+ expect.objectContaining({ lineHeight: { value: 30, units: 'PIXELS' } })
+ ])
+ })
+
test('writes styled ranges with the characters of a text claim, as Figma does', () => {
const graph = new SceneGraph()
const page = graph.getPages()[0]
@@ -158,13 +177,17 @@ describe('@open-pencil/fig SceneGraph export policy', () => {
const page = graph.getPages()[0]
const component = graph.createNode('COMPONENT', page.id)
graph.createNode('RECTANGLE', component.id, { overrideKey: '2:20', strokeWeight: 2 })
- graph.createNode('TEXT', component.id, { overrideKey: '2:21', text: 'A', lineHeight: 30 })
+ graph.createNode('TEXT', component.id, {
+ overrideKey: '2:21',
+ text: 'A',
+ lineHeight: pixelLength(30)
+ })
const instance = expectDefined(graph.createInstance(component.id, page.id), 'instance')
const [rect, text] = graph.getChildren(instance.id)
// Placed at twice the component's size, as a scaled instance is.
graph.updateNode(instance.id, { componentScale: 2 })
graph.updateNode(rect.id, { strokeWeight: 8, strokeAlign: 'CENTER', cornerSmoothing: 0.6 })
- graph.updateNode(text.id, { lineHeight: null, letterSpacing: 4 })
+ graph.updateNode(text.id, { lineHeight: null, letterSpacing: pixelLength(4) })
graph.updateNode(instance.id, {
instanceOverrides: {
self: new Map(),
@@ -181,7 +204,7 @@ describe('@open-pencil/fig SceneGraph export policy', () => {
text.id,
new Map<string, unknown>([
['lineHeight', null],
- ['letterSpacing', 4]
+ ['letterSpacing', pixelLength(4)]
])
]
])
diff --git a/packages/fig/tests/node-change/generated/shape-with-text.test.ts b/packages/fig/tests/node-change/generated/shape-with-text.test.ts
index 259744ba0..c7fee73b0 100644
--- a/packages/fig/tests/node-change/generated/shape-with-text.test.ts
+++ b/packages/fig/tests/node-change/generated/shape-with-text.test.ts
@@ -11,6 +11,7 @@ import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { createShapeWithText, shapeWithTextLabel } from '@open-pencil/scene-graph/generated'
import type { Color } from '@open-pencil/scene-graph/primitives'
import { shapeWithTextLabelBox } from '@open-pencil/scene-graph/shape-with-text'
+import { percentLength } from '@open-pencil/scene-graph/text'
const guid = (localID: number) => ({ sessionID: 0, localID })
const slot = (localID: number) => ({ guids: [{ sessionID: 40_000_000, localID }] })
@@ -94,7 +95,7 @@ describe('shapes with text', () => {
fontFamily: 'Inter',
fontWeight: 500,
fontSize: 24,
- lineHeight: 36,
+ lineHeight: percentLength(150),
textAutoResize: 'HEIGHT'
})
expect(label.fills[0]).toMatchObject({ color: black })
diff --git a/packages/fig/tests/node-change/generated/sticky.test.ts b/packages/fig/tests/node-change/generated/sticky.test.ts
index 2d9225fb8..c75fb5bf6 100644
--- a/packages/fig/tests/node-change/generated/sticky.test.ts
+++ b/packages/fig/tests/node-change/generated/sticky.test.ts
@@ -9,6 +9,7 @@ import { materializeDocument } from '@open-pencil/fig'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { createSticky, stickySublayers, STICKY_COLORS } from '@open-pencil/scene-graph/generated'
+import { percentLength, pixelLength } from '@open-pencil/scene-graph/text'
const guid = (localID: number) => ({ sessionID: 0, localID })
const slot = (localID: number) => ({ guids: [{ sessionID: 40_000_000, localID }] })
@@ -88,7 +89,7 @@ describe('sticky notes', () => {
fontFamily: 'Inter',
fontWeight: 500,
fontSize: 24,
- lineHeight: 36,
+ lineHeight: percentLength(150),
x: 30,
y: 30,
width: 300,
@@ -134,8 +135,13 @@ describe('sticky notes', () => {
expect(sticky.fills[0]?.color).toEqual(STICKY_COLORS.yellow)
expect(sticky.effects).toHaveLength(3)
const { body, author } = expectDefined(stickySublayers(reread, sticky))
- expect(body).toMatchObject({ text: 'Hello', fontSize: 16, lineHeight: 24 })
- expect(author).toMatchObject({ text: 'Grace', fontSize: 12, lineHeight: 16, visible: true })
+ expect(body).toMatchObject({ text: 'Hello', fontSize: 16, lineHeight: percentLength(150) })
+ expect(author).toMatchObject({
+ text: 'Grace',
+ fontSize: 12,
+ lineHeight: pixelLength(16),
+ visible: true
+ })
expect(sticky).toMatchObject({ paddingLeft: 20, itemSpacing: 16, minHeight: 240 })
})
diff --git a/packages/fig/tests/node-change/index.test.ts b/packages/fig/tests/node-change/index.test.ts
index 00b99e456..ba4fec3ae 100644
--- a/packages/fig/tests/node-change/index.test.ts
+++ b/packages/fig/tests/node-change/index.test.ts
@@ -28,6 +28,7 @@ import {
import { SceneGraph } from '@open-pencil/scene-graph'
import { getWorldMatrix } from '@open-pencil/scene-graph/coordinate'
import TransformMatrix from '@open-pencil/scene-graph/matrix'
+import { percentLength, pixelLength } from '@open-pencil/scene-graph/text'
describe('@open-pencil/fig NodeChange policy', () => {
test('keeps raw LINE endpoints through reflected parents and exports authored origin pivots', () => {
@@ -106,8 +107,11 @@ describe('@open-pencil/fig NodeChange policy', () => {
})
test('converts normalized text values', () => {
- expect(convertLineHeight({ value: 120, units: 'PERCENT' }, 20)).toBe(24)
- expect(convertLetterSpacing({ value: 10, units: 'PERCENT' }, 20)).toBe(2)
+ // A percent stays one, and Figma's RAW multiplier is a percent too.
+ expect(convertLineHeight({ value: 120, units: 'PERCENT' })).toEqual(percentLength(120))
+ expect(convertLineHeight({ value: 1.5, units: 'RAW' })).toEqual(percentLength(150))
+ expect(convertLineHeight({ value: 24, units: 'PIXELS' })).toEqual(pixelLength(24))
+ expect(convertLetterSpacing({ value: 10, units: 'PERCENT' })).toEqual(percentLength(10))
expect(mapTextDecoration('UNDERLINE')).toBe('UNDERLINE')
})
diff --git a/packages/pen/src/text.ts b/packages/pen/src/text.ts
index 8b00b8059..50fa7cec4 100644
--- a/packages/pen/src/text.ts
+++ b/packages/pen/src/text.ts
@@ -1,4 +1,5 @@
import type { SceneNode, TextAlignVertical, TextAutoResize } from '@open-pencil/scene-graph'
+import { percentLength, pixelLength } from '@open-pencil/scene-graph/text'
import type { PenNode } from './schema'
import { bindIfVar, isVarRef, resolveNumber, resolveString, type VarContext } from './variables'
@@ -67,10 +68,13 @@ export function applyTextProps(node: SceneNode, pen: PenNode, ctx: VarContext):
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)
+ // pen.dev's line height multiplies the font size, so it follows the size as a percent.
+ if (pen.lineHeight !== undefined) {
+ node.lineHeight = percentLength(resolveNumber(pen.lineHeight, ctx) * 100)
+ }
+ if (pen.letterSpacing !== undefined) {
+ node.letterSpacing = pixelLength(resolveNumber(pen.letterSpacing, ctx))
+ }
node.textAutoResize = TEXT_GROWTH[pen.textGrowth ?? 'auto'] ?? 'WIDTH_AND_HEIGHT'
// pen.dev draws every font at its default optical size, whatever the text's size.
node.opticalSizeFromFontSize = false
diff --git a/packages/pen/tests/text.test.ts b/packages/pen/tests/text.test.ts
index bd781cbad..970c166c8 100644
--- a/packages/pen/tests/text.test.ts
+++ b/packages/pen/tests/text.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, test } from 'bun:test'
import type { PenDocument, PenNode } from '@open-pencil/pen'
+import { percentLength } from '@open-pencil/scene-graph/text'
import { getNodeOrThrow } from './helpers/assert'
import { parseDocument } from './helpers/document'
@@ -52,9 +53,10 @@ describe('parsePenFile — text', () => {
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)
+ // A multiple of the font size follows it, as a percent does.
+ test('reads the line height as a multiple of the font size', () => {
+ expect(textOf({ fontSize: 28, lineHeight: 2 }).lineHeight).toEqual(percentLength(200))
+ expect(textOf({ fontSize: 10, lineHeight: 6 }).lineHeight).toEqual(percentLength(600))
})
test('keeps every font at its default optical size, as pen.dev draws it', () => {
diff --git a/packages/scene-graph/AGENTS.md b/packages/scene-graph/AGENTS.md
index 09dc8e5b9..3bc16e005 100644
--- a/packages/scene-graph/AGENTS.md
+++ b/packages/scene-graph/AGENTS.md
@@ -18,6 +18,7 @@ Framework-neutral document model. Owns node types, primitives, geometry, matrice
- `componentScale` records an occurrence's coordinates relative to its component definition. Shared rescaling lives in `packages/scene-graph/src/scaling/`; Core's Figma API delegates there instead of scaling nodes itself.
- Shared primitives that format packages and collaboration need live here: color conversion and management under `@open-pencil/scene-graph/color`, text/layout direction under `@open-pencil/scene-graph/text/direction`, and fractional sibling order keys under `@open-pencil/scene-graph/order-keys` (`packages/scene-graph/tests/order-keys.test.ts`).
- A text's list items, and spacing a paragraph sets for itself over the text's (`paragraphSpacingAt`), are one `TextParagraphStyle` per paragraph in `textParagraphs`; `@open-pencil/scene-graph/text` numbers them (`textListItems`) and keeps the styles aligned through edits (`paragraphStylesAfterEdit`, `paragraphStylesInRange`), so the renderer, `.fig`, the Figma API, and exporters never count markers or split paragraphs themselves (`packages/scene-graph/tests/text/lists.test.ts`).
+- A text's `lineHeight` and `letterSpacing`, on the layer and its runs, are a `TextLength` in pixels or a percent of the font size, kept in that unit as Figma keeps it (`null` line height is automatic). Resolve them with `lineHeightPixels` and `textLengthPixels` from `@open-pencil/scene-graph/text` at the size of the characters they space; never read `.value` as pixels (`packages/core/tests/figma-api/text/units.test.ts`).
- A node's per-axis sizing (Figma's `layoutSizingHorizontal`/`Vertical`) is read and written through `packages/scene-graph/src/layout/sizing.ts`. Fill is stored on the child as Figma stores it, `layoutGrow` along the parent's primary axis (a grid's is horizontal) and `layoutAlignSelf: 'STRETCH'` across it; `primaryAxisSizing`/`counterAxisSizing` only fix or hug. Layout, the Figma API, the properties panel, and exporters call it instead of mapping axes themselves (`packages/core/tests/figma-api/accessors/layout/sizing.test.ts`).
- Formats read auto layout keywords (stack direction, `justify-content`, `align-items`, `align-self`, padding shorthand) through `packages/scene-graph/src/layout/keywords.ts`, and an importer builds fill and hug for a node not yet in the graph with `fillSizingFields` and `autoLayoutSizingFields`. Design JSX and `.pen` pass their own spellings straight to it, and DOM/CSS parses CSS values first with `parseCSSJustifyContent` and its siblings in `@open-pencil/scene-graph/css` (`packages/scene-graph/tests/layout/keywords.test.ts`, `packages/scene-graph/tests/css/layout.test.ts`).
- CSS values that become scene-graph types, such as grid track lists, are parsed in `@open-pencil/scene-graph/css` on `postcss-value-parser`; design-jsx and dom-css call it instead of splitting or matching CSS by hand (`packages/scene-graph/tests/css`).
diff --git a/packages/scene-graph/src/connectors/sublayers.ts b/packages/scene-graph/src/connectors/sublayers.ts
index dcc600130..e1913229e 100644
--- a/packages/scene-graph/src/connectors/sublayers.ts
+++ b/packages/scene-graph/src/connectors/sublayers.ts
@@ -2,6 +2,7 @@ import { BLACK } from '../constants'
import type { GeneratedFrameKind } from '../generated/kind'
import type { SceneGraph } from '../graph'
import type { Color, Vector } from '../primitives'
+import { pixelLength } from '../text/lengths'
import type { ConnectorEndpoint, Fill, SceneNode, Stroke, VectorNetwork } from '../types'
/**
@@ -140,7 +141,7 @@ export function buildConnectorSublayers(
fontFamily: 'Inter',
fontWeight: 500,
fontSize: 16,
- lineHeight: 24,
+ lineHeight: pixelLength(24),
textAlignHorizontal: 'CENTER',
textAutoResize: 'WIDTH_AND_HEIGHT',
fills: [solid(BLACK)],
diff --git a/packages/scene-graph/src/copy.ts b/packages/scene-graph/src/copy.ts
index b367d4e9b..ad91bfaec 100644
--- a/packages/scene-graph/src/copy.ts
+++ b/packages/scene-graph/src/copy.ts
@@ -72,6 +72,8 @@ export function copyStyleRun(r: StyleRun): StyleRun {
}
}
if (r.style.hyperlink) copy.style.hyperlink = { ...r.style.hyperlink }
+ if (r.style.lineHeight) copy.style.lineHeight = { ...r.style.lineHeight }
+ if (r.style.letterSpacing) copy.style.letterSpacing = { ...r.style.letterSpacing }
if (r.style.boundVariables) copy.style.boundVariables = { ...r.style.boundVariables }
return copy
}
@@ -244,6 +246,14 @@ function copyArcData(a: ArcData): ArcData {
*/
export type NodeCloneMode = 'deep' | 'fig-import'
+/** A text's line height and letter spacing, copied so a clone never shares them. */
+function copyTextLengths(src: SceneNode): Pick<SceneNode, 'lineHeight' | 'letterSpacing'> {
+ return {
+ lineHeight: src.lineHeight && { ...src.lineHeight },
+ letterSpacing: { ...src.letterSpacing }
+ }
+}
+
export function cloneNodeProps(
src: SceneNode,
componentId: string | null,
@@ -285,6 +295,7 @@ export function cloneNodeProps(
source: componentId === null ? structuredClone(src.source) : createDefaultSourceMetadata(),
dashPattern: copyOpt(src.dashPattern, (a) => [...a]),
fontVariations: copyOpt(src.fontVariations, (a) => a.map((v) => ({ ...v }))),
+ ...copyTextLengths(src),
fontFeatures: copyOpt(src.fontFeatures, (a) => a.map((v) => ({ ...v }))),
textParagraphs: copyOpt(src.textParagraphs, (a) => a.map((v) => ({ ...v }))),
textDecorationFills: copyOpt(src.textDecorationFills, copyFills),
diff --git a/packages/scene-graph/src/css/index.ts b/packages/scene-graph/src/css/index.ts
index 0ae3597cd..83004a1fb 100644
--- a/packages/scene-graph/src/css/index.ts
+++ b/packages/scene-graph/src/css/index.ts
@@ -6,4 +6,5 @@ export {
parseCSSJustifyContent
} from './layout'
export { parseCSSShadows } from './shadows'
+export { parseCSSLetterSpacing, parseCSSLineHeight } from './text'
export { parseCSSColor, parseCSSNumber, splitCSSValue } from './values'
diff --git a/packages/scene-graph/src/css/text.ts b/packages/scene-graph/src/css/text.ts
new file mode 100644
index 000000000..7cd5eca23
--- /dev/null
+++ b/packages/scene-graph/src/css/text.ts
@@ -0,0 +1,43 @@
+import valueParser from 'postcss-value-parser'
+
+import { percentLength, pixelLength } from '../text/lengths'
+import type { TextLength } from '../types'
+import { parseCSSNumber } from './values'
+
+/** A CSS dimension's number and lowercase unit, or null. */
+function dimension(value: string): { number: number; unit: string } | null {
+ const parsed = valueParser.unit(value)
+ if (!parsed) return null
+ const number = Number(parsed.number)
+ return Number.isFinite(number) ? { number, unit: parsed.unit.toLowerCase() } : null
+}
+
+/**
+ * A CSS `line-height` as a text length: a unitless multiple, `em`, or a percent follows the font size,
+ * as a percent does in Figma; pixels stay pixels; `normal` is automatic, a null. Undefined for a
+ * value it cannot read.
+ */
+export function parseCSSLineHeight(value: string | undefined): TextLength | null | undefined {
+ const trimmed = value?.trim()
+ if (!trimmed) return undefined
+ if (trimmed === 'normal') return null
+ const parsed = dimension(trimmed)
+ if (parsed?.unit === '' || parsed?.unit === 'em') return percentLength(parsed.number * 100)
+ if (parsed?.unit === '%') return percentLength(parsed.number)
+ const pixels = parseCSSNumber(trimmed)
+ return pixels === null ? undefined : pixelLength(pixels)
+}
+
+/**
+ * A CSS `letter-spacing` as a text length: `em` is a percent of the font size, pixels stay pixels,
+ * and `normal` is none. Undefined for a value it cannot read.
+ */
+export function parseCSSLetterSpacing(value: string | undefined): TextLength | undefined {
+ const trimmed = value?.trim()
+ if (!trimmed) return undefined
+ if (trimmed === 'normal') return pixelLength(0)
+ const parsed = dimension(trimmed)
+ if (parsed?.unit === 'em') return percentLength(parsed.number * 100)
+ const pixels = parseCSSNumber(trimmed)
+ return pixels === null ? undefined : pixelLength(pixels)
+}
diff --git a/packages/scene-graph/src/figjam/text.ts b/packages/scene-graph/src/figjam/text.ts
index b3bbdf10e..36a7cbe55 100644
--- a/packages/scene-graph/src/figjam/text.ts
+++ b/packages/scene-graph/src/figjam/text.ts
@@ -1,15 +1,16 @@
+import { percentLength } from '../text/lengths'
import type { SceneNode } from '../types'
/**
- * FigJam's text sizes for sticky notes and shapes, each with the tracking it sets, as a fraction
+ * FigJam's text sizes for sticky notes and shapes, each with the tracking it sets, as a percent
* of the size; the line stays one and a half times the size.
*/
export const FIGJAM_TEXT_SIZES = {
- small: { fontSize: 16, tracking: -0.011 },
- medium: { fontSize: 24, tracking: -0.019 },
- large: { fontSize: 40, tracking: -0.022 },
- extraLarge: { fontSize: 64, tracking: -0.022 },
- huge: { fontSize: 96, tracking: -0.023 }
+ small: { fontSize: 16, tracking: -1.1 },
+ medium: { fontSize: 24, tracking: -1.9 },
+ large: { fontSize: 40, tracking: -2.2 },
+ extraLarge: { fontSize: 64, tracking: -2.2 },
+ huge: { fontSize: 96, tracking: -2.3 }
} as const
export type FigJamTextSize = keyof typeof FIGJAM_TEXT_SIZES
@@ -38,7 +39,12 @@ export function figJamTextSizeFields(
): Partial<SceneNode> {
const { fontSize, tracking } = FIGJAM_TEXT_SIZES[size]
const tracked = FIGJAM_TYPEFACES[typeface].tracked
- return { fontSize, lineHeight: fontSize * 1.5, letterSpacing: tracked ? fontSize * tracking : 0 }
+ return {
+ fontSize,
+ // FigJam writes both relative to the size, a line at 150% and tracking in percent.
+ lineHeight: percentLength(150),
+ letterSpacing: percentLength(tracked ? tracking : 0)
+ }
}
/** The preset a text is closest to, as FigJam's size menu shows a rescaled one. */
diff --git a/packages/scene-graph/src/generated/shape-with-text.ts b/packages/scene-graph/src/generated/shape-with-text.ts
index ea4e44ebe..7a3711f01 100644
--- a/packages/scene-graph/src/generated/shape-with-text.ts
+++ b/packages/scene-graph/src/generated/shape-with-text.ts
@@ -3,6 +3,7 @@ import { FIGJAM_TYPEFACES, figJamTextSizeFields } from '../figjam/text'
import type { SceneGraph } from '../index'
import { shapeWithTextLabelBox } from '../shape-with-text/fit'
import type { ShapeWithTextType } from '../shape-with-text/kinds'
+import { lineHeightPixels } from '../text/lengths'
import type { Fill, SceneNode } from '../types'
import type { GeneratedFrameKind } from './kind'
@@ -100,7 +101,7 @@ export function buildShapeWithTextLabel(
x: box.x,
y: box.y,
width: box.width,
- height: fields.lineHeight ?? undefined,
+ height: lineHeightPixels(fields.lineHeight ?? null, fields.fontSize ?? 0) ?? undefined,
text: '',
...props
})
diff --git a/packages/scene-graph/src/generated/sticky.ts b/packages/scene-graph/src/generated/sticky.ts
index 5221da321..d7c3c2907 100644
--- a/packages/scene-graph/src/generated/sticky.ts
+++ b/packages/scene-graph/src/generated/sticky.ts
@@ -1,6 +1,7 @@
import { BLACK } from '../constants'
import type { SceneGraph } from '../graph'
import type { Color } from '../primitives'
+import { lineHeightPixels, percentLength, pixelLength } from '../text/lengths'
import type { Effect, Fill, SceneNode } from '../types'
import type { GeneratedFrameKind } from './kind'
@@ -100,8 +101,9 @@ export function stickyTextFields(
fontFamily: STICKY_FONT_FAMILY,
fontWeight: STICKY_FONT_WEIGHT,
fontSize,
- lineHeight: role === 'body' ? fontSize * 1.5 : 16 * scale,
- letterSpacing: fontSize * -0.011,
+ // As Figma writes a note: the body at 150% and the author at 16 px a scale, tracked -1.1%.
+ lineHeight: role === 'body' ? percentLength(150) : pixelLength(16 * scale),
+ letterSpacing: percentLength(-1.1),
textAlignHorizontal: 'LEFT',
textAlignVertical: 'TOP',
...STICKY_SUBLAYER_LAYOUT,
@@ -173,14 +175,15 @@ export function buildStickySublayers(
const body = graph.createNode('TEXT', sticky.id, {
...bodyFields,
width: inner,
- height: bodyFields.lineHeight ?? undefined,
+ height: lineHeightPixels(bodyFields.lineHeight ?? null, bodyFields.fontSize ?? 0) ?? undefined,
text: content.text ?? '',
...overrides.body
})
const author = graph.createNode('TEXT', sticky.id, {
...authorFields,
width: inner,
- height: authorFields.lineHeight ?? undefined,
+ height:
+ lineHeightPixels(authorFields.lineHeight ?? null, authorFields.fontSize ?? 0) ?? undefined,
text: content.author ?? '',
visible: content.authorVisible ?? true,
...overrides.author
diff --git a/packages/scene-graph/src/node-defaults.ts b/packages/scene-graph/src/node-defaults.ts
index 3f7bff660..d01015acb 100644
--- a/packages/scene-graph/src/node-defaults.ts
+++ b/packages/scene-graph/src/node-defaults.ts
@@ -5,6 +5,7 @@ import {
DEFAULT_STROKE_WEIGHT
} from './constants'
import { createInstanceOverrideState } from './instances/overrides'
+import { NO_LETTER_SPACING } from './text/lengths'
import type { NodeType, SceneNode, SourceMetadata } from './types'
export function createDefaultSourceMetadata(): SourceMetadata {
@@ -102,7 +103,7 @@ export function createDefaultNode(
textLanguage: null,
leadingTrim: 'NONE',
lineHeight: null,
- letterSpacing: 0,
+ letterSpacing: NO_LETTER_SPACING,
layoutMode: 'NONE',
layoutDirection: 'AUTO',
layoutWrap: 'NO_WRAP',
diff --git a/packages/scene-graph/src/scaling/node.ts b/packages/scene-graph/src/scaling/node.ts
index 4bd429f98..12348c5a5 100644
--- a/packages/scene-graph/src/scaling/node.ts
+++ b/packages/scene-graph/src/scaling/node.ts
@@ -1,4 +1,5 @@
import { scaleGeometryPaths } from '../copy'
+import { scaledTextLength } from '../text/lengths'
import { TEXT_PARAGRAPH_SPACING_FIELDS } from '../text/paragraphs'
import {
type Effect,
@@ -53,8 +54,8 @@ function scaledStyleRuns(styleRuns: readonly StyleRun[], scale: number): StyleRu
style: {
...structuredClone(run.style),
fontSize: run.style.fontSize == null ? undefined : run.style.fontSize * scale,
- letterSpacing: run.style.letterSpacing == null ? undefined : run.style.letterSpacing * scale,
- lineHeight: scaledOptional(run.style.lineHeight ?? null, scale),
+ letterSpacing: run.style.letterSpacing && scaledTextLength(run.style.letterSpacing, scale),
+ lineHeight: run.style.lineHeight && scaledTextLength(run.style.lineHeight, scale),
textDecorationThickness: scaledOptional(run.style.textDecorationThickness ?? null, scale),
textUnderlineOffset: scaledOptional(run.style.textUnderlineOffset ?? null, scale)
}
@@ -127,8 +128,8 @@ export function scaleNodeChanges(
bottomRightRadius: node.bottomRightRadius * scale,
bottomLeftRadius: node.bottomLeftRadius * scale,
fontSize: node.fontSize * scale,
- letterSpacing: node.letterSpacing * scale,
- lineHeight: scaledOptional(node.lineHeight, scale),
+ letterSpacing: scaledTextLength(node.letterSpacing, scale),
+ lineHeight: node.lineHeight && scaledTextLength(node.lineHeight, scale),
textDecorationThickness: scaledOptional(node.textDecorationThickness, scale),
textUnderlineOffset: scaledOptional(node.textUnderlineOffset, scale),
styleRuns: scaledStyleRuns(node.styleRuns, scale),
diff --git a/packages/scene-graph/src/text/index.ts b/packages/scene-graph/src/text/index.ts
index 474dd5a62..8de0a312d 100644
--- a/packages/scene-graph/src/text/index.ts
+++ b/packages/scene-graph/src/text/index.ts
@@ -1,3 +1,5 @@
export * from './lists'
export * from './paragraphs'
export * from './references'
+export * from './lengths'
+export * from './schema'
diff --git a/packages/scene-graph/src/text/lengths.ts b/packages/scene-graph/src/text/lengths.ts
new file mode 100644
index 000000000..cb7d4d557
--- /dev/null
+++ b/packages/scene-graph/src/text/lengths.ts
@@ -0,0 +1,34 @@
+import type { TextLength } from '../types'
+
+/** No letter spacing, as a new text has it and as Figma writes it. */
+export const NO_LETTER_SPACING: TextLength = { value: 0, unit: 'PERCENT' }
+
+/** `length` in pixels at `fontSize`. */
+export function textLengthPixels(length: TextLength, fontSize: number): number {
+ return length.unit === 'PIXELS' ? length.value : (length.value / 100) * fontSize
+}
+
+/** A line height in pixels at `fontSize`, or null when it is automatic. */
+export function lineHeightPixels(lineHeight: TextLength | null, fontSize: number): number | null {
+ return lineHeight ? textLengthPixels(lineHeight, fontSize) : null
+}
+
+/** A length in pixels, as a bound number variable and most authored formats give one. */
+export function pixelLength(value: number): TextLength {
+ return { value, unit: 'PIXELS' }
+}
+
+/** A length as a percent of the font size. */
+export function percentLength(value: number): TextLength {
+ return { value, unit: 'PERCENT' }
+}
+
+/** `length` scaled by `factor`: pixels scale, a percent already follows the font size. */
+export function scaledTextLength(length: TextLength, factor: number): TextLength {
+ return length.unit === 'PIXELS' ? pixelLength(length.value * factor) : length
+}
+
+/** `length` as people read it: `24px` or `150%`. */
+export function formatTextLength(length: TextLength): string {
+ return length.unit === 'PIXELS' ? `${length.value}px` : `${length.value}%`
+}
diff --git a/packages/scene-graph/src/text/schema.ts b/packages/scene-graph/src/text/schema.ts
new file mode 100644
index 000000000..df802f37a
--- /dev/null
+++ b/packages/scene-graph/src/text/schema.ts
@@ -0,0 +1,7 @@
+import * as v from 'valibot'
+
+/** A line height or letter spacing as files carry it: pixels, or a percent of the font size. */
+export const textLengthSchema = v.object({
+ value: v.number(),
+ unit: v.picklist(['PIXELS', 'PERCENT'])
+})
diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.ts
index 37e3b4c01..eadc558c8 100644
--- a/packages/scene-graph/src/types.ts
+++ b/packages/scene-graph/src/types.ts
@@ -354,6 +354,15 @@ export type TextBindableField = (typeof TEXT_BINDABLE_FIELDS)[number]
/** Variable IDs bound to text fields, by field. */
export type TextBoundVariables = Partial<Record<TextBindableField, string>>
+/**
+ * A line height or letter spacing as Figma keeps it: pixels, or a percent of the font size that
+ * follows the size when it changes.
+ */
+export interface TextLength {
+ value: number
+ unit: 'PIXELS' | 'PERCENT'
+}
+
export interface CharacterStyleOverride {
fontWeight?: number
italic?: boolean
@@ -365,8 +374,9 @@ export interface CharacterStyleOverride {
textUnderlineOffset?: number | null
fontSize?: number
fontFamily?: string
- letterSpacing?: number
- lineHeight?: number | null
+ letterSpacing?: TextLength
+ /** `null` is automatic, from the font. */
+ lineHeight?: TextLength | null
fills?: Fill[]
fontVariations?: FontVariation[]
fontFeatures?: FontFeature[]
@@ -650,8 +660,9 @@ export interface SceneNode {
textDecorationSkipInk: boolean
textUnderlineOffset: number | null
leadingTrim: LeadingTrim
- lineHeight: number | null
- letterSpacing: number
+ /** `null` is automatic, from the font. */
+ lineHeight: TextLength | null
+ letterSpacing: TextLength
maxLines: number | null
/**
* One entry per paragraph of `text`, in order. Missing entries are plain paragraphs, so text
diff --git a/packages/scene-graph/src/variables/bindings.ts b/packages/scene-graph/src/variables/bindings.ts
index 92502d36a..e1498fd76 100644
--- a/packages/scene-graph/src/variables/bindings.ts
+++ b/packages/scene-graph/src/variables/bindings.ts
@@ -1,9 +1,12 @@
+import { isEqual } from 'es-toolkit/predicate'
+
import type { VariableModeFallback } from '.'
import { copyFills, copyStrokes } from '../copy'
import type { SceneGraph } from '../graph'
import { hasInstanceOverride } from '../instances'
import type { Color } from '../primitives'
-import type { Fill, SceneNode, Stroke, StyleRun } from '../types'
+import { pixelLength } from '../text/lengths'
+import type { Fill, SceneNode, Stroke, StyleRun, TextLength } from '../types'
import { NUMERIC_FIELDS, isNumericVariableBindingField } from './fields'
import { variableText, variableTruthy } from './text'
import { variableValueReferences } from './value'
@@ -38,6 +41,14 @@ export function assignVariableBindingUnits(
}
}
+/** Fields a bound number sets as a length in pixels, as Figma's do, whatever unit they held. */
+const TEXT_LENGTH_FIELDS: ReadonlySet<string> = new Set(['lineHeight', 'letterSpacing'])
+
+/** A bound number as the field stores it. */
+function boundValue(field: string, value: number): number | TextLength {
+ return TEXT_LENGTH_FIELDS.has(field) ? pixelLength(value) : value
+}
+
/**
* The values a node's numeric bindings resolve to in its mode, in scene units, for the fields
* whose stored value differs. A width or height an instance overrides keeps its own value.
@@ -57,8 +68,11 @@ export function resolvedNumericBindings(
const scale = node.variableBindingScales[field] ?? 1
const effective = value * scale
if (!Number.isFinite(effective)) continue
- const next = field === 'opacity' ? Math.max(0, Math.min(1, effective)) : effective
- if (node[field as keyof SceneNode] !== next) Object.assign(updates, { [field]: next })
+ const next = boundValue(
+ field,
+ field === 'opacity' ? Math.max(0, Math.min(1, effective)) : effective
+ )
+ if (!isEqual(node[field as keyof SceneNode], next)) Object.assign(updates, { [field]: next })
}
return updates
}
@@ -109,8 +123,10 @@ export function resolvedRunBindings(
const variableId = bound[field]
if (!variableId) continue
const value = graph.resolveNumberVariableForNode(node.id, variableId, fallback)
- if (value === undefined || !Number.isFinite(value) || style[field] === value) continue
- style = { ...style, [field]: value }
+ if (value === undefined || !Number.isFinite(value)) continue
+ const next = boundValue(field, value)
+ if (isEqual(style[field], next)) continue
+ style = { ...style, [field]: next }
}
return style === run.style ? run : { ...run, style }
})
diff --git a/packages/scene-graph/tests/components/sync-field-contract.test.ts b/packages/scene-graph/tests/components/sync-field-contract.test.ts
index 0c88f396a..f5b0c5e29 100644
--- a/packages/scene-graph/tests/components/sync-field-contract.test.ts
+++ b/packages/scene-graph/tests/components/sync-field-contract.test.ts
@@ -2,6 +2,7 @@ import { expect, test } from 'bun:test'
import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
import { setInstanceOverride } from '@open-pencil/scene-graph/instances/overrides'
+import { pixelLength } from '@open-pencil/scene-graph/text'
import { expectDefined } from '../helpers/assert'
@@ -323,11 +324,11 @@ test('a copy that sizes itself to its own content keeps that size through a comp
graph.updateNode(instance.id, { width: 24 })
setInstanceOverride(instance.instanceOverrides, instance.id, copyText.id, 'text', true)
- graph.updateNode(text.id, { width: 64, letterSpacing: 1 })
+ graph.updateNode(text.id, { width: 64, letterSpacing: pixelLength(1) })
graph.updateNode(label.id, { width: 64 })
graph.syncInstances(badge.id)
expect([copyText.text, copyText.width, copyLabel.width, instance.width]).toEqual(['2', 8, 8, 24])
- expect(copyText.letterSpacing).toBe(1)
+ expect(copyText.letterSpacing).toEqual(pixelLength(1))
})
test('content-sized copies retain their constraint anchor through live component edits', () => {
diff --git a/packages/scene-graph/tests/css/text.test.ts b/packages/scene-graph/tests/css/text.test.ts
new file mode 100644
index 000000000..84d786694
--- /dev/null
+++ b/packages/scene-graph/tests/css/text.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, test } from 'bun:test'
+
+import { parseCSSLetterSpacing, parseCSSLineHeight } from '@open-pencil/scene-graph/css'
+import { percentLength, pixelLength } from '@open-pencil/scene-graph/text'
+
+describe('parseCSSLineHeight', () => {
+ test.each([
+ ['1.5', percentLength(150)],
+ ['120%', percentLength(120)],
+ ['24px', pixelLength(24)],
+ ['1.5rem', pixelLength(24)],
+ ['normal', null],
+ ['2em', percentLength(200)],
+ ['2vh', undefined],
+ ['', undefined]
+ ])('%s', (value, expected) => {
+ expect(parseCSSLineHeight(value)).toEqual(expected)
+ })
+})
+
+describe('parseCSSLetterSpacing', () => {
+ test.each([
+ ['0.1em', percentLength(10)],
+ ['2px', pixelLength(2)],
+ ['normal', pixelLength(0)],
+ ['10%', undefined]
+ ])('%s', (value, expected) => {
+ expect(parseCSSLetterSpacing(value)).toEqual(expected)
+ })
+})
diff --git a/packages/scene-graph/tests/figjam/text.test.ts b/packages/scene-graph/tests/figjam/text.test.ts
index 01fe65a74..81578eec2 100644
--- a/packages/scene-graph/tests/figjam/text.test.ts
+++ b/packages/scene-graph/tests/figjam/text.test.ts
@@ -1,14 +1,19 @@
import { describe, expect, test } from 'bun:test'
-import { figJamTextSizeFields, figJamTypeface, figJamTypefaceFields } from '@open-pencil/scene-graph/figjam'
+import {
+ figJamTextSizeFields,
+ figJamTypeface,
+ figJamTypefaceFields
+} from '@open-pencil/scene-graph/figjam'
+import { percentLength } from '@open-pencil/scene-graph/text'
// Values measured in FigJam's text menus.
describe("FigJam's text", () => {
test('each size sets its tracking, and the line stays one and a half times the size', () => {
expect(figJamTextSizeFields('huge')).toEqual({
fontSize: 96,
- lineHeight: 144,
- letterSpacing: 96 * -0.023
+ lineHeight: percentLength(150),
+ letterSpacing: percentLength(-2.3)
})
})
@@ -17,11 +22,11 @@ describe("FigJam's text", () => {
fontFamily: 'Merriweather',
fontWeight: 400,
fontSize: 24,
- letterSpacing: 24 * -0.019
+ letterSpacing: percentLength(-1.9)
})
expect(figJamTypefaceFields('scribbled', { fontSize: 16 })).toMatchObject({
fontFamily: 'Figma Hand',
- letterSpacing: 0
+ letterSpacing: percentLength(0)
})
expect(figJamTypeface({ fontFamily: 'Roboto Mono' })).toBe('technical')
expect(figJamTypeface({ fontFamily: 'Comic Sans' })).toBeNull()
diff --git a/packages/vue/src/controls/typography/actions.ts b/packages/vue/src/controls/typography/actions.ts
index 7af7e3096..52853ec13 100644
--- a/packages/vue/src/controls/typography/actions.ts
+++ b/packages/vue/src/controls/typography/actions.ts
@@ -6,6 +6,7 @@ import { fontManager, nearestFamilyFace } from '@open-pencil/core/text'
import type {
SceneNode,
TextDecoration,
+ TextLength,
TextListType,
TextParagraphSpacingField
} from '@open-pencil/scene-graph'
@@ -30,6 +31,8 @@ type TextDirection = SceneNode['textDirection']
type TextVerticalAlign = SceneNode['textAlignVertical']
type TextCase = SceneNode['textCase']
type TextTruncation = SceneNode['textTruncation']
+/** A value the panel previews and commits on every selected text. */
+type PropValue = number | string | TextLength | null
function sharedValue<T>(values: readonly T[]): MixedValue<T> {
const [first] = values
@@ -362,7 +365,7 @@ export function createTypographyActions({
}
}
- function updateProp(key: keyof SceneNode, value: number | string | null) {
+ function updateProp(key: keyof SceneNode, value: PropValue) {
if (previewKey !== key) {
previewKey = key
beforePreview.clear()
@@ -374,11 +377,7 @@ export function createTypographyActions({
}
}
- function commitProp(
- key: keyof SceneNode,
- _value: number | string | null,
- previous: number | string | null
- ) {
+ function commitProp(key: keyof SceneNode, _value: PropValue, previous: PropValue) {
const targets = nodes.value
if (targets.length === 0) return
const snapshots = previewKey === key ? beforePreview : new Map<string, Preview>()
diff --git a/skills/open-pencil/SKILL.md b/skills/open-pencil/SKILL.md
index d4408913e..a837c1df8 100644
--- a/skills/open-pencil/SKILL.md
+++ b/skills/open-pencil/SKILL.md
@@ -177,7 +177,7 @@ openpencil eval design.fig -w -c '
'
```
-Text styles follow Figma's per-character model: `getStyledTextSegments(fields)` reads runs, `getRange…`/`setRange…` read and set font, size, fills, letter spacing, line height, decorations, text case, hyperlinks, text and fill style IDs, and bound variables for `[start, end)`, and a text's `fontSize`, `fontName`, `fills`, and similar read `figma.mixed` while characters differ. Check for it before using the value.
+Text styles follow Figma's per-character model: `getStyledTextSegments(fields)` reads runs, `getRange…`/`setRange…` read and set font, size, fills, letter spacing, line height, decorations, text case, hyperlinks, text and fill style IDs, and bound variables for `[start, end)`, and a text's `fontSize`, `fontName`, `fills`, and similar read `figma.mixed` while characters differ. Check for it before using the value. Paints everywhere take Figma's shape: a solid `color` is `{ r, g, b }` with the alpha in `opacity`, and an image is `{ type: "IMAGE", imageHash, scaleMode: "FILL" | "FIT" | "CROP" | "TILE" }` with optional `rotation` and `scalingFactor`.
Next to `figma`, scripts get `openpencil`: what OpenPencil adds to the Figma API, in its style. A main component can behave as a Reka UI control, by its own property and slot names:
diff --git a/skills/open-pencil/references/design-authoring.md b/skills/open-pencil/references/design-authoring.md
index 0963cc453..289b6c1db 100644
--- a/skills/open-pencil/references/design-authoring.md
+++ b/skills/open-pencil/references/design-authoring.md
@@ -36,7 +36,7 @@ This reference describes scene creation, not React DOM output. Use the `render`
## Variables and components
- Create document variables before referencing them with `designVar('id-or-name')`. `defineVars` groups references; it does not create variable collections.
-- COLOR references work in paint props. FLOAT references work in `w`, `h`, `gap`, padding, corner radii, `strokeWidth`, `opacity`, text `size`/`fontSize`, `lineHeight`, and `letterSpacing`. Grid `columnGap`/`rowGap` and wrapped flex `rowGap` also support FLOAT references; grid `gap` overrides both axis-specific gaps. Use numbers or FLOAT references for these scalar props, not CSS unit strings.
+- COLOR references work in paint props. FLOAT references work in `w`, `h`, `gap`, padding, corner radii, `strokeWidth`, `opacity`, text `size`/`fontSize`, `lineHeight`, and `letterSpacing`. Grid `columnGap`/`rowGap` and wrapped flex `rowGap` also support FLOAT references; grid `gap` overrides both axis-specific gaps. Use numbers or FLOAT references for these scalar props, not CSS unit strings; the one exception is `lineHeight` and `letterSpacing`, which also take a percent of the font size such as `"150%"` that follows the size when it changes.
- References preserve real graph bindings, not just copied values. Set the intended collection mode on the parent before creating scalar-bound content: initial scalar layout resolves that inherited mode. This does not guarantee automatic scalar layout recomputation after a later mode switch. Verify resulting geometry as well as paint when changing modes. Missing or incorrectly typed scalar variables are errors.
- `bind` maps supported scene-field paths to variable IDs or references when no shorthand exists. Use semantic tokens consistently rather than declaring unused collections.
- Build repeated or computed content with JavaScript inside `{}` rather than writing each item out: `{days.map((day) => <Text>{day}</Text>)}`, `{Array.from({ length: 35 }, (_, i) => <Frame>…</Frame>)}`, and conditionals. Statements such as `const weeks = …` may come first and then end with `return` and the JSX, as a component's body does: `const weeks = 5` on one line, `return <Frame>…</Frame>` on the next.
diff --git a/src/app/collab/shared-tree/fields.ts b/src/app/collab/shared-tree/fields.ts
index ce3b9d1cd..e459cea1f 100644
--- a/src/app/collab/shared-tree/fields.ts
+++ b/src/app/collab/shared-tree/fields.ts
@@ -12,7 +12,7 @@ import { randomIndex } from '@open-pencil/scene-graph/random'
* name, the move clock, and the tree format. The document node's plugin data, comments,
* libraries, and settings live in their own maps (`src/app/collab/document/sync.ts`).
*/
-export const TREE_FORMAT = 4
+export const TREE_FORMAT = 5
export const PARENTS_FIELD = 'parents'
export const ORDER_KEY_FIELD = 'orderKey'
export const PAGE_FIELD = 'page'
diff --git a/src/components/properties/TypographySection.vue b/src/components/properties/TypographySection.vue
index 9f1c3588a..200690ad4 100644
--- a/src/components/properties/TypographySection.vue
+++ b/src/components/properties/TypographySection.vue
@@ -11,6 +11,7 @@ import { appMenuShortcutLabel } from '@/app/shell/menu/shortcut'
import FontPicker from '@/components/font-picker/FontPicker.vue'
import NumberField from '@/components/inputs/NumberField.vue'
import SharedStyleField from '@/components/properties/shared-style/SharedStyleField.vue'
+import LetterSpacingField from '@/components/properties/typography/LetterSpacingField.vue'
import LineHeightField from '@/components/properties/typography/LineHeightField.vue'
import VariableNumberField from '@/components/properties/VariableNumberField.vue'
import IconButton from '@/components/ui/button/IconButton.vue'
@@ -152,20 +153,11 @@ function picked<T>(value: MixedValue<T>): T | '' {
/>
</PanelFieldGroup>
<PanelFieldGroup :label="panels.letterSpacing">
- <VariableNumberField
- suffix="px"
- :model-value="ctx.merged('letterSpacing')"
- :aria-label="panels.letterSpacing"
- :node-id="ctx.node.value.id"
- :node-ids="ctx.nodes.value.map((text) => text.id)"
- binding-path="letterSpacing"
- @update:model-value="ctx.actions.updateProp('letterSpacing', $event)"
- @commit="(v: number, p: number) => ctx.actions.commitProp('letterSpacing', v, p)"
- >
- <template #icon>
- <icon-lucide-a-large-small class="size-3" />
- </template>
- </VariableNumberField>
+ <LetterSpacingField
+ :nodes="ctx.nodes.value"
+ @update="ctx.actions.updateProp('letterSpacing', $event)"
+ @commit="(v, p) => ctx.actions.commitProp('letterSpacing', v, p)"
+ />
</PanelFieldGroup>
</PanelGrid>
diff --git a/src/components/properties/typography/LetterSpacingField.vue b/src/components/properties/typography/LetterSpacingField.vue
new file mode 100644
index 000000000..0642b83eb
--- /dev/null
+++ b/src/components/properties/typography/LetterSpacingField.vue
@@ -0,0 +1,38 @@
+<script setup lang="ts">
+import type { SceneNode, TextLength } from '@open-pencil/scene-graph'
+import { useI18n } from '@open-pencil/vue/i18n'
+
+import VariableNumberField from '@/components/properties/VariableNumberField.vue'
+
+import { useTextLength } from './useTextLength'
+
+/** Every selected text layer; the field reads Mixed when their letter spacings differ. */
+const { nodes } = defineProps<{ nodes: readonly SceneNode[] }>()
+const emit = defineEmits<{
+ update: [value: TextLength]
+ commit: [value: TextLength, previous: TextLength]
+}>()
+const { panels } = useI18n()
+const { value, suffix, length } = useTextLength(
+ () => nodes,
+ 'letterSpacing',
+ () => 0
+)
+</script>
+
+<template>
+ <VariableNumberField
+ :model-value="value"
+ :suffix="suffix"
+ :aria-label="panels.letterSpacing"
+ :node-id="nodes.at(0)?.id ?? ''"
+ :node-ids="nodes.map((node) => node.id)"
+ binding-path="letterSpacing"
+ @update:model-value="emit('update', length($event))"
+ @commit="(current, previous) => emit('commit', length(current), length(previous))"
+ >
+ <template #icon>
+ <icon-lucide-a-large-small class="size-3" />
+ </template>
+ </VariableNumberField>
+</template>
diff --git a/src/components/properties/typography/LineHeightField.vue b/src/components/properties/typography/LineHeightField.vue
index 5fa3039fb..270633779 100644
--- a/src/components/properties/typography/LineHeightField.vue
+++ b/src/components/properties/typography/LineHeightField.vue
@@ -2,9 +2,9 @@
import { SelectRoot, SelectTrigger } from 'reka-ui'
import { computed } from 'vue'
-import type { SceneNode } from '@open-pencil/scene-graph'
+import type { SceneNode, TextLength } from '@open-pencil/scene-graph'
+import { pixelLength } from '@open-pencil/scene-graph/text'
import { useEditor } from '@open-pencil/vue'
-import { MIXED } from '@open-pencil/vue/controls/node-props'
import { useI18n } from '@open-pencil/vue/i18n'
import { useRetainedPopup } from '@open-pencil/vue/lifecycle/retention'
@@ -12,20 +12,22 @@ import VariableNumberField from '@/components/properties/VariableNumberField.vue
import AppSelectContent from '@/components/ui/select/AppSelectContent.vue'
import AppSelectItem from '@/components/ui/select/AppSelectItem.vue'
+import { useTextLength } from './useTextLength'
+
/** Every selected text layer; the field reads Mixed when their line heights differ. */
const { nodes } = defineProps<{ nodes: readonly SceneNode[] }>()
-const emit = defineEmits<{ update: [value: number]; commit: [value: number, previous: number] }>()
+const emit = defineEmits<{
+ update: [value: TextLength]
+ commit: [value: TextLength, previous: TextLength]
+}>()
const editor = useEditor()
const { open: popupOpen, portalActive } = useRetainedPopup()
const { panels } = useI18n()
const isAutomatic = (node: SceneNode) => node.lineHeight == null && !node.boundVariables.lineHeight
-const fixedValue = (node: SceneNode) => node.lineHeight ?? Math.round((node.fontSize || 14) * 1.2)
+/** The pixels an automatic line height becomes when it is fixed. */
+const automaticPixels = (node: SceneNode) => Math.round((node.fontSize || 14) * 1.2)
const automatic = computed(() => nodes.length > 0 && nodes.every(isAutomatic))
-const value = computed(() => {
- const values = nodes.map(fixedValue)
- const [first = 0] = values
- return values.every((current) => current === first) ? first : MIXED
-})
+const { value, suffix, length } = useTextLength(() => nodes, 'lineHeight', automaticPixels)
const nodeId = computed(() => nodes.at(0)?.id ?? '')
const nodeIds = computed(() => nodes.map((node) => node.id))
function setMode(mode: string) {
@@ -39,7 +41,11 @@ function setMode(mode: string) {
} else if (mode === 'FIXED') {
editor.undo.runBatch('Set line height', () => {
for (const node of nodes.filter(isAutomatic))
- editor.updateNodeWithUndo(node.id, { lineHeight: fixedValue(node) }, 'Set line height')
+ editor.updateNodeWithUndo(
+ node.id,
+ { lineHeight: pixelLength(automaticPixels(node)) },
+ 'Set line height'
+ )
})
}
}
@@ -49,13 +55,13 @@ function setMode(mode: string) {
<VariableNumberField
:model-value="value"
:aria-label="panels.lineHeight"
- suffix="px"
+ :suffix="suffix"
:min="0"
:node-id="nodeId"
:node-ids="nodeIds"
binding-path="lineHeight"
- @update:model-value="emit('update', $event)"
- @commit="(current, previous) => emit('commit', current, previous)"
+ @update:model-value="emit('update', length($event))"
+ @commit="(current, previous) => emit('commit', length(current), length(previous))"
>
<template #icon><icon-lucide-baseline class="size-3" /></template>
<template v-if="automatic" #display
diff --git a/src/components/properties/typography/useTextLength.ts b/src/components/properties/typography/useTextLength.ts
new file mode 100644
index 000000000..0ff5a7e84
--- /dev/null
+++ b/src/components/properties/typography/useTextLength.ts
@@ -0,0 +1,35 @@
+import { uniq } from 'es-toolkit/array'
+import { computed } from 'vue'
+
+import type { SceneNode, TextLength } from '@open-pencil/scene-graph'
+import { MIXED } from '@open-pencil/vue/controls/node-props'
+
+type LengthField = 'lineHeight' | 'letterSpacing'
+
+/**
+ * A line height or letter spacing as the panel edits it: in the unit the layers share, pixels or
+ * a percent of the font size, so an edit keeps that unit. Layers in other units read Mixed.
+ */
+export function useTextLength(
+ nodes: () => readonly SceneNode[],
+ field: LengthField,
+ fallback: (node: SceneNode) => number
+) {
+ const lengths = computed(() => nodes().map((node): TextLength | null => node[field]))
+ const unit = computed((): TextLength['unit'] => {
+ const units = uniq(lengths.value.flatMap((length) => (length ? [length.unit] : [])))
+ return units.length === 1 ? units[0] : 'PIXELS'
+ })
+ const value = computed(() => {
+ const values = nodes().map((node, index) => {
+ const length = lengths.value[index]
+ if (!length) return unit.value === 'PIXELS' ? fallback(node) : null
+ return length.unit === unit.value ? length.value : null
+ })
+ const [first] = values
+ return first != null && values.every((current) => current === first) ? first : MIXED
+ })
+ const suffix = computed(() => (unit.value === 'PERCENT' ? '%' : 'px'))
+ const length = (value: number): TextLength => ({ value, unit: unit.value })
+ return { unit, value, suffix, length }
+}
diff --git a/src/constants.ts b/src/constants.ts
index 9cebd791d..d75868b37 100644
--- a/src/constants.ts
+++ b/src/constants.ts
@@ -66,7 +66,7 @@ import type { Color } from '@open-pencil/scene-graph/primitives'
* builds that sync the layer tree or variables differently, or encode what they send
* differently, never join each other's rooms; change it with either.
*/
-export const COLLAB_APP_ID = 'openpencil/6'
+export const COLLAB_APP_ID = 'openpencil/7'
// 32 base36 characters provide roughly 165 bits of entropy. The room ID is a
// bearer credential and must resist offline enumeration from public signaling topics.
diff --git a/tests/e2e/canvas/saved-text-visual.spec.ts b/tests/e2e/canvas/saved-text-visual.spec.ts
index ac65944c6..2940ac843 100644
--- a/tests/e2e/canvas/saved-text-visual.spec.ts
+++ b/tests/e2e/canvas/saved-text-visual.spec.ts
@@ -27,7 +27,7 @@ test('wrapped text keeps its lines after a .fig is saved and reopened (#914)', a
height: 32,
fontFamily: 'Inter',
fontSize: 13,
- lineHeight: 16,
+ lineHeight: { value: 16, unit: 'PIXELS' },
textAutoResize: 'HEIGHT',
fills: [{ type: 'SOLID', color: { r: 0.1, g: 0.1, b: 0.1, a: 1 }, visible: true, opacity: 1 }]
})
diff --git a/tests/e2e/canvas/text/lines-visual.spec.ts b/tests/e2e/canvas/text/lines-visual.spec.ts
index 7ce46e2ce..c703d2a50 100644
--- a/tests/e2e/canvas/text/lines-visual.spec.ts
+++ b/tests/e2e/canvas/text/lines-visual.spec.ts
@@ -22,13 +22,13 @@ test('places lines of mixed sizes as Figma does', async () => {
x: 40,
y: 220,
text: 'one\ntwo with a tall line\nthree',
- styleRuns: [{ start: 4, length: 20, style: { lineHeight: 48 } }]
+ styleRuns: [{ start: 4, length: 20, style: { lineHeight: { value: 48, unit: 'PIXELS' } } }]
},
{
x: 280,
y: 220,
text: 'Small LARGE\nunder a fixed line height',
- lineHeight: 24,
+ lineHeight: { value: 24, unit: 'PIXELS' },
styleRuns: [big(6, 5)]
},
{
diff --git a/tests/e2e/canvas/typography-depth-visual.spec.ts b/tests/e2e/canvas/typography-depth-visual.spec.ts
index 130d774e1..13053dfd5 100644
--- a/tests/e2e/canvas/typography-depth-visual.spec.ts
+++ b/tests/e2e/canvas/typography-depth-visual.spec.ts
@@ -36,7 +36,7 @@ test('text case vertical alignment and ending truncation', async () => {
height: 106,
text: item.label,
fontSize: 20,
- lineHeight: 36,
+ lineHeight: { value: 36, unit: 'PIXELS' },
textCase: item.textCase,
textAlignVertical: item.vertical
})
@@ -63,7 +63,7 @@ test('text case vertical alignment and ending truncation', async () => {
height: 60,
text: 'This paragraph demonstrates a deterministic two-line ending truncation with an ellipsis.',
fontSize: 17,
- lineHeight: 22,
+ lineHeight: { value: 22, unit: 'PIXELS' },
textTruncation: 'ENDING',
maxLines: 2,
textAlignHorizontal: 'JUSTIFIED'
diff --git a/tests/e2e/properties/line-height.spec.ts b/tests/e2e/properties/line-height.spec.ts
index bca251042..31a2ce3e5 100644
--- a/tests/e2e/properties/line-height.spec.ts
+++ b/tests/e2e/properties/line-height.spec.ts
@@ -34,7 +34,7 @@ test('automatic line height survives focus and can be restored with undo', async
.poll(() =>
page.evaluate((id) => window.openPencil?.getStore?.().graph.getNode(id)?.lineHeight, id)
)
- .toBe(32)
+ .toEqual({ value: 32, unit: 'PIXELS' })
await page.getByRole('combobox', { name: 'Line height mode' }).click()
await page.getByRole('option', { name: 'Auto', exact: true }).click()
await expect(field).toContainText('Auto')
@@ -44,7 +44,7 @@ test('automatic line height survives focus and can be restored with undo', async
.poll(() =>
page.evaluate((id) => window.openPencil?.getStore?.().graph.getNode(id)?.lineHeight, id)
)
- .toBe(32)
+ .toEqual({ value: 32, unit: 'PIXELS' })
await field.getByRole('button', { name: 'Apply variable' }).click()
await page.getByRole('button', { name: 'Create number variable from 32', exact: true }).click()
await page.getByPlaceholder('Variable name').fill('Typography/Line height/Body')
diff --git a/tests/e2e/properties/shared-styles.spec.ts b/tests/e2e/properties/shared-styles.spec.ts
index 8e781bbf8..80fcf0ae7 100644
--- a/tests/e2e/properties/shared-styles.spec.ts
+++ b/tests/e2e/properties/shared-styles.spec.ts
@@ -37,7 +37,7 @@ test.beforeAll(async ({ browser }) => {
fontFamily: 'Inter',
fontSize: 30,
fontWeight: 700,
- lineHeight: 38,
+ lineHeight: { value: 38, unit: 'PIXELS' },
sharedStyleType: 'TEXT',
internalOnly: true
})
diff --git a/tests/e2e/properties/tracking-binding.spec.ts b/tests/e2e/properties/tracking-binding.spec.ts
index cd0948321..e8a086da4 100644
--- a/tests/e2e/properties/tracking-binding.spec.ts
+++ b/tests/e2e/properties/tracking-binding.spec.ts
@@ -14,7 +14,11 @@ for (const theme of ['light', 'dark']) {
const editor = window.openPencil?.getStore?.()
if (!editor) throw new Error('Editor unavailable')
const id = editor.createShape('TEXT', 100, 100, 240, 80)
- editor.updateNode(id, { text: 'Tracking review', fontSize: 24, letterSpacing: 2 })
+ editor.updateNode(id, {
+ text: 'Tracking review',
+ fontSize: 24,
+ letterSpacing: { value: 2, unit: 'PIXELS' }
+ })
editor.select([id])
return id
}, theme)
@@ -37,7 +41,7 @@ for (const theme of ['light', 'dark']) {
.poll(() =>
page.evaluate((id) => window.openPencil?.getStore?.().graph.getNode(id)?.letterSpacing, id)
)
- .toBe(3)
+ .toEqual({ value: 3, unit: 'PIXELS' })
await expect(field).not.toHaveAttribute('data-bound')
await section.getByRole('heading', { name: 'Typography', exact: true }).click()
await page.keyboard.press(process.platform === 'darwin' ? 'Meta+z' : 'Control+z')
diff --git a/tests/e2e/properties/typography-panel.spec.ts b/tests/e2e/properties/typography-panel.spec.ts
index 4d68f709f..3ad3075f7 100644
--- a/tests/e2e/properties/typography-panel.spec.ts
+++ b/tests/e2e/properties/typography-panel.spec.ts
@@ -19,7 +19,8 @@ for (const theme of ['light', 'dark']) {
return id
}, theme)
const section = page.getByRole('region', { name: 'Typography', exact: true })
- await expect(section.locator('[data-property="letterSpacing"]')).toContainText('px')
+ // A new text has no letter spacing in percent, as Figma shows it.
+ await expect(section.locator('[data-property="letterSpacing"]')).toContainText('%')
await expect(section.locator('[data-property="lineHeight"]')).toContainText('Auto')
await expect(section).toHaveScreenshot(`typography-groups-${theme}.png`)
await section.getByRole('button', { name: 'Align center horizontally', exact: true }).click()
diff --git a/tests/e2e/properties/unresolved-binding.spec.ts b/tests/e2e/properties/unresolved-binding.spec.ts
index 26080fc4e..18b529309 100644
--- a/tests/e2e/properties/unresolved-binding.spec.ts
+++ b/tests/e2e/properties/unresolved-binding.spec.ts
@@ -26,7 +26,11 @@ for (const theme of ['light', 'dark']) {
const editor = window.openPencil?.getStore?.()
if (!editor) throw new Error('Editor unavailable')
const id = editor.createShape('TEXT', 100, 100, 240, 80)
- editor.updateNode(id, { text: 'Unavailable variable', fontSize: 24, letterSpacing: 2 })
+ editor.updateNode(id, {
+ text: 'Unavailable variable',
+ fontSize: 24,
+ letterSpacing: { value: 2, unit: 'PIXELS' }
+ })
const collection = editor.graph.createCollection('Typography')
const variable = editor.graph.createVariable(
'Tracking/Missing alias',
diff --git a/tests/engine/clipboard/figma/html.test.ts b/tests/engine/clipboard/figma/html.test.ts
index 470896a1a..7ecc5c951 100644
--- a/tests/engine/clipboard/figma/html.test.ts
+++ b/tests/engine/clipboard/figma/html.test.ts
@@ -6,6 +6,7 @@ import { parseFigmaClipboard } from '@open-pencil/fig/clipboard'
import { initCodec } from '@open-pencil/kiwi/fig/codec'
import { SceneGraph } from '@open-pencil/scene-graph'
import { slotPropertyId } from '@open-pencil/scene-graph/slots'
+import { pixelLength } from '@open-pencil/scene-graph/text'
import { expectDefined } from '#tests/helpers/assert'
@@ -16,7 +17,8 @@ function expectFigmaEditableTextDefaults(
expect(textNode.textExplicitLayoutVersion).toBe(1)
expect(textNode.textBidiVersion).toBe(1)
expect(textNode.lineHeight).toEqual({ value: 100, units: 'PERCENT' })
- expect(textNode.letterSpacing).toEqual({ value: 0, units: 'PIXELS' })
+ // Figma writes no letter spacing as zero percent.
+ expect(textNode.letterSpacing).toEqual({ value: 0, units: 'PERCENT' })
expect(textNode.fontVariantCommonLigatures).toBe(true)
expect(textNode.fontVariantContextualLigatures).toBe(true)
expect(textNode.textDecorationSkipInk).toBe(true)
@@ -173,7 +175,7 @@ describe('buildFigmaClipboardHTML', () => {
fontFamily: 'Missing Preview Font',
fontWeight: 700,
fontSize: 56,
- lineHeight: 67,
+ lineHeight: pixelLength(67),
textAutoResize: 'HEIGHT'
})
diff --git a/tests/engine/color/okhcl/basic.test.ts b/tests/engine/color/okhcl/basic.test.ts
index 6264218bf..7e0e2f1e0 100644
--- a/tests/engine/color/okhcl/basic.test.ts
+++ b/tests/engine/color/okhcl/basic.test.ts
@@ -15,7 +15,7 @@ import {
import { expectDefined } from '#tests/helpers/assert'
import { uint8ArrayToArrayBuffer } from '#tests/helpers/fig/fixtures'
-import { solidFill, solidStroke } from '#tests/helpers/plugin-api'
+import { solidFill } from '#tests/helpers/plugin-api'
describe('OkHCL metadata', () => {
test('applies rgba rendering color while preserving fill metadata', () => {
@@ -27,7 +27,9 @@ describe('OkHCL metadata', () => {
openpencil.setFillOkHCL(frame, { h: 240, c: 0.12, l: 0.7, a: 0.8 })
- expect(frame.fills[0]?.color).toEqual(okhclToRGBA({ h: 240, c: 0.12, l: 0.7, a: 0.8 }))
+ // The plugin API reads the alpha as the paint's opacity, as Figma does.
+ const { a: alpha, ...fillColor } = okhclToRGBA({ h: 240, c: 0.12, l: 0.7, a: 0.8 })
+ expect(frame.fills[0]).toMatchObject({ color: fillColor, opacity: alpha })
expect(openpencil.getFillOkHCL(frame)).toMatchObject({
version: 1,
kind: 'fill',
@@ -41,11 +43,14 @@ describe('OkHCL metadata', () => {
const api = new FigmaAPI(graph)
const openpencil = new OpenPencilAPI(api)
const frame = api.createFrame()
- frame.strokes = [solidStroke({ r: 0, g: 0, b: 0, a: 1 }, { weight: 1, align: 'INSIDE' })]
+ frame.strokes = [solidFill({ r: 0, g: 0, b: 0, a: 1 })]
+ frame.strokeWeight = 1
+ frame.strokeAlign = 'INSIDE'
openpencil.setStrokeOkHCL(frame, { h: 20, c: 0.08, l: 0.6 })
- expect(frame.strokes[0]?.color).toEqual(okhclToRGBA({ h: 20, c: 0.08, l: 0.6 }))
+ const { a: alpha, ...strokeColor } = okhclToRGBA({ h: 20, c: 0.08, l: 0.6 })
+ expect(frame.strokes[0]).toMatchObject({ color: strokeColor, opacity: alpha })
expect(openpencil.getStrokeOkHCL(frame)).toMatchObject({
version: 1,
kind: 'stroke',
@@ -72,7 +77,9 @@ describe('OkHCL metadata', () => {
const frame = api.createFrame()
frame.name = 'OKHCL frame'
frame.fills = [solidFill({ r: 0, g: 0, b: 0, a: 1 })]
- frame.strokes = [solidStroke({ r: 0, g: 0, b: 0, a: 1 }, { weight: 1, align: 'INSIDE' })]
+ frame.strokes = [solidFill({ r: 0, g: 0, b: 0, a: 1 })]
+ frame.strokeWeight = 1
+ frame.strokeAlign = 'INSIDE'
openpencil.setFillOkHCL(frame, { h: 210, c: 0.1, l: 0.65 })
openpencil.setStrokeOkHCL(frame, { h: 320, c: 0.09, l: 0.55, a: 0.9 })
diff --git a/tests/engine/core/editor/text/path-edit.test.ts b/tests/engine/core/editor/text/path-edit.test.ts
index abeff0c5a..91b045f72 100644
--- a/tests/engine/core/editor/text/path-edit.test.ts
+++ b/tests/engine/core/editor/text/path-edit.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, test } from 'bun:test'
import { SceneGraph } from '@open-pencil/scene-graph'
+import { pixelLength } from '@open-pencil/scene-graph/text'
import { pathTextEditChanges, resizedPathTextGlyphs } from '#core/editor/text/path-edit'
import { fontManager } from '#core/text/fonts'
@@ -102,7 +103,7 @@ describe('pathTextEditChanges — reflow on character edit', () => {
fontWeight: 400,
italic: false,
fontSize: 40,
- letterSpacing,
+ letterSpacing: pixelLength(letterSpacing),
textPathBox: { ...box },
derivedTextGlyphs: [
{ commandsBlob: new Uint8Array(4), x: 50, y: 50, fontSize: 40, rotation: 0 },
diff --git a/tests/engine/dom-css/conversion.test.ts b/tests/engine/dom-css/conversion.test.ts
index ca7536960..e7b757aa3 100644
--- a/tests/engine/dom-css/conversion.test.ts
+++ b/tests/engine/dom-css/conversion.test.ts
@@ -12,6 +12,7 @@ import { sceneGraphToDesignDocument, serializeHTML } from '@open-pencil/dom-css/
import { designDocumentToSceneGraph } from '@open-pencil/dom-css/scene-graph'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { parseColor } from '@open-pencil/scene-graph/color'
+import { pixelLength } from '@open-pencil/scene-graph/text'
import {
DOM_CSS_COLORS,
@@ -99,8 +100,8 @@ function expectStyleRoundTripText(graph: SceneGraph, panel: SceneNode) {
if (heading?.type !== 'TEXT') throw new Error('Expected text node')
expect(heading.fontSize).toBe(18)
expect(heading.fontWeight).toBe(700)
- expect(heading.lineHeight).toBe(24)
- expect(heading.letterSpacing).toBe(0.2)
+ expect(heading.lineHeight).toEqual(pixelLength(24))
+ expect(heading.letterSpacing).toEqual(pixelLength(0.2))
expect(heading.textAlignHorizontal).toBe('CENTER')
expect(heading.opacity).toBe(0.5)
expect(heading.effects[0]?.type).toBe('DROP_SHADOW')
diff --git a/tests/engine/io/fig/import/legacy/shared-styles.test.ts b/tests/engine/io/fig/import/legacy/shared-styles.test.ts
index add7852e6..18cbf92e6 100644
--- a/tests/engine/io/fig/import/legacy/shared-styles.test.ts
+++ b/tests/engine/io/fig/import/legacy/shared-styles.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, test } from 'bun:test'
import { materializeDocument } from '@open-pencil/fig'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { pixelLength } from '@open-pencil/scene-graph/text'
import { canvas, doc, node } from './helpers'
@@ -72,7 +73,7 @@ describe('fig-import: shared styles', () => {
gridStyleId: styleId('Grid/12 columns'),
fontSize: 18,
fontWeight: 700,
- lineHeight: 26,
+ lineHeight: pixelLength(26),
fills: [paint],
effects: [effect],
layoutGrids: [grid]
diff --git a/tests/engine/io/fig/import/legacy/text.test.ts b/tests/engine/io/fig/import/legacy/text.test.ts
index 79b0bae54..ad7112254 100644
--- a/tests/engine/io/fig/import/legacy/text.test.ts
+++ b/tests/engine/io/fig/import/legacy/text.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, test } from 'bun:test'
import { materializeDocument } from '@open-pencil/fig'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import type { SceneGraph } from '@open-pencil/scene-graph'
+import { lineHeightPixels } from '@open-pencil/scene-graph/text'
import { canvas, doc, node } from './helpers'
@@ -103,7 +104,7 @@ describe('fig-import: text properties', () => {
} as Partial<NodeChange>)
]).graph
const n = graph.getChildren(graph.getPages()[0].id)[0]
- expect(n.lineHeight).toBe(16.94)
+ expect(lineHeightPixels(n.lineHeight, n.fontSize)).toBe(16.94)
})
test('keeps a pixel line height shorter than the font, which Figma saves lines taller than', () => {
@@ -130,7 +131,8 @@ describe('fig-import: text properties', () => {
}
} as Partial<NodeChange>)
]).graph
- expect(graph.getChildren(graph.getPages()[0].id)[0]?.lineHeight).toBe(10)
+ const [text] = graph.getChildren(graph.getPages()[0].id)
+ expect(text && lineHeightPixels(text.lineHeight, text.fontSize)).toBe(10)
})
test('reads line heights as Figma writes them: auto as 100 percent, a percent as a multiplier', () => {
@@ -163,7 +165,7 @@ describe('fig-import: text properties', () => {
]).graph
const [auto, raw] = graph.getChildren(graph.getPages()[0].id)
expect(auto.lineHeight).toBeNull()
- expect(raw.lineHeight).toBe(36)
+ expect(lineHeightPixels(raw.lineHeight, raw.fontSize)).toBe(36)
})
test('applies shared text style refs', () => {
@@ -191,7 +193,7 @@ describe('fig-import: text properties', () => {
expect(styled?.fontSize).toBe(16)
expect(styleNamed(graph, styled?.textStyleId)).toBe('Body style')
expect(styled?.fontWeight).toBe(400)
- expect(styled?.lineHeight).toBe(24)
+ expect(styled && lineHeightPixels(styled.lineHeight, styled.fontSize)).toBe(24)
expect(styled?.textDecoration).toBe('NONE')
const style = [...graph.getAllNodes()].find((node) => node.source.id === '1:20')
expect(style).toMatchObject({ name: 'Body style', sharedStyleType: 'TEXT', internalOnly: true })
diff --git a/tests/engine/kiwi/serialize-fixes/integration.test.ts b/tests/engine/kiwi/serialize-fixes/integration.test.ts
index 7b9acfca6..f65c40975 100644
--- a/tests/engine/kiwi/serialize-fixes/integration.test.ts
+++ b/tests/engine/kiwi/serialize-fixes/integration.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, test } from 'bun:test'
import { exportFigFile, parseFigFile } from '@open-pencil/core/io/formats/fig'
import { sceneNodeToKiwi } from '@open-pencil/fig/node-change'
import { SceneGraph } from '@open-pencil/scene-graph'
+import { lineHeightPixels, pixelLength } from '@open-pencil/scene-graph/text'
import { expectDefined, getNodeOrThrow } from '#tests/helpers/assert'
@@ -43,7 +44,7 @@ describe('Integration: auto-layout component with all fixes', () => {
fontFamily: 'DM Sans 9pt',
fontWeight: 600,
fontSize: 14,
- lineHeight: 20
+ lineHeight: pixelLength(20)
})
// Value text
@@ -57,7 +58,7 @@ describe('Integration: auto-layout component with all fixes', () => {
fontFamily: 'Inter',
fontWeight: 700,
fontSize: 32,
- lineHeight: 40
+ lineHeight: pixelLength(40)
})
// Verify kiwi output directly
@@ -121,6 +122,6 @@ describe('Integration: auto-layout component with all fixes', () => {
expect(cardNode.layoutMode).toBe('VERTICAL')
expect(cardNode.clipsContent).toBe(true)
expect(titleNode.fontFamily).toBe('DM Sans')
- expect(titleNode.lineHeight).toBe(20)
+ expect(lineHeightPixels(titleNode.lineHeight, titleNode.fontSize)).toBe(20)
})
})
diff --git a/tests/engine/kiwi/serialize-fixes/line/height.test.ts b/tests/engine/kiwi/serialize-fixes/line/height.test.ts
index 5a7968d2a..e0e54775f 100644
--- a/tests/engine/kiwi/serialize-fixes/line/height.test.ts
+++ b/tests/engine/kiwi/serialize-fixes/line/height.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, test } from 'bun:test'
import { exportFigFile, parseFigFile } from '@open-pencil/core/io/formats/fig'
import { SceneGraph } from '@open-pencil/scene-graph'
+import { lineHeightPixels, pixelLength } from '@open-pencil/scene-graph/text'
import { expectDefined } from '#tests/helpers/assert'
@@ -20,7 +21,7 @@ describe('Fix 4: text lineHeight serialization', () => {
fontFamily: 'Inter',
fontWeight: 400,
fontSize: 16,
- lineHeight: 24
+ lineHeight: pixelLength(24)
})
const changes = toKiwi(node, graph)
@@ -57,7 +58,7 @@ describe('Fix 4: text lineHeight serialization', () => {
fontFamily: 'Inter',
fontWeight: 400,
fontSize: 16,
- lineHeight: 28
+ lineHeight: pixelLength(28)
})
const exported = await exportFigFile(graph)
@@ -67,7 +68,7 @@ describe('Fix 4: text lineHeight serialization', () => {
[...reimported.nodes.values()].find((n) => n.type === 'TEXT'),
'text node'
)
- expect(textNode.lineHeight).toBe(28)
+ expect(lineHeightPixels(textNode.lineHeight, textNode.fontSize)).toBe(28)
})
})
diff --git a/tests/engine/layout/auto-layout/text/measurement.test.ts b/tests/engine/layout/auto-layout/text/measurement.test.ts
index b41f0671c..83c73b28e 100644
--- a/tests/engine/layout/auto-layout/text/measurement.test.ts
+++ b/tests/engine/layout/auto-layout/text/measurement.test.ts
@@ -3,6 +3,7 @@ import { expect, test } from 'bun:test'
import { createEditor } from '@open-pencil/core'
import { computeAllLayouts, setTextMeasurer } from '@open-pencil/core/layout'
import { SceneGraph } from '@open-pencil/scene-graph'
+import { pixelLength } from '@open-pencil/scene-graph/text'
import { getNodeOrThrow } from '#tests/helpers/assert'
import { autoFrame, loadFixtureGraph, pageId, rect } from '#tests/helpers/layout'
@@ -342,7 +343,7 @@ heavy('text measurement', () => {
height: 66,
text: 'GDP Growth Exceeds Expectations at 3.1% in Q2 Report That Nobody Expected',
fontSize: 15,
- lineHeight: 22,
+ lineHeight: pixelLength(22),
textAutoResize: 'HEIGHT' as const
})
@@ -372,7 +373,7 @@ heavy('text measurement', () => {
height: 100,
text: 'GDP Growth Exceeds Expectations at 3.1% in Q2 Report That Nobody Expected',
fontSize: 15,
- lineHeight: 22,
+ lineHeight: pixelLength(22),
textAutoResize: 'HEIGHT' as const
})
diff --git a/tests/engine/mcp/tools.test.ts b/tests/engine/mcp/tools.test.ts
index d18180037..fdfa4ab91 100644
--- a/tests/engine/mcp/tools.test.ts
+++ b/tests/engine/mcp/tools.test.ts
@@ -147,9 +147,7 @@ describe('MCP tool execution', () => {
findTool('set_fill').execute(api, { id: frame.id, color: '#ff0000' })
const node = expectDefined(api.getNodeById(frame.id), 'filled rectangle')
expect(node.fills).toHaveLength(1)
- expect(expectFills(node.fills)[0].color.r).toBeCloseTo(1)
- expect(expectFills(node.fills)[0].color.g).toBeCloseTo(0)
- expect(expectFills(node.fills)[0].color.b).toBeCloseTo(0)
+ expect(expectFills(node.fills)[0]).toMatchObject({ color: { r: 1, g: 0, b: 0 } })
})
test('set_layout configures auto-layout', () => {
diff --git a/tests/engine/render/canvas/raster-export.test.ts b/tests/engine/render/canvas/raster-export.test.ts
index 47cca6a3d..3fc9f21d2 100644
--- a/tests/engine/render/canvas/raster-export.test.ts
+++ b/tests/engine/render/canvas/raster-export.test.ts
@@ -6,6 +6,7 @@ import { SkiaRenderer } from '@open-pencil/core/canvas'
import { renderNodesToImage } from '@open-pencil/core/io/formats/raster'
import { SceneGraph } from '@open-pencil/scene-graph'
import { getWorldMatrix } from '@open-pencil/scene-graph/coordinate'
+import { pixelLength } from '@open-pencil/scene-graph/text'
import { initCanvasKit } from '#cli/headless'
import { NodePathCaches } from '#core/canvas/paths/cache'
@@ -244,7 +245,7 @@ describe('raster export', () => {
height: 40,
text: 'Primitives',
fontSize: 30,
- lineHeight: 40,
+ lineHeight: pixelLength(40),
fills: [
{
type: 'SOLID',
diff --git a/tests/engine/render/canvas/text/preparation-cache.test.ts b/tests/engine/render/canvas/text/preparation-cache.test.ts
index 8c618692a..f4fa321d3 100644
--- a/tests/engine/render/canvas/text/preparation-cache.test.ts
+++ b/tests/engine/render/canvas/text/preparation-cache.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, test } from 'bun:test'
import type { CanvasKit } from 'canvaskit-wasm'
import { SceneGraph } from '@open-pencil/scene-graph'
+import { pixelLength } from '@open-pencil/scene-graph/text'
import { initCanvasKit } from '#cli/headless'
import { buildParagraph, nodeFontReadiness } from '#core/canvas/text'
@@ -252,8 +253,8 @@ describe('text preparation cache', () => {
textLanguage: 'ar',
textDirection: 'RTL',
textCase: 'UPPER',
- letterSpacing: 2,
- lineHeight: 30,
+ letterSpacing: pixelLength(2),
+ lineHeight: pixelLength(30),
textAlignHorizontal: 'CENTER',
leadingTrim: 'CAP_HEIGHT',
textDecoration: 'UNDERLINE',
diff --git a/tests/engine/render/canvas/text/render.test.ts b/tests/engine/render/canvas/text/render.test.ts
index e9f0fa487..c3aff3726 100644
--- a/tests/engine/render/canvas/text/render.test.ts
+++ b/tests/engine/render/canvas/text/render.test.ts
@@ -5,6 +5,7 @@ import { describe, test, expect, mock, spyOn } from 'bun:test'
import { SkiaRenderer as SkiaRendererClass } from '@open-pencil/core/canvas'
import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
import { createDefaultNode } from '@open-pencil/scene-graph/node-defaults'
+import { pixelLength } from '@open-pencil/scene-graph/text'
import { detectTextDirection, resolveTextDirection } from '@open-pencil/scene-graph/text/direction'
import { initCanvasKit } from '#cli/headless'
@@ -109,7 +110,7 @@ function textNode(overrides: Partial<SceneNode> = {}): SceneNode {
fontFamily: 'Arial',
fontWeight: 400,
italic: false,
- letterSpacing: 0,
+ letterSpacing: pixelLength(0),
lineHeight: null,
textAlignHorizontal: 'LEFT',
textAlignVertical: 'TOP',
diff --git a/tests/engine/render/jsx/reference.test.ts b/tests/engine/render/jsx/reference.test.ts
index c6612f58f..448e49129 100644
--- a/tests/engine/render/jsx/reference.test.ts
+++ b/tests/engine/render/jsx/reference.test.ts
@@ -3,6 +3,7 @@ import { expect, test } from 'bun:test'
import { renderJSX } from '@open-pencil/core/design-jsx'
import { CODEGEN_PROMPT as BARREL_CODEGEN, CODEGEN_PROMPT } from '@open-pencil/core/tools'
import { AUTHORING_EXAMPLES, JSX_REFERENCE } from '@open-pencil/design-jsx'
+import { pixelLength } from '@open-pencil/scene-graph/text'
import SYSTEM_PROMPT from '@/app/ai/chat/system-prompt'
@@ -75,8 +76,8 @@ test('shared bound example retains bindings and resolves the initial inherited m
})
const [text] = graph.getChildren(bound.id)
expect(text.fontSize).toBe(11)
- expect(text.lineHeight).toBe(16)
- expect(text.letterSpacing).toBe(0)
+ expect(text.lineHeight).toEqual(pixelLength(16))
+ expect(text.letterSpacing).toEqual(pixelLength(0))
expect(text.boundVariables).toMatchObject({
fontSize: 'Type/body',
lineHeight: 'Type/body-leading',
diff --git a/tests/engine/render/jsx/text-props.test.ts b/tests/engine/render/jsx/text-props.test.ts
index 7118f3221..13d9b24e7 100644
--- a/tests/engine/render/jsx/text-props.test.ts
+++ b/tests/engine/render/jsx/text-props.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'bun:test'
import { renderJSX } from '@open-pencil/core/design-jsx'
import { sceneNodeToJSX } from '@open-pencil/design-jsx'
+import { percentLength, pixelLength } from '@open-pencil/scene-graph/text'
import { getNodeOrThrow, childIdAt } from '#tests/helpers/assert'
import { makeSceneGraph } from '#tests/helpers/scene'
@@ -11,7 +12,7 @@ describe('text props round-trip', () => {
const g = makeSceneGraph()
const [result] = await renderJSX(g, '<Text color="#000" lineHeight={24}>Hello</Text>')
const n = getNodeOrThrow(g, result.id)
- expect(n.lineHeight).toBe(24)
+ expect(n.lineHeight).toEqual(pixelLength(24))
const jsx = sceneNodeToJSX(n.id, g)
expect(jsx).toContain('lineHeight={24}')
})
@@ -20,7 +21,7 @@ describe('text props round-trip', () => {
const g = makeSceneGraph()
const [result] = await renderJSX(g, '<Text color="#000" letterSpacing={2}>Spaced</Text>')
const n = getNodeOrThrow(g, result.id)
- expect(n.letterSpacing).toBe(2)
+ expect(n.letterSpacing).toEqual(pixelLength(2))
const jsx = sceneNodeToJSX(n.id, g)
expect(jsx).toContain('letterSpacing={2}')
})
@@ -97,7 +98,7 @@ describe('text props round-trip', () => {
const [result] = await renderJSX(g, '<Text color="#000">Plain</Text>')
const n = getNodeOrThrow(g, result.id)
expect(n.lineHeight).toBeNull()
- expect(n.letterSpacing).toBe(0)
+ expect(n.letterSpacing).toEqual(percentLength(0))
expect(n.textDecoration).toBe('NONE')
expect(n.textCase).toBe('ORIGINAL')
expect(n.maxLines).toBeNull()
diff --git a/tests/engine/tools/ai-adapter.test.ts b/tests/engine/tools/ai-adapter.test.ts
index 929c51908..6e8f6d670 100644
--- a/tests/engine/tools/ai-adapter.test.ts
+++ b/tests/engine/tools/ai-adapter.test.ts
@@ -108,8 +108,7 @@ describe('AI adapter', () => {
await setFill.execute({ id: rect.id, color: '#00ff00' })
const fills = expectFills(expectDefined(figma.getNodeById(rect.id), 'filled rectangle').fills)
- expect(fills.length).toBe(1)
- expect(fills[0].color.g).toBeCloseTo(1)
+ expect(fills).toEqual([expect.objectContaining({ color: { r: 0, g: 1, b: 0 } })])
})
test('get_page_tree tool returns structure', async () => {
diff --git a/tests/engine/tools/modify.test.ts b/tests/engine/tools/modify.test.ts
index 37cad4ee1..f3a2adc86 100644
--- a/tests/engine/tools/modify.test.ts
+++ b/tests/engine/tools/modify.test.ts
@@ -17,10 +17,7 @@ describe('set_fill', () => {
tool.execute(figma, { id: frame.id, color: '#ff0000' })
const fills = expectFills(expectDefined(figma.getNodeById(frame.id), 'frame node').fills)
- expect(fills.length).toBe(1)
- expect(fills[0].color.r).toBeCloseTo(1)
- expect(fills[0].color.g).toBeCloseTo(0)
- expect(fills[0].color.b).toBeCloseTo(0)
+ expect(fills).toEqual([expect.objectContaining({ color: { r: 1, g: 0, b: 0 } })])
})
test('returns error for missing node', () => {
@@ -40,10 +37,9 @@ describe('set_stroke', () => {
const tool = getTool('set_stroke')
tool.execute(figma, { id: rect.id, color: '#0000ff', weight: 2 })
- const strokes = expectDefined(figma.getNodeById(rect.id), 'rectangle node').strokes
- expect(strokes.length).toBe(1)
- expect(strokes[0].color.b).toBeCloseTo(1)
- expect(strokes[0].weight).toBe(2)
+ const node = expectDefined(figma.getNodeById(rect.id), 'rectangle node')
+ expect(node.strokes).toEqual([expect.objectContaining({ color: { r: 0, g: 0, b: 1 } })])
+ expect(node.strokeWeight).toBe(2)
})
})
diff --git a/tests/engine/tools/modify/image-fill.test.ts b/tests/engine/tools/modify/image-fill.test.ts
index e4d52b2f9..65d0b9835 100644
--- a/tests/engine/tools/modify/image-fill.test.ts
+++ b/tests/engine/tools/modify/image-fill.test.ts
@@ -46,9 +46,11 @@ describe('set_image_fill tool', () => {
const fills = expectFills(expectDefined(figma.getNodeById(node.id), 'image-filled node').fills)
expect(fills).toHaveLength(1)
- expect(fills[0].type).toBe('IMAGE')
- expect(fills[0].imageHash).toBe(result.imageHash)
- expect(fills[0].imageScaleMode).toBe('FILL')
+ expect(fills[0]).toMatchObject({
+ type: 'IMAGE',
+ imageHash: result.imageHash,
+ scaleMode: 'FILL'
+ })
})
test('returns error for non-existent node', () => {
@@ -101,7 +103,7 @@ describe('set_image_fill tool', () => {
const fills = expectFills(
expectDefined(figma.getNodeById(node.id), 'image-filled node').fills
)
- expect(fills[0].imageScaleMode).toBe(mode)
+ expect(fills[0]).toMatchObject({ scaleMode: mode })
}
})
diff --git a/tests/engine/vue/controls/shared-style.test.ts b/tests/engine/vue/controls/shared-style.test.ts
index ff0821ab8..7d65bb9ba 100644
--- a/tests/engine/vue/controls/shared-style.test.ts
+++ b/tests/engine/vue/controls/shared-style.test.ts
@@ -4,6 +4,7 @@ import { createEditor } from '@open-pencil/core'
import { effectiveFigmaRawNodeFields } from '@open-pencil/fig'
import type { Effect, Fill, SceneNode } from '@open-pencil/scene-graph'
import { getSharedStyles } from '@open-pencil/scene-graph/shared-styles'
+import { pixelLength } from '@open-pencil/scene-graph/text'
import { sharedStyleDetachPatch, sharedStylePatch } from '#vue/controls/shared-style/model'
@@ -58,7 +59,7 @@ describe('shared style model', () => {
fontFamily: 'Inter',
fontSize: 24,
fontWeight: 700,
- lineHeight: 32,
+ lineHeight: pixelLength(32),
textCase: 'UPPER'
})
const effect: Effect = {
@@ -78,7 +79,7 @@ describe('shared style model', () => {
textStyleId: '1:21',
fontSize: 24,
fontWeight: 700,
- lineHeight: 32,
+ lineHeight: pixelLength(32),
textCase: 'UPPER'
})
expect(sharedStylePatch('effect', target, '1:22', effectStyle)).toMatchObject({
diff --git a/tests/helpers/plugin-api.ts b/tests/helpers/plugin-api.ts
index 995bf7ca3..df3b83157 100644
--- a/tests/helpers/plugin-api.ts
+++ b/tests/helpers/plugin-api.ts
@@ -1,5 +1,5 @@
import { FigmaAPI, type FigmaNodeProxy } from '@open-pencil/core/figma-api'
-import { SceneGraph, type Fill, type Stroke } from '@open-pencil/scene-graph'
+import { SceneGraph, type Fill } from '@open-pencil/scene-graph'
import type { Color } from '@open-pencil/scene-graph/primitives'
// Plugin API support for the render and colour suites still under tests/engine. Core's own Plugin
@@ -23,10 +23,3 @@ type SolidFill = Omit<Fill, 'gradientTransform' | 'imageTransform'> & SolidPaint
export function solidFill(color: Color): SolidFill {
return { type: 'SOLID', color, opacity: 1, visible: true }
}
-
-export function solidStroke(
- color: Color,
- stroke: { weight: number; align: Stroke['align'] }
-): SolidFill & Pick<Stroke, 'weight' | 'align'> {
- return { ...solidFill(color), weight: stroke.weight, align: stroke.align }
-}
diff --git a/tools/checks/package-quality/src/smoke/scenarios.ts b/tools/checks/package-quality/src/smoke/scenarios.ts
index 9299365ae..2b65ef10e 100644
--- a/tools/checks/package-quality/src/smoke/scenarios.ts
+++ b/tools/checks/package-quality/src/smoke/scenarios.ts
@@ -18,7 +18,7 @@ export const runtimeScenarios: RuntimeScenario[] = [
},
{
name: 'FIG NodeChange API',
- code: "const { convertLineHeight, sceneNodeToKiwi } = await import('@open-pencil/fig/node-change'); if (convertLineHeight({ value: 120, units: 'PERCENT' }, 20) !== 24 || typeof sceneNodeToKiwi !== 'function') throw new Error('Fig NodeChange subpath failed')"
+ code: "const { convertLineHeight, sceneNodeToKiwi } = await import('@open-pencil/fig/node-change'); const lineHeight = convertLineHeight({ value: 1.5, units: 'RAW' }); if (lineHeight?.unit !== 'PERCENT' || lineHeight.value !== 150 || typeof sceneNodeToKiwi !== 'function') throw new Error('Fig NodeChange subpath failed')"
},
{
name: 'FIG instance override API',