AI-native design editor. Open-source Figma alternative.
fix(text): keep text faithful through Figma, Design JSX, and the Code tab (#1084)
Danila Poyarkovdd99b0d740d3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a5a675f06..61f72b97f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -55,7 +55,7 @@### Added- While text is being edited, the Fill and Typography fields show and change the style of the selected characters, as in Figma, instead of the whole layer.-- Design JSX writes rich text: `<Span>` styles characters with `<Text>`'s own props, and `<Paragraph>` makes a paragraph with `list`, `level`, `spacing`, `listSpacing`, and `indent`. Exporting a text layer to design JSX writes them back.+- Design JSX writes rich text: `<Span>` styles characters with `<Text>`'s own props, and `<Paragraph>` makes a paragraph with `list`, `level`, `spacing`, `listSpacing`, and `indent`. `<Text>` and `<Span>` take `textDecorationStyle`, `textDecorationColor`, `textDecorationThickness`, `textUnderlineOffset`, and `textDecorationSkipInk`, and `<Text>` takes `paragraphSpacing`, `listSpacing`, `paragraphIndent`, and `hangingList`. Exporting a text layer to design JSX writes them back, and the Code tab keeps a text's spans and paragraphs when the layer and edited code change.- Scripts style text by character range, as in Figma: `getStyledTextSegments` and `getRange` / `setRange` methods for font name and size, fills, letter spacing, line height, and decoration with its style, offset, thickness, colour, and skip ink. The `set_font_range` AI and MCP tool uses them.- Bulleted and numbered lists in text, as in Figma: `.fig` files and the Figma clipboard keep each paragraph's list type, nesting, list and paragraph spacing, and first-line indent, and the text's hanging markers, and the canvas lays lists out as Figma does, with markers centred or ending a third of an em before the item, numbers counting 1, a, i as they nest, and wrapped lines hanging at the indent. Set a list's style, list and paragraph spacing, paragraph indent, and hanging markers in the Typography section, for the paragraphs being edited or the whole text; while editing, <kbd>⇧</kbd><kbd>⌘</kbd><kbd>8</kbd> and <kbd>⇧</kbd><kbd>⌘</kbd><kbd>7</kbd> make bulleted and numbered lists, <kbd>Tab</kbd> and <kbd>⇧</kbd><kbd>Tab</kbd> nest and unnest items, and text you type into a list continues it. Flattening or outlining text keeps its markers. Scripts read and set lists with `getRangeListOptions`, `setRangeListOptions`, `getRangeIndentation`, `setRangeIndentation`, `listSpacing`, `paragraphSpacing`, `paragraphIndent`, their `getRange` and `setRange` methods, and `hangingList`.- Drag several layers along an auto layout row or column together, as in Figma: they move as one block in their order, wherever you grab them, and layers selected in different rows each move along their own row. A layer dragged along a flow takes the next slot once its leading edge reaches the next layer's centre, as Figma reorders, instead of once the cursor does.@@ -191,7 +191,8 @@- Crash recovery, chat history, diagnostics, local files, libraries, saved credentials, and the sync outbox keep saving after Safari suspends the tab. Safari closes their IndexedDB connections without telling the page, and every later write failed with "The database connection is closing" until the page was reloaded.- HTML, Tailwind JSX, and Vue and React exports keep a text's character styles as spans, its lists as nested lists with Figma's markers, its paragraph spacing and first-line indent, and its decoration style, colour, thickness, offset, and skip ink, where they wrote the whole text in one style. Importing HTML reads them back: inline formatting and box-less paragraphs, headings, and lists join into one text layer.- Underlines and strikethroughs are drawn where and as Figma draws them, from the font's own metrics: underlines break around descenders, dotted ones are round dots, and a set offset or thickness is kept, in reopened `.fig` files too, which drew no strikethroughs and misplaced the other styles. Text saved to `.fig` or copied to Figma keeps its decorations there, where Figma showed underlined text without them and underlined text over several lines not at all.-- Text that mixes font sizes keeps its auto line height when a `.fig` file OpenPencil saved is reopened. Every line took the height of the first, which pushed later lines down and cut them off.+- Text in auto line height stays in auto when a `.fig` file is opened, OpenPencil's or Figma's, and saving writes auto as Figma does. Text that mixed font sizes took the height of its first line for every line, which pushed later lines down and cut them off.+- Text saved to `.fig` or copied to Figma shows there when part of it is drawn in a fallback font, its font is missing or variable, or it is truncated, where Figma showed it blank, since Figma draws such text only from saved glyph outlines. Truncated text saves the characters it shows and its ellipsis, and Figma files show truncated text without the characters Figma hides.- Instances follow their component's structure as in Figma: wrapping a layer of the component in auto layout or a frame, or moving it into another frame of the component, moves the layer's copy in every instance with its overrides instead of adding a fresh copy beside the old one, and moving a layer out of the component or deleting it removes its copy from every instance, while undo brings the copies back with their overrides.- Dragging a number field in the properties panel moves its value in whole steps instead of fractions on high-density screens.- While text is being edited, its caret and selection follow a property dragged in the panel instead of catching up when the mouse is released.diff --git a/packages/core/src/canvas/text/placed.ts b/packages/core/src/canvas/text/placed.tsindex 54519887a..7487a1d8e 100644--- a/packages/core/src/canvas/text/placed.ts+++ b/packages/core/src/canvas/text/placed.ts@@ -2,9 +2,11 @@ import type { Paragraph } from 'canvaskit-wasm'import type { SceneNode } from '@open-pencil/scene-graph'+import { resolveParagraphFontFamilies } from '#core/canvas/text/font-families'import type { TextLayout, TextLayoutMarker } from '#core/canvas/text/layout'+import { textFontVariations } from '#core/canvas/text/paragraph'import { utf16IndicesByUtf8 } from '#core/canvas/text/utf8'-import { weightToStyle } from '#core/text/fonts'+import { fontManager, fontWeightMatchOrder, weightToStyle } from '#core/text/fonts'import { glyphOutlineSourceSync, type GlyphOutlineSource } from '#core/text/opentype'type GlyphRun = ReturnType<Paragraph['getShapedLines']>[number]['runs'][number]@@ -26,18 +28,66 @@ export interface LaidOutGlyph {source: GlyphOutlineSource | null}-function fontStyleAt(node: SceneNode, index: number): { family: string; style: string } {+/**+ * The loaded face of a family the paragraph draws a style in: the style itself, or the nearest+ * loaded weight in the same slant, then the other, as font matching picks it.+ */+function loadedStyle(family: string, weight: number, italic: boolean): string | null {+ for (const slant of [italic, !italic]) {+ for (const candidate of fontWeightMatchOrder(weight)) {+ const style = weightToStyle(candidate, slant)+ if (fontManager.isStyleLoaded(family, style)) return style+ }+ }+ return null+}++/** The font a character asks for: its family, weight, and slant, and the variable axes it sets. */+function fontAt(node: SceneNode, index: number) {const run = node.styleRuns.find((item) => index >= item.start && index < item.start + item.length)- return {- family: run?.style.fontFamily ?? node.fontFamily,- style: weightToStyle(run?.style.fontWeight ?? node.fontWeight, run?.style.italic ?? node.italic)+ const family = run?.style.fontFamily ?? node.fontFamily+ const weight = run?.style.fontWeight ?? node.fontWeight+ const italic = run?.style.italic ?? node.italic+ const style = weightToStyle(weight, italic)+ const variations =+ textFontVariations(+ run?.style.fontVariations ?? node.fontVariations,+ fontManager.namedInstanceVariations(family, style)+ ) ?? []+ return { family, weight, italic, style, variations }+}++/** The outline source of each font the paragraph may have drawn a character in, in its order. */+function* candidateSources(font: ReturnType<typeof fontAt>) {+ for (const family of resolveParagraphFontFamilies(font.family, font.style)) {+ const style = loadedStyle(family, font.weight, font.italic)+ const source = style ? glyphOutlineSourceSync(family, style, font.variations) : null+ if (source) yield source+ }+}++/** Whether a glyph the shaper chose is the one the font maps its character to. */+function drawsOwnGlyph(+ source: GlyphOutlineSource,+ run: GlyphRun,+ text: string,+ characterAt: (offset: number) => number+): boolean {+ for (let index = 0; index < run.glyphs.length; index++) {+ const start = characterAt(run.offsets[index])+ const end = characterAt(run.offsets[index + 1])+ // A glyph for one character, not a ligature or a cluster, maps straight from it.+ if (end - start !== 1 || /\s/.test(text[start])) continue+ if (source.glyphOf(text[start]) === run.glyphs[index]) return true}+ return false}/**- * The font a run was shaped with. CanvasKit leaves `GlyphRun.typeface` null, so the run's- * glyph IDs are trusted only when the style's own font covers every character of the run and- * so the paragraph had no reason to fall back to another font.+ * The font a run was shaped with. CanvasKit leaves `GlyphRun.typeface` null, so the run's font+ * is found as the paragraph falls back: the first of the fonts it lists, the style's own then+ * its fallbacks, that has every character of the run, confirmed by the glyph IDs it chose.+ * Glyphs CanvasKit emboldened or slanted itself match no font's outlines.*/function runOutlineSource(node: SceneNode,@@ -49,10 +99,31 @@ function runOutlineSource(const offsets = Array.from(run.offsets, characterAt)const start = Math.min(...offsets)const end = Math.max(...offsets)- const { family, style } = fontStyleAt(node, start)- const source = glyphOutlineSourceSync(family, style)const characters = text.slice(start, end).replace(/\s/g, '')- return source?.covers(characters) ? source : null+ for (const source of candidateSources(fontAt(node, start))) {+ if (!source.covers(characters)) continue+ if (characters === '' || drawsOwnGlyph(source, run, text, characterAt)) return source+ }+ return null+}++/** What truncated text ends in, as the paragraph builds it. */+const ELLIPSIS = '…'++/**+ * The font of the ellipsis that ends truncated text, when the run is that ellipsis: the+ * paragraph adds it after the last characters shown, from the first font that maps it.+ */+function ellipsisSource(+ node: SceneNode,+ run: GlyphRun,+ characterAt: (offset: number) => number+): GlyphOutlineSource | null {+ if (run.glyphs.length !== 1 || run.fakeBold || run.fakeItalic) return null+ for (const source of candidateSources(fontAt(node, characterAt(run.offsets[0])))) {+ if (source.glyphOf(ELLIPSIS) === run.glyphs[0]) return source+ }+ return null}/**@@ -104,8 +175,13 @@ export function laidOutGlyphs(const marker = markers.get(lineIndex)if (marker) glyphs.push(...markerGlyphs(marker, offsetY))const { left, baseline } = metrics[lineIndex]- for (const run of line.runs) {- const source = runOutlineSource(node, text, run, characterAt)+ const lastLine = lineIndex === lines.length - 1+ for (const [runIndex, run] of line.runs.entries()) {+ const ellipsis =+ lastLine && runIndex === line.runs.length - 1 && layout.didExceedMaxLines()+ ? ellipsisSource(node, run, characterAt)+ : null+ const source = ellipsis ?? runOutlineSource(node, text, run, characterAt)for (let index = 0; index < run.glyphs.length; index++) {const x = run.positions[index * 2]glyphs.push({@@ -114,7 +190,8 @@ export function laidOutGlyphs(// Run positions round the baseline to whole pixels; line metrics keep it exact.y: baseline + offsetY,fontSize: run.size,- firstCharacter: characterAt(run.offsets[index]),+ // The ellipsis truncation adds draws no character, as Figma saves it.+ firstCharacter: ellipsis ? undefined : characterAt(run.offsets[index]),advance: run.positions[(index + 1) * 2] - x,lineLeft: left,sourcediff --git a/packages/core/src/canvas/text/shape.ts b/packages/core/src/canvas/text/shape.tsindex a5ad1a8b0..0bebdfff1 100644--- a/packages/core/src/canvas/text/shape.ts+++ b/packages/core/src/canvas/text/shape.ts@@ -19,16 +19,12 @@ import { transformTextCase } from '#core/text/case'import { fontManager } from '#core/text/fonts'/**- * Whether saved glyphs could stand for this text: truncation and case changes that alter its- * length move glyphs off the characters they came from, and path text is placed along its path.+ * Whether saved glyphs could stand for this text: case changes that alter its length move+ * glyphs off the characters they came from, and path text is placed along its path. Truncated+ * text saves the characters it shows and the ellipsis after them.*/function canShape(node: SceneNode, text: string): boolean {- return (- node.text.length > 0 &&- node.textTruncation !== 'ENDING' &&- text.length === node.text.length &&- !node.textPathData- )+ return node.text.length > 0 && text.length === node.text.length && !node.textPathData}/** Characters inside a glyph cluster or without a glyph take the offset of the one before. */diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex b80a0d5da..c44945ade 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -160,6 +160,7 @@ export {FontManager,chooseLocalFontMatch,fontManager,+ fontWeightMatchOrder,styleToWeight,weightToFigmaStyle,weightToStyle,diff --git a/packages/core/src/text/font/style.ts b/packages/core/src/text/font/style.tsindex 50f748d07..3e7a9c643 100644--- a/packages/core/src/text/font/style.ts+++ b/packages/core/src/text/font/style.ts@@ -1,4 +1,4 @@-import { normalizeFontFamily } from '@open-pencil/scene-graph'+import { FONT_WEIGHT_NAMES, normalizeFontFamily } from '@open-pencil/scene-graph'import type { FontFamilyStyle } from '@open-pencil/scene-graph'export {@@ -11,6 +11,30 @@ export {import { parseFontStyle } from '#core/text/face'+const FONT_WEIGHTS = Object.keys(FONT_WEIGHT_NAMES)+ .map(Number)+ .toSorted((a, b) => a - b)++/**+ * Font weights in the order CSS font matching tries them for `weight`, as Skia picks a face+ * from a family: heavier first above 500, lighter first below 400, and from 400 to 500 the+ * weights up to 500, then lighter, then heavier.+ */+export function fontWeightMatchOrder(weight: number): number[] {+ const lighter = FONT_WEIGHTS.filter((candidate) => candidate < weight).toReversed()+ const heavier = FONT_WEIGHTS.filter((candidate) => candidate > weight)+ const own = FONT_WEIGHTS.includes(weight) ? [weight] : []+ if (weight > 500) return [...own, ...heavier, ...lighter]+ if (weight < 400) return [...own, ...lighter, ...heavier]+ const upTo500 = heavier.filter((candidate) => candidate <= 500)+ return [...own, ...upTo500, ...lighter, ...heavier.filter((candidate) => candidate > 500)]+}++/**+ * A local font for a family and style. A style asked for is matched exactly, by name or by+ * weight and slant, since the face is registered as that style; without one, the face CSS+ * font matching would pick for the regular style.+ */export function chooseLocalFontMatch<T extends FontFamilyStyle>(fonts: T[],family: string,@@ -35,10 +59,15 @@ export function chooseLocalFontMatch<T extends FontFamilyStyle>(if (sameStyle) return sameStyleif (style) continue- const sameSlant = candidates.filter(- (font) => parseFontStyle(font.style).italic === requested.italic- )- if (sameSlant.length > 0) return sameSlant[0]+ for (const italic of [requested.italic, !requested.italic]) {+ for (const weight of fontWeightMatchOrder(requested.weight)) {+ const match = candidates.find((font) => {+ const parsed = parseFontStyle(font.style)+ return parsed.weight === weight && parsed.italic === italic+ })+ if (match) return match+ }+ }if (candidates.length > 0) return candidates[0]}diff --git a/packages/core/src/text/opentype.ts b/packages/core/src/text/opentype.tsindex 81429b868..491ab4c7c 100644--- a/packages/core/src/text/opentype.ts+++ b/packages/core/src/text/opentype.ts@@ -1,5 +1,7 @@import * as OpenTypeSync from 'opentype.js'+import type { FontVariation } from '@open-pencil/scene-graph'+import { fontManager } from './fonts'export interface OutlineCommand {@@ -19,7 +21,13 @@ interface OutlinePath {interface OutlineGlyph {path: OutlinePathadvanceWidth?: number- getPath(x: number, y: number, fontSize: number): OutlinePath+ getPath(+ x: number,+ y: number,+ fontSize: number,+ options?: { variation?: Record<string, number> },+ font?: OutlineFont+ ): OutlinePath}interface OutlineFont {@@ -224,25 +232,34 @@ export function getGlyphOutlineMetricsSync(}}-/** Outlines of one loaded static font, addressed by the glyph IDs a shaper produced. */+/** Outlines of one loaded font, addressed by the glyph IDs a shaper produced. */export interface GlyphOutlineSource {/** Whether the font has a glyph for every code point, so a shaper used it rather than a fallback. */covers(text: string): boolean+ /** The glyph the font maps `character` to, to check a shaper's glyph IDs are this font's. */+ glyphOf(character: string): numberoutline(glyphId: number, fontSize: number): OutlineCommand[] | null}/**- * Glyph outlines by glyph ID for a loaded font, or `null` when it is not loaded, cannot be- * parsed, or is variable: opentype.js draws a variable font's default instance, not the- * instance a shaper used.+ * Glyph outlines by glyph ID for a loaded font, or `null` when it is not loaded or cannot be+ * parsed. A variable font draws the instance at `variations`, the axis values the shaper used.*/-export function glyphOutlineSourceSync(family: string, style: string): GlyphOutlineSource | null {+export function glyphOutlineSourceSync(+ family: string,+ style: string,+ variations: readonly FontVariation[] = []+): GlyphOutlineSource | null {const font = getParsedFont(family, style)- if (!font || font.tables.fvar) return null+ if (!font) return null+ const variation = font.tables.fvar+ ? { variation: Object.fromEntries(variations.map(({ axis, value }) => [axis, value])) }+ : undefinedreturn {covers: (text) => Array.from(text).every((char) => font.charToGlyphIndex(char) !== 0),+ glyphOf: (character) => font.charToGlyphIndex(character),outline: (glyphId, fontSize) =>- font.glyphs.get(glyphId)?.getPath(0, 0, fontSize).commands ?? null+ font.glyphs.get(glyphId)?.getPath(0, 0, fontSize, variation, font).commands ?? null}}diff --git a/packages/core/tests/canvas/text/shape.test.ts b/packages/core/tests/canvas/text/shape.test.tsindex 6cf7382ad..9467a68b3 100644--- a/packages/core/tests/canvas/text/shape.test.ts+++ b/packages/core/tests/canvas/text/shape.test.ts@@ -1,6 +1,9 @@import { beforeAll, describe, expect, test } from 'bun:test'+import { join } from 'node:path'+import { expectDefined } from '#core-tests/helpers/assert'+import { FIXTURES } from '#core-tests/helpers/paths'import type { ShapedText } from '@open-pencil/fig/node-change'import { SceneGraph } from '@open-pencil/scene-graph'@@ -11,6 +14,8 @@ import { getCanvasKit } from '#core/canvaskit'import { fontManager } from '#core/text/fonts'import { getGlyphOutlineMetricsSync } from '#core/text/opentype'+const testFont = (name: string) => join(FIXTURES, 'fonts', name)+const SENTENCE = 'A sentence long enough that it has to wrap onto a second line.'async function shape(props: Partial<SceneNode>): Promise<ShapedText | null> {@@ -84,14 +89,18 @@ describe('text shaping for saved glyphs', () => {expect(shaped.logicalIndexToCharacterOffsetMap[2]).toBe(arrow.x)})- test('keeps the layout but no outlines when the font is not loaded', async () => {+ test('outlines text whose font is not loaded in the font that drew it instead', async () => {+ // The canvas draws it in the default font, and Figma shows nothing for glyphs without outlines.const shaped = expectDefined(- await shape({ text: SENTENCE, fontFamily: 'Missing Font' }),+ await shape({ text: 'Missing', fontFamily: 'Missing Font' }),'shaped text')+ const first = expectDefined(shaped.glyphs[0]?.commands, 'outline')- expect(shaped.baselines.length).toBeGreaterThan(1)- expect(shaped.glyphs.every((glyph) => glyph.commands === null)).toBe(true)+ expect(shaped.glyphs.every((glyph) => glyph.commands !== null)).toBe(true)+ expect(first).toEqual(+ expectDefined(getGlyphOutlineMetricsSync('Inter', 'Regular', 'M', 13)?.[0]).commands+ )})test('keeps outlines for decorations across lines, which Figma draws from saved rects', async () => {@@ -104,7 +113,62 @@ describe('text shaping for saved glyphs', () => {expect(shaped.glyphs.every((glyph) => glyph.commands !== null)).toBe(true)})- test('does not shape truncated text', async () => {- expect(await shape({ text: SENTENCE, textTruncation: 'ENDING' })).toBeNull()+ test('saves truncated text as the characters it shows and the ellipsis after them', async () => {+ // Figma draws pasted text only from its saved glyphs, so truncated text needs them too.+ const shaped = expectDefined(+ await shape({ text: SENTENCE, textTruncation: 'ENDING', height: 16, textAutoResize: 'NONE' }),+ 'shaped text'+ )+ const ellipsis = expectDefined(shaped.glyphs.at(-1), 'ellipsis')++ expect(shaped.baselines).toHaveLength(1)+ expect(shaped.glyphs.every((glyph) => glyph.commands !== null)).toBe(true)+ expect(ellipsis.firstCharacter).toBeUndefined()+ const shown = shaped.glyphs.slice(0, -1)+ expect(shown.every((glyph) => (glyph.firstCharacter ?? Infinity) < SENTENCE.length)).toBe(true)+ })++ test('outlines characters a fallback font draws from that font', async () => {+ const fallbackFamilies = fontManager.getCJKFallbackFamilies()+ const originalFallbacks = [...fallbackFamilies]+ fallbackFamilies.length = 0+ try {+ const cjk = await Bun.file(testFont('NotoSansCJK-Test.otf')).arrayBuffer()+ fontManager.markLoaded('Shape Test CJK', 'Regular', cjk)+ fontManager.setCJKFallbackFamily('Shape Test CJK')+ const shaped = expectDefined(await shape({ text: 'Hi 你好' }), 'shaped text')+ const ni = expectDefined(+ shaped.glyphs.find((glyph) => glyph.firstCharacter === 3),+ 'glyph of 你'+ )++ expect(shaped.glyphs.every((glyph) => glyph.commands !== null)).toBe(true)+ expect(ni.commands).toEqual(+ expectDefined(getGlyphOutlineMetricsSync('Shape Test CJK', 'Regular', '你', 13)?.[0])+ .commands+ )+ } finally {+ fallbackFamilies.splice(0, fallbackFamilies.length, ...originalFallbacks)+ }+ })++ test('outlines a variable font at the instance the text is set in', async () => {+ const variable = await Bun.file(testFont('InterVariable-Latin.ttf')).arrayBuffer()+ fontManager.markLoaded('Shape Test Variable', 'Bold', variable)+ const shaped = expectDefined(+ await shape({ text: 'l', fontFamily: 'Shape Test Variable', fontWeight: 700 }),+ 'shaped text'+ )+ const bold = expectDefined(shaped.glyphs[0]?.commands, 'bold outline')+ const regular = expectDefined(+ getGlyphOutlineMetricsSync('Shape Test Variable', 'Bold', 'l', 13)?.[0]+ ).commands++ // The default instance is the regular weight; the bold stem is wider.+ const width = (commands: readonly { x?: number }[]) => {+ const xs = commands.flatMap((command) => (command.x === undefined ? [] : [command.x]))+ return Math.max(...xs) - Math.min(...xs)+ }+ expect(width(bold)).toBeGreaterThan(width(regular) * 1.2)})})diff --git a/packages/core/tests/design-jsx/export-round-trip.test.ts b/packages/core/tests/design-jsx/export-round-trip.test.tsindex 2bd35b8e2..4fd4bb710 100644--- a/packages/core/tests/design-jsx/export-round-trip.test.ts+++ b/packages/core/tests/design-jsx/export-round-trip.test.ts@@ -130,7 +130,8 @@ describe('rich text round trip', () => {const graph = new SceneGraph()const [source] = await renderJSX(graph,- `<Text size={24} color="#111111">+ `<Text size={24} color="#111111" lineHeight={30} paragraphSpacing={6} textDecorationColor="#2222EE">+ <Paragraph list="unordered" indent={2}>Auto <Span lineHeight="auto" textDecoration="underline" textDecorationStyle="dotted" textDecorationColor="currentColor" textDecorationThickness={3} textUnderlineOffset="auto" textDecorationSkipInk={false}>underlined</Span> <Span fills={[]}>hidden</Span></Paragraph><Paragraph spacing={12}>Hello <Span weight={700} color="#EE2222">bold <Span italic>world</Span></Span>!</Paragraph><Paragraph list="ordered">First <Span textDecoration="underline" letterSpacing={1}>item</Span></Paragraph><Paragraph list="ordered" level={2} listSpacing={4} indent={8}>Nested</Paragraph>@@ -140,7 +141,7 @@ describe('rich text round trip', () => {)const node = getNodeOrThrow(graph, expectDefined(source, 'render result').id)expect(node.styleRuns.length).toBeGreaterThan(0)- expect(node.textParagraphs).toHaveLength(4)+ expect(node.textParagraphs).toHaveLength(5)await expectRoundTrip(graph, node.id)})diff --git a/packages/core/tests/helpers/property-cases.ts b/packages/core/tests/helpers/property-cases.tsindex 44bba29fb..7bca46f2b 100644--- a/packages/core/tests/helpers/property-cases.ts+++ b/packages/core/tests/helpers/property-cases.ts@@ -256,6 +256,23 @@ export const PROPERTY_CASES: RoundTripCase[] = [textCase: 'UPPER',textDecoration: 'UNDERLINE'}),+ leafCase('text decoration details', 'TEXT', {+ text: 'Link',+ textDecoration: 'UNDERLINE',+ textDecorationStyle: 'WAVY',+ textDecorationFills: [solidFill(BLUE)],+ textDecorationThickness: 2,+ textUnderlineOffset: 3,+ textDecorationSkipInk: false+ }),+ leafCase('text paragraph spacing', 'TEXT', {+ text: 'One\nTwo',+ paragraphSpacing: 8,+ listSpacing: 2,+ paragraphIndent: 4,+ hangingList: true+ }),+ leafCase('text without fills', 'TEXT', { text: 'Hidden', fills: [] }),leafCase('text that wraps at a fixed width', 'TEXT', {text: 'Wrapped',textAutoResize: 'HEIGHT'diff --git a/packages/design-jsx/src/export/decoration.ts b/packages/design-jsx/src/export/decoration.tsnew file mode 100644index 000000000..93e01bd49--- /dev/null+++ b/packages/design-jsx/src/export/decoration.ts@@ -0,0 +1,38 @@+import type { CharacterStyleOverride, SceneNode } from '@open-pencil/scene-graph'++import { AUTO, CURRENT_COLOR } from '../overrides/text'+import { paintPropValue } from './paint'+import type { JSXProp } from './value'++type DecorationStyle = Pick<+ CharacterStyleOverride,+ | 'textDecorationStyle'+ | 'textDecorationFills'+ | 'textDecorationThickness'+ | 'textUnderlineOffset'+ | 'textDecorationSkipInk'+>++/**+ * The decoration details set in `style`, as `<Text>` and `<Span>` write them. A decoration+ * painted with more than one paint keeps only its first, the one `textDecorationColor` holds.+ */+export function collectDecorationProps(+ style: DecorationStyle,+ node: SceneNode,+ props: JSXProp[]+): void {+ const { textDecorationFills: fills } = style+ if (style.textDecorationStyle !== undefined)+ props.push(['textDecorationStyle', style.textDecorationStyle.toLowerCase()])+ if (fills) {+ const fill = fills.at(0)+ props.push(['textDecorationColor', fill ? paintPropValue(fill, node) : CURRENT_COLOR])+ }+ if (style.textDecorationThickness !== undefined)+ props.push(['textDecorationThickness', style.textDecorationThickness ?? AUTO])+ if (style.textUnderlineOffset !== undefined)+ props.push(['textUnderlineOffset', style.textUnderlineOffset ?? AUTO])+ if (style.textDecorationSkipInk !== undefined)+ props.push(['textDecorationSkipInk', style.textDecorationSkipInk])+}diff --git a/packages/design-jsx/src/export/index.ts b/packages/design-jsx/src/export/index.tsindex fa0ca9cda..8927bf650 100644--- a/packages/design-jsx/src/export/index.ts+++ b/packages/design-jsx/src/export/index.ts@@ -118,12 +118,23 @@ export interface DesignJSXElement {tag: string/** Each attribute as `sceneNodeAttributes` prints it, keyed by name: `w={320}`. */attributes: Record<string, string>- /** Text content of a text layer as JSX writes it, else `null`. */+ /**+ * A text layer's content as JSX writes it between its tags, `<Span>`s and `<Paragraph>`s+ * included, for an element at the start of its line; `null` for no content or another layer.+ */text: string | null/** The layers written as child elements, in order. */childIds: string[]}+/** What a text's element holds between its tags, printed as `sceneNodeToJSX` prints it. */+function textContent(node: SceneNode, tag: string): string | null {+ const { children, inline } = textChildren(node, 0)+ if (children.length === 0) return null+ const printed = jsx.printJSX(jsx.element(tag, [], children, 0, inline))+ return printed.slice(tag.length + 2, printed.lastIndexOf(`</${tag}>`))+}+export function designJSXElement(nodeId: string, graph: SceneGraph): DesignJSXElement | null {const node = graph.getNode(nodeId)const tag = node && NODE_TYPE_TO_TAG[node.type]@@ -136,10 +147,7 @@ export function designJSXElement(nodeId: string, graph: SceneGraph): DesignJSXEl.filter(({ name }) => !isText || name !== 'text').map(({ name, source }) => [name, source]))- if (isText) {- const text = node.text ? jsx.printJSX(jsx.text(node.text)) : null- return { tag, attributes, text, childIds: [] }- }+ if (isText) return { tag, attributes, text: textContent(node, tag), childIds: [] }const childIds = graph.getChildren(node.id).filter((child) => NODE_TYPE_TO_TAG[child.type])diff --git a/packages/design-jsx/src/export/paint.ts b/packages/design-jsx/src/export/paint.tsindex 035e5f2b8..9550e5f4e 100644--- a/packages/design-jsx/src/export/paint.ts+++ b/packages/design-jsx/src/export/paint.ts@@ -92,8 +92,17 @@ function solidShorthand(fills: Fill[]): string | null {return formatColor(fill.color, fill.color.a)}+/** One paint as a colour prop takes it: a colour string when it is plain, its helper otherwise. */+export function paintPropValue(fill: Fill, node: SceneNode): JSXValue {+ return solidShorthand([fill]) ?? fillValue(fill, node)+}+export function collectFillProps(node: SceneNode, props: JSXProp[]): void {- if (node.fills.length === 0) return+ if (node.fills.length === 0) {+ // A text is painted black unless it says it is not painted.+ if (node.type === 'TEXT') props.push(['fills', []])+ return+ }const shorthand = solidShorthand(node.fills)if (shorthand) props.push([node.type === 'TEXT' ? 'color' : 'bg', shorthand])else props.push(['fills', node.fills.map((fill) => fillValue(fill, node))])diff --git a/packages/design-jsx/src/export/props.ts b/packages/design-jsx/src/export/props.tsindex e5ba0b742..6082570b6 100644--- a/packages/design-jsx/src/export/props.ts+++ b/packages/design-jsx/src/export/props.ts@@ -1,4 +1,7 @@+import { isEqual, omitBy, pick } from 'es-toolkit'+import {+ createDefaultNode,layoutSizing,type SceneGraph,type SceneNode,@@ -7,6 +10,7 @@ import {import { DEFAULT_FONT_FAMILY } from '@open-pencil/scene-graph/constants'import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text-direction'+import { collectDecorationProps } from './decoration'import {collectCornerRadii,collectPadding,@@ -216,6 +220,19 @@ function collectTextSizingProps(node: SceneNode, graph: SceneGraph, props: JSXPrif (emitH && node.height > 0) props.push(['h', node.height])}+const DECORATION_FIELDS = [+ 'textDecorationStyle',+ 'textDecorationFills',+ 'textDecorationThickness',+ 'textUnderlineOffset',+ 'textDecorationSkipInk'+] as const++const TEXT_DEFAULTS = pick(+ createDefaultNode(() => '', 'TEXT'),+ DECORATION_FIELDS+)+/** A font weight as `weight` writes it, by name for the weights that have one. */export function fontWeightValue(weight: number): string | number {if (weight === 700) return 'bold'@@ -241,9 +258,18 @@ function collectTextNodeProps(node: SceneNode, props: JSXProp[]): void {if (node.letterSpacing !== 0) props.push(['letterSpacing', node.letterSpacing])if (node.textDecoration !== 'NONE')props.push(['textDecoration', node.textDecoration.toLowerCase()])+ collectDecorationProps(+ omitBy(pick(node, DECORATION_FIELDS), (value, key) => isEqual(value, TEXT_DEFAULTS[key])),+ node,+ props+ )if (node.textCase !== 'ORIGINAL') props.push(['textCase', node.textCase.toLowerCase()])if (node.maxLines != null) props.push(['maxLines', node.maxLines])if (node.textTruncation === 'ENDING' && node.maxLines == null) props.push(['truncate', true])+ if (node.paragraphSpacing !== 0) props.push(['paragraphSpacing', node.paragraphSpacing])+ if (node.listSpacing !== 0) props.push(['listSpacing', node.listSpacing])+ if (node.paragraphIndent !== 0) props.push(['paragraphIndent', node.paragraphIndent])+ if (node.hangingList) props.push(['hangingList', true])}const TEXT_AUTO_RESIZE: Record<SceneNode['textAutoResize'], string> = {diff --git a/packages/design-jsx/src/export/text.ts b/packages/design-jsx/src/export/text.tsindex 2d7d2c632..12ec87919 100644--- a/packages/design-jsx/src/export/text.ts+++ b/packages/design-jsx/src/export/text.ts@@ -6,11 +6,15 @@ import {MAX_LIST_INDENTATION,paragraphStyleAt,textParagraphRanges,+ withParagraphSpacing,type SceneNode,+ type TextParagraphSpacingField,type TextParagraphStyle} from '@open-pencil/scene-graph'+import { AUTO } from '../overrides/text'import { SPAN_STYLE_FIELDS, type SpanStyle } from '../text-content'+import { collectDecorationProps } from './decoration'import { collectFillProps } from './paint'import { fontWeightValue } from './props'import { propAttribute, type JSXProp } from './value'@@ -21,13 +25,6 @@ export interface TextChildren {inline: boolean}-/** Whether a style can be written as `<Span>` props: auto line height and no fills cannot. */-function writable(value: SpanStyle[keyof SpanStyle], key: keyof SpanStyle): boolean {- if (key === 'lineHeight') return value !== null- if (key === 'fills') return Array.isArray(value) && value.length > 0- return value !== undefined-}-/** Each character's style where it differs from the text's own, as a span writes it. */function characterStyles(node: SceneNode): SpanStyle[] {const styles = Array.from({ length: node.text.length }, (): SpanStyle => ({}))@@ -37,7 +34,7 @@ function characterStyles(node: SceneNode): SpanStyle[] {for (let index = run.start; index < end; index++) styles[index] = { ...styles[index], ...style }}return styles.map((style) =>- omitBy(style, (value, key) => !writable(value, key) || isEqual(value, node[key]))+ omitBy(style, (value, key) => value === undefined || isEqual(value, node[key])))}@@ -48,10 +45,11 @@ 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 != null) props.push(['lineHeight', style.lineHeight])+ if (style.lineHeight !== undefined) props.push(['lineHeight', style.lineHeight ?? AUTO])if (style.letterSpacing !== undefined) props.push(['letterSpacing', style.letterSpacing])if (style.textDecoration !== undefined)props.push(['textDecoration', style.textDecoration.toLowerCase()])+ collectDecorationProps(style, node, props)return props}@@ -78,6 +76,22 @@ function inlineContent(return content}+/** `<Paragraph>`'s prop for each spacing a paragraph can set, in the order they are written. */+const PARAGRAPH_SPACING_PROPS: readonly (readonly [TextParagraphSpacingField, string])[] = [+ ['paragraphSpacing', 'spacing'],+ ['listSpacing', 'listSpacing'],+ ['paragraphIndent', 'indent']+]++/** A paragraph's style with only the spacing that differs from the text's own. */+function ownParagraphStyle(node: SceneNode, paragraph: number): TextParagraphStyle {+ let style = paragraphStyleAt(node.textParagraphs, paragraph)+ for (const [field] of PARAGRAPH_SPACING_PROPS) {+ if (style[field] === node[field]) style = withParagraphSpacing(style, field, undefined)+ }+ return style+}+function paragraphProps(style: TextParagraphStyle): JSXProp[] {const props: JSXProp[] = []if (style.listType !== 'NONE') {@@ -85,21 +99,22 @@ function paragraphProps(style: TextParagraphStyle): JSXProp[] {const level = Math.min(style.indentation, MAX_LIST_INDENTATION)if (level > 1) props.push(['level', level])}- if (style.paragraphSpacing !== undefined) props.push(['spacing', style.paragraphSpacing])- if (style.listSpacing !== undefined) props.push(['listSpacing', style.listSpacing])- if (style.paragraphIndent !== undefined) props.push(['indent', style.paragraphIndent])+ for (const [field, name] of PARAGRAPH_SPACING_PROPS) {+ const value = style[field]+ if (value !== undefined) props.push([name, value])+ }return props}/*** A text's content as JSX children: its text alone when it is styled as a whole, with* `<Span>`s for characters styled apart, and as `<Paragraph>`s when a paragraph is a list item- * or has spacing of its own.+ * or has spacing other than the text's.*/export function textChildren(node: SceneNode, depth: number): TextChildren {const styles = characterStyles(node)const ranges = textParagraphRanges(node.text)- const paragraphs = ranges.map((_, index) => paragraphStyleAt(node.textParagraphs, index))+ const paragraphs = ranges.map((_, index) => ownParagraphStyle(node, index))const styledParagraphs = paragraphs.some((style) => style.listType !== 'NONE' || hasParagraphSpacing(style))diff --git a/packages/design-jsx/src/index.ts b/packages/design-jsx/src/index.tsindex 0bc50732f..8016bd2ec 100644--- a/packages/design-jsx/src/index.ts+++ b/packages/design-jsx/src/index.ts@@ -98,6 +98,7 @@ export {DESIGN_JSX_PARAGRAPH_PROPERTY_NAMES,DESIGN_JSX_SPAN_PROPERTY_NAMES,DESIGN_JSX_STYLE_KEYS,+ DESIGN_JSX_TEXT_PARAGRAPH_PROPERTY_NAMES,type DesignJSXStyleKey,designJSXProp,designJSXPropertyNames,diff --git a/packages/design-jsx/src/overrides/fills.ts b/packages/design-jsx/src/overrides/fills.tsnew file mode 100644index 000000000..e16ce116e--- /dev/null+++ b/packages/design-jsx/src/overrides/fills.ts@@ -0,0 +1,33 @@+import type { Fill } from '@open-pencil/scene-graph'+import { colorToFill } from '@open-pencil/scene-graph/color'+import type { Color } from '@open-pencil/scene-graph/primitives'++export function isColor(value: unknown): value is Color {+ return (+ value !== null &&+ typeof value === 'object' &&+ 'r' in value &&+ 'g' in value &&+ 'b' in value &&+ 'a' in value+ )+}++function isFill(value: unknown): value is Fill {+ return (+ value !== null &&+ typeof value === 'object' &&+ 'type' in value &&+ 'color' in value &&+ 'visible' in value+ )+}++/** A paint as props write it: a colour string, a colour, or a paint from a helper. */+export function isFillValue(value: unknown): value is string | Color | Fill {+ return typeof value === 'string' || isColor(value) || isFill(value)+}++export function fillFromValue(value: string | Color | Fill): Fill {+ return isFill(value) ? structuredClone(value) : colorToFill(value)+}diff --git a/packages/design-jsx/src/overrides/text.ts b/packages/design-jsx/src/overrides/text.tsnew file mode 100644index 000000000..78ae519ee--- /dev/null+++ b/packages/design-jsx/src/overrides/text.ts@@ -0,0 +1,66 @@+import * as v from 'valibot'++import type { Fill, SceneNode, TextDecorationStyle } from '@open-pencil/scene-graph'+import type { Color } from '@open-pencil/scene-graph/primitives'++import { parseScriptInput } from '../validation'+import { fillFromValue, isFillValue } from './fills'++/** Lengths that follow the font unless set take `'auto'`, as in CSS. */+export const AUTO = 'auto'+/** The decoration colour that follows the text's, as in CSS. */+export const CURRENT_COLOR = 'currentColor'++const Length = v.pipe(v.number(), v.finite())+const AutoLength = v.union([Length, v.literal(AUTO)])++const DECORATION_STYLES = {+ solid: 'SOLID',+ dotted: 'DOTTED',+ wavy: 'WAVY'+} as const satisfies Record<string, TextDecorationStyle>++const TextProps = v.object({+ textDecorationStyle: v.optional(v.picklist(['solid', 'dotted', 'wavy'])),+ textDecorationColor: v.optional(+ v.custom<string | Color | Fill>(isFillValue, 'Expected a colour or a paint')+ ),+ textDecorationThickness: v.optional(AutoLength),+ textUnderlineOffset: v.optional(AutoLength),+ textDecorationSkipInk: v.optional(v.boolean()),+ paragraphSpacing: v.optional(Length),+ listSpacing: v.optional(Length),+ paragraphIndent: v.optional(Length),+ hangingList: v.optional(v.boolean())+})++function autoLength(value: number | typeof AUTO): number | null {+ return value === AUTO ? null : value+}++/** The decoration details and text-wide paragraph spacing a `<Text>` or `<Span>` sets. */+export function applyTextDetailOverrides(+ props: Record<string, unknown>,+ o: Partial<SceneNode>+): void {+ const parsed = parseScriptInput('Invalid <Text> props', TextProps, props)+ const color = parsed.textDecorationColor+ if (parsed.textDecorationStyle !== undefined)+ o.textDecorationStyle = DECORATION_STYLES[parsed.textDecorationStyle]+ if (color !== undefined) {+ o.textDecorationFills =+ typeof color === 'string' && color.toLowerCase() === CURRENT_COLOR.toLowerCase()+ ? []+ : [fillFromValue(color)]+ }+ if (parsed.textDecorationThickness !== undefined)+ o.textDecorationThickness = autoLength(parsed.textDecorationThickness)+ if (parsed.textUnderlineOffset !== undefined)+ o.textUnderlineOffset = autoLength(parsed.textUnderlineOffset)+ if (parsed.textDecorationSkipInk !== undefined)+ o.textDecorationSkipInk = parsed.textDecorationSkipInk+ if (parsed.paragraphSpacing !== undefined) o.paragraphSpacing = parsed.paragraphSpacing+ if (parsed.listSpacing !== undefined) o.listSpacing = parsed.listSpacing+ if (parsed.paragraphIndent !== undefined) o.paragraphIndent = parsed.paragraphIndent+ if (parsed.hangingList !== undefined) o.hangingList = parsed.hangingList+}diff --git a/packages/design-jsx/src/props-overrides.ts b/packages/design-jsx/src/props-overrides.tsindex ae2ac2fa5..89fc70e70 100644--- a/packages/design-jsx/src/props-overrides.ts+++ b/packages/design-jsx/src/props-overrides.ts@@ -14,8 +14,10 @@ import { parseCSSGridTracks, parseCSSNumber } from '@open-pencil/scene-graph/cssimport type { Color, JSONObject } from '@open-pencil/scene-graph/primitives'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 { isShaderFill } from './paints'import { DESIGN_JSX_STYLE_KEYS, designJSXProp } from './schema'@@ -113,24 +115,6 @@ export function applySizeOverrides(return { w, h }}-function isFill(value: unknown): value is Fill {- return (- value !== null &&- typeof value === 'object' &&- 'type' in value &&- 'color' in value &&- 'visible' in value- )-}--function isFillValue(value: unknown): value is string | Color | Fill {- return typeof value === 'string' || isColor(value) || isFill(value)-}--function fillFromValue(value: string | Color | Fill): Fill {- return isFill(value) ? structuredClone(value) : colorToFill(value)-}-/*** Sets the layer's fills, moving each shader paint's preset into the layer's plugin data,* where a shader paint keeps it.@@ -150,18 +134,12 @@ function setFills(values: (string | Color | Fill)[], o: Partial<SceneNode>): voio.pluginData = withShaderPaints({ pluginData: o.pluginData ?? [] }, fills, shaders)}-function isColor(value: unknown): value is Color {- return (- value !== null &&- typeof value === 'object' &&- 'r' in value &&- 'g' in value &&- 'b' in value &&- 'a' in value- )-}-function applyFillOverride(props: Record<string, unknown>, o: Partial<SceneNode>): void {+ // `fills={[]}` paints nothing, which a text, painted black by default, has to say.+ if (Array.isArray(props.fills) && props.fills.length === 0) {+ o.fills = []+ return+ }if (Array.isArray(props.fills)) {setFills(props.fills.filter(isFillValue), o)return@@ -396,10 +374,12 @@ function applyTextStyleOverrides(props: Record<string, unknown>, o: Partial<Sceno.fills = [colorToFill(props.color)]}- if (props.lineHeight !== undefined) o.lineHeight = props.lineHeight as number+ if (props.lineHeight === AUTO) o.lineHeight = null+ else if (props.lineHeight !== undefined) o.lineHeight = props.lineHeight as numberif (props.letterSpacing !== undefined) o.letterSpacing = props.letterSpacing as numberif (props.textDecoration !== undefined)o.textDecoration = (props.textDecoration as string).toUpperCase() as SceneNode['textDecoration']+ applyTextDetailOverrides(props, o)if (props.textCase !== undefined)o.textCase = (props.textCase as string).toUpperCase() as SceneNode['textCase']if (props.maxLines !== undefined) {diff --git a/packages/design-jsx/src/reference/authoring.md b/packages/design-jsx/src/reference/authoring.mdindex 30e122c9e..60e158350 100644--- a/packages/design-jsx/src/reference/authoring.md+++ b/packages/design-jsx/src/reference/authoring.md@@ -22,8 +22,8 @@ This reference describes scene creation, not React DOM output. Use the `render`- `stroke` describes one stroke, refined by `strokeWidth`, `strokeAlign` (`"inside"`, `"center"`, `"outside"`), `strokeDash`, `strokeCap`, and `strokeJoin`. `strokes` takes several, as objects with `color`, `weight`, `align`, `dash`, `cap`, `join`, and `visible`; `strokeWeights={{ top, right, bottom, left }}` sets per-side widths. `dashPattern` sets the node's own dash pattern, separate from the per-stroke `strokeDash`.- `rounded` and `roundedTL`/`roundedTR`/`roundedBL`/`roundedBR` control corners. `strokeWidth`, `opacity`, `rotate`, and `blendMode` control appearance. `overflow="hidden"` clips content; do not hide accidental text overflow to make a broken layout appear correct.- `effects` accepts structured effects such as `dropShadow`, `innerShadow`, and `layerBlur`. `shadow` takes a CSS `box-shadow` list, such as `shadow="0 4 8 #0002, inset 0 1 0 #fff"`, and `blur` a layer blur radius; both are convenient shorthands. Effect helpers take `radius`, as Figma's effects do; when a JSX string is rendered, an option a paint or effect helper does not support is reported as a warning.-- Text content belongs inside `Text`. Use `size`, `font`, `weight`, `italic`, `lineHeight`, `letterSpacing`, `textAlign`, `textAlignVertical`, `textDecoration`, and `textCase`. Verify fonts actually load before judging dimensions; do not assume every font is available.-- `Span` styles some characters of a `Text` with `Text`'s own prop names: `size`, `font`, `weight`, `italic`, `color`, `lineHeight`, `letterSpacing`, and `textDecoration`. Spans nest; the inner one wins. `Paragraph` writes one paragraph: `list="ordered"` or `list="unordered"` makes it a list item nested at `level` 1–5, and `spacing`, `listSpacing`, and `indent` give it spacing of its own. A `Text` holds only `Paragraph`s or none; without them, a line break in its text still starts a paragraph.+- Text content belongs inside `Text`. Use `size`, `font`, `weight`, `italic`, `lineHeight`, `letterSpacing`, `textAlign`, `textAlignVertical`, `textDecoration`, and `textCase`. Decorations take CSS's names and values: `textDecorationStyle` (`solid`, `dotted`, `wavy`), `textDecorationColor` (`currentColor` follows the text), `textDecorationThickness` and `textUnderlineOffset` (pixels or `auto`), and `textDecorationSkipInk`. `lineHeight="auto"` follows the font, and `fills={[]}` paints no text. Verify fonts actually load before judging dimensions; do not assume every font is available.+- `Span` styles some characters of a `Text` with `Text`'s own prop names: `size`, `font`, `weight`, `italic`, `color`, `fills`, `lineHeight`, `letterSpacing`, `textDecoration`, and the decoration details. Spans nest; the inner one wins. `Paragraph` writes one paragraph: `list="ordered"` or `list="unordered"` makes it a list item nested at `level` 1–5, and `spacing`, `listSpacing`, and `indent` override the `Text`'s `paragraphSpacing`, `listSpacing`, and `paragraphIndent` for it; `hangingList` on the `Text` hangs list markers outside the text box. A `Text` holds only `Paragraph`s or none; without them, a line break in its text still starts a paragraph.- `Icon` uses an Iconify name, size, and color. Prefer icons to emoji when reliable vector output is needed. Image fills belong on appropriate leaf shapes, not containers whose children must remain visible.- Design JSX props are the portable authoring interface. Some CSS-style aliases are supported, but this is not a browser CSS engine; do not assume arbitrary HTML, classes, or styles work.diff --git a/packages/design-jsx/src/reference/examples.ts b/packages/design-jsx/src/reference/examples.tsindex 714457be5..e00b8ab91 100644--- a/packages/design-jsx/src/reference/examples.ts+++ b/packages/design-jsx/src/reference/examples.ts@@ -23,8 +23,8 @@ export const AUTHORING_EXAMPLES: readonly AuthoringExample[] = [{title: 'Rich text with spans and lists',jsx: dedent`<Frame name="Release notes" w={280} h="hug" flex="col" gap={8} p={16} bg="#FFFFFF">- <Text name="Notes" w="fill" size={12} color="#252A31">- <Paragraph spacing={8}>Version 2 is <Span weight="bold" color="#3B6CF6">out now</Span>.</Paragraph>+ <Text name="Notes" w="fill" size={12} color="#252A31" paragraphSpacing={4}>+ <Paragraph spacing={8}>Version 2 is <Span weight="bold" color="#3B6CF6" textDecoration="underline" textDecorationStyle="wavy" textUnderlineOffset={2}>out now</Span>.</Paragraph><Paragraph list="unordered">Faster export</Paragraph><Paragraph list="unordered" level={2}>PDF and SVG</Paragraph><Paragraph list="ordered">Fewer clicks</Paragraph>diff --git a/packages/design-jsx/src/render.ts b/packages/design-jsx/src/render.tsindex af4b4bff9..2f7f4b6fe 100644--- a/packages/design-jsx/src/render.ts+++ b/packages/design-jsx/src/render.ts@@ -10,7 +10,8 @@ import { renderRoots, renderTree, componentPropNames, type RenderResult } from 'import {DESIGN_JSX_PARAGRAPH_PROPERTY_NAMES,DESIGN_JSX_SPAN_PROPERTY_NAMES,- DESIGN_JSX_SUPPORTED_PROPERTY_NAMES+ DESIGN_JSX_SUPPORTED_PROPERTY_NAMES,+ DESIGN_JSX_TEXT_PARAGRAPH_PROPERTY_NAMES} from './schema'import type { DesignJSXServices } from './services'import { PARAGRAPH, SPAN, TEXT_CONTENT_NAMES } from './text-content'@@ -37,9 +38,12 @@ function unsupportedPropWarnings(graph: SceneGraph, tree: TreeNode): string[] {return warnings}-// Paragraph props describe a paragraph of a text, never a layer.+// Paragraph props describe a paragraph of a text, never a layer, unless a text sets them too.const LAYER_PROPS = new Set<string>(- difference(DESIGN_JSX_SUPPORTED_PROPERTY_NAMES, DESIGN_JSX_PARAGRAPH_PROPERTY_NAMES)+ difference(+ DESIGN_JSX_SUPPORTED_PROPERTY_NAMES,+ difference(DESIGN_JSX_PARAGRAPH_PROPERTY_NAMES, DESIGN_JSX_TEXT_PARAGRAPH_PROPERTY_NAMES)+ ))const SVG_ROOT_PROPS = new Set([...LAYER_PROPS, 'viewBox', 'body'])const PARAGRAPH_PROPS = new Set<string>(['key', ...DESIGN_JSX_PARAGRAPH_PROPERTY_NAMES])diff --git a/packages/design-jsx/src/schema.ts b/packages/design-jsx/src/schema.tsindex 5aee1666a..82644f083 100644--- a/packages/design-jsx/src/schema.ts+++ b/packages/design-jsx/src/schema.ts@@ -86,7 +86,20 @@ export const DESIGN_JSX_SPAN_PROPERTY_NAMES = ['fills','lineHeight','letterSpacing',- 'textDecoration'+ 'textDecoration',+ 'textDecorationStyle',+ 'textDecorationColor',+ 'textDecorationThickness',+ 'textUnderlineOffset',+ 'textDecorationSkipInk'+] as const++/** Props `<Text>` sets every paragraph's spacing with; a `<Paragraph>` sets its own. */+export const DESIGN_JSX_TEXT_PARAGRAPH_PROPERTY_NAMES = [+ 'paragraphSpacing',+ 'listSpacing',+ 'paragraphIndent',+ 'hangingList'] as constexport const DESIGN_JSX_SUPPORTED_PROPERTY_NAMES = [@@ -185,7 +198,15 @@ export const DESIGN_JSX_SUPPORTED_PROPERTY_NAMES = ['lineHeight','letterSpacing','textDecoration',+ 'textDecorationStyle',+ 'textDecorationColor',+ 'textDecorationThickness',+ 'textUnderlineOffset',+ 'textDecorationSkipInk','textCase',+ 'paragraphSpacing',+ 'paragraphIndent',+ 'hangingList','list','level','spacing',diff --git a/packages/design-jsx/src/text-content.ts b/packages/design-jsx/src/text-content.tsindex 43fc3a2bd..fb634b13d 100644--- a/packages/design-jsx/src/text-content.ts+++ b/packages/design-jsx/src/text-content.ts@@ -36,7 +36,12 @@ export const SPAN_STYLE_FIELDS = ['fills','letterSpacing','lineHeight',- 'textDecoration'+ 'textDecoration',+ 'textDecorationStyle',+ 'textDecorationFills',+ 'textDecorationThickness',+ 'textUnderlineOffset',+ 'textDecorationSkipInk'] as const satisfies readonly (keyof CharacterStyleOverride & keyof SceneNode)[]export type SpanStyle = Pick<CharacterStyleOverride, (typeof SPAN_STYLE_FIELDS)[number]>diff --git a/packages/design-jsx/src/tree.ts b/packages/design-jsx/src/tree.tsindex b481f92ae..ee5ad206e 100644--- a/packages/design-jsx/src/tree.ts+++ b/packages/design-jsx/src/tree.ts@@ -158,7 +158,7 @@ export type StyleProps = {size?: number | DesignVariablefontSize?: number | DesignVariable- lineHeight?: number | DesignVariable+ lineHeight?: number | 'auto' | DesignVariableletterSpacing?: number | DesignVariablefont?: stringfontFamily?: string@@ -206,6 +206,11 @@ export type SpanProps = Pick<style?: Record<string, unknown>italic?: booleantextDecoration?: 'none' | 'underline' | 'strikethrough'+ textDecorationStyle?: 'solid' | 'dotted' | 'wavy'+ textDecorationColor?: string | Color | Fill+ textDecorationThickness?: number | 'auto'+ textUnderlineOffset?: number | 'auto'+ textDecorationSkipInk?: booleanchildren?: unknown}diff --git a/packages/design-jsx/tests/export/text.test.ts b/packages/design-jsx/tests/export/text.test.tsindex a224134ed..783df60e4 100644--- a/packages/design-jsx/tests/export/text.test.ts+++ b/packages/design-jsx/tests/export/text.test.ts@@ -1,6 +1,6 @@import { describe, expect, test } from 'bun:test'-import { sceneNodeToJSX } from '#design-jsx/index'+import { designJSXElement, sceneNodeToJSX } from '#design-jsx/index'import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'import { colorToFill } from '@open-pencil/scene-graph/color'@@ -10,7 +10,6 @@ function exportText(fields: Partial<SceneNode>): string {const node = graph.createNode('TEXT', graph.getPages()[0].id, {name: 'Note',textAutoResize: 'WIDTH_AND_HEIGHT',- fills: [],...fields})return sceneNodeToJSX(node.id, graph)@@ -26,7 +25,7 @@ describe('rich text export', () => {]})expect(code).toBe(- '<Text name="Note" weight="bold">Hello <Span color="#EE2222">world</Span>!</Text>'+ '<Text name="Note" color="#000000" weight="bold">Hello <Span color="#EE2222">world</Span>!</Text>')})@@ -51,7 +50,7 @@ describe('rich text export', () => {]})expect(code).toBe(- '<Text name="Note"><Span size={20} font="Roboto" weight="medium" italic lineHeight={30} letterSpacing={1} textDecoration="strikethrough">a</Span>b</Text>'+ '<Text name="Note" color="#000000"><Span size={20} font="Roboto" weight="medium" italic lineHeight={30} letterSpacing={1} textDecoration="strikethrough">a</Span>b</Text>')})@@ -65,19 +64,78 @@ describe('rich text export', () => {],styleRuns: [{ start: 6, length: 5, style: { fontWeight: 700 } }]})- expect(code).toBe(`<Text name="Note">+ expect(code).toBe(`<Text name="Note" color="#000000"><Paragraph spacing={12}>Intro</Paragraph><Paragraph list="ordered"><Span weight="bold">First</Span></Paragraph><Paragraph list="ordered" level={2} listSpacing={4} indent={8}>Nested</Paragraph></Text>`)})+ test('writes decoration details on the text and on spans', () => {+ const code = exportText({+ text: 'ab',+ textDecoration: 'UNDERLINE',+ textDecorationStyle: 'DOTTED',+ textDecorationFills: [colorToFill('#EE2222')],+ textDecorationThickness: 2,+ textDecorationSkipInk: false,+ styleRuns: [+ {+ start: 1,+ length: 1,+ style: {+ textDecorationStyle: 'WAVY',+ textDecorationFills: [],+ textDecorationThickness: null,+ textUnderlineOffset: 3,+ textDecorationSkipInk: true+ }+ }+ ]+ })+ expect(code).toBe(+ '<Text name="Note" color="#000000" textDecoration="underline" textDecorationStyle="dotted" textDecorationColor="#EE2222" textDecorationThickness={2} textDecorationSkipInk={false}>a<Span textDecorationStyle="wavy" textDecorationColor="currentColor" textDecorationThickness="auto" textUnderlineOffset={3} textDecorationSkipInk>b</Span></Text>'+ )+ })++ test('writes auto line height and no fills in a span', () => {+ const code = exportText({+ text: 'ab',+ lineHeight: 20,+ styleRuns: [{ start: 1, length: 1, style: { lineHeight: null, fills: [] } }]+ })+ expect(code).toBe(+ '<Text name="Note" color="#000000" lineHeight={20}>a<Span fills={[]} lineHeight="auto">b</Span></Text>'+ )+ })++ test('writes the text-wide spacing, and a paragraph only where it differs', () => {+ const code = exportText({+ text: 'a\nb',+ paragraphSpacing: 8,+ listSpacing: 2,+ paragraphIndent: 4,+ hangingList: true,+ textParagraphs: [+ { listType: 'NONE', indentation: 0, paragraphSpacing: 8, paragraphIndent: 6 },+ { listType: 'NONE', indentation: 0, paragraphSpacing: 8 }+ ]+ })+ expect(code)+ .toBe(`<Text name="Note" color="#000000" paragraphSpacing={8} listSpacing={2} paragraphIndent={4} hangingList>+ <Paragraph indent={6}>a</Paragraph>+ <Paragraph>b</Paragraph>+</Text>`)+ })+test('keeps spaces and syntax characters next to spans', () => {const code = exportText({text: ' a {b} ',styleRuns: [{ start: 1, length: 1, style: { fontWeight: 700 } }]})- expect(code).toBe('<Text name="Note"> <Span weight="bold">a</Span>{" {b} "}</Text>')+ expect(code).toBe(+ '<Text name="Note" color="#000000"> <Span weight="bold">a</Span>{" {b} "}</Text>'+ )})test('writes plain text as before', () => {@@ -86,6 +144,45 @@ describe('rich text export', () => {textParagraphs: [{ listType: 'NONE', indentation: 0 }],styleRuns: [{ start: 0, length: 3, style: { fontWeight: 400 } }]})- expect(code).toBe('<Text name="Note">{"One\\nTwo"}</Text>')+ expect(code).toBe('<Text name="Note" color="#000000">{"One\\nTwo"}</Text>')+ })+})++describe('designJSXElement', () => {+ function describeText(fields: Partial<SceneNode>) {+ const graph = new SceneGraph()+ const node = graph.createNode('TEXT', graph.getPages()[0].id, { name: 'Note', ...fields })+ return { element: designJSXElement(node.id, graph), code: sceneNodeToJSX(node.id, graph) }+ }++ /** What the exported element holds between its opening and closing tags. */+ function between(code: string): string {+ return code.slice(code.indexOf('>') + 1, code.lastIndexOf('</Text>'))+ }++ test('describes plain text as before', () => {+ expect(describeText({ text: 'One\nTwo' }).element?.text).toBe('{"One\\nTwo"}')+ expect(describeText({ text: '' }).element?.text).toBeNull()+ })++ test('describes spans and paragraphs as the export writes them', () => {+ const spans = describeText({+ text: 'Hello world',+ styleRuns: [{ start: 6, length: 5, style: { fontWeight: 700 } }]+ })+ expect(spans.element?.text).toBe('Hello <Span weight="bold">world</Span>')+ expect(spans.element?.text).toBe(between(spans.code))++ const paragraphs = describeText({+ text: 'a\nb',+ textParagraphs: [+ { listType: 'UNORDERED', indentation: 1 },+ { listType: 'UNORDERED', indentation: 1 }+ ]+ })+ expect(paragraphs.element?.text).toBe(+ '\n <Paragraph list="unordered">a</Paragraph>\n <Paragraph list="unordered">b</Paragraph>\n'+ )+ expect(paragraphs.element?.text).toBe(between(paragraphs.code))})})diff --git a/packages/design-jsx/tests/text-content.test.ts b/packages/design-jsx/tests/text-content.test.tsindex 4f15664d2..758cea5a7 100644--- a/packages/design-jsx/tests/text-content.test.ts+++ b/packages/design-jsx/tests/text-content.test.ts@@ -52,6 +52,36 @@ describe('Span', () => {expect(warnings).toEqual([])})+ 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>'+ )+ expect(node.textDecorationFills).toEqual([colorToFill('#EE2222')])+ expect(node.textDecorationThickness).toBe(2)+ expect(node.styleRuns).toEqual([+ {+ start: 1,+ length: 1,+ style: {+ lineHeight: null,+ fills: [],+ textDecorationStyle: 'WAVY',+ textDecorationFills: [],+ textDecorationThickness: null,+ textUnderlineOffset: 4,+ textDecorationSkipInk: false+ }+ }+ ])+ expect(warnings).toEqual([])+ })++ test('rejects decoration details it cannot draw', async () => {+ await expect(renderText('<Text textDecorationStyle="dashed">a</Text>')).rejects.toThrow(+ 'Invalid <Text> props'+ )+ })+test('nests, the inner span winning', async () => {const { node } = await renderText('<Text><Span weight={700}>a<Span weight={300} italic>b</Span></Span>c</Text>'@@ -158,6 +188,23 @@ describe('Paragraph', () => {const { warnings } = await renderText('<Text spacing={4}>a</Text>')expect(warnings).toEqual(['Unsupported prop "spacing" on <text> is ignored.'])})++ test('follows the spacing its text sets for every paragraph', async () => {+ const { node, warnings } = await renderText(+ '<Text paragraphSpacing={8} listSpacing={2} paragraphIndent={4} hangingList><Paragraph spacing={12}>a</Paragraph><Paragraph list="ordered">b</Paragraph></Text>'+ )+ expect(node).toMatchObject({+ paragraphSpacing: 8,+ listSpacing: 2,+ paragraphIndent: 4,+ hangingList: true+ })+ expect(node.textParagraphs).toEqual([+ { listType: 'NONE', indentation: 0, paragraphSpacing: 12 },+ { listType: 'ORDERED', indentation: 1 }+ ])+ expect(warnings).toEqual([])+ })})test('a text without spans or paragraphs keeps its text as before', async () => {diff --git a/packages/docs/reference/design-authoring.md b/packages/docs/reference/design-authoring.mdindex fbc916d4b..7b52ea215 100644--- a/packages/docs/reference/design-authoring.md+++ b/packages/docs/reference/design-authoring.md@@ -24,8 +24,8 @@ This reference describes scene creation, not React DOM output. Use the `render`- `stroke` describes one stroke, refined by `strokeWidth`, `strokeAlign` (`"inside"`, `"center"`, `"outside"`), `strokeDash`, `strokeCap`, and `strokeJoin`. `strokes` takes several, as objects with `color`, `weight`, `align`, `dash`, `cap`, `join`, and `visible`; `strokeWeights={{ top, right, bottom, left }}` sets per-side widths. `dashPattern` sets the node's own dash pattern, separate from the per-stroke `strokeDash`.- `rounded` and `roundedTL`/`roundedTR`/`roundedBL`/`roundedBR` control corners. `strokeWidth`, `opacity`, `rotate`, and `blendMode` control appearance. `overflow="hidden"` clips content; do not hide accidental text overflow to make a broken layout appear correct.- `effects` accepts structured effects such as `dropShadow`, `innerShadow`, and `layerBlur`. `shadow` takes a CSS `box-shadow` list, such as `shadow="0 4 8 #0002, inset 0 1 0 #fff"`, and `blur` a layer blur radius; both are convenient shorthands. Effect helpers take `radius`, as Figma's effects do; when a JSX string is rendered, an option a paint or effect helper does not support is reported as a warning.-- Text content belongs inside `Text`. Use `size`, `font`, `weight`, `italic`, `lineHeight`, `letterSpacing`, `textAlign`, `textAlignVertical`, `textDecoration`, and `textCase`. Verify fonts actually load before judging dimensions; do not assume every font is available.-- `Span` styles some characters of a `Text` with `Text`'s own prop names: `size`, `font`, `weight`, `italic`, `color`, `lineHeight`, `letterSpacing`, and `textDecoration`. Spans nest; the inner one wins. `Paragraph` writes one paragraph: `list="ordered"` or `list="unordered"` makes it a list item nested at `level` 1–5, and `spacing`, `listSpacing`, and `indent` give it spacing of its own. A `Text` holds only `Paragraph`s or none; without them, a line break in its text still starts a paragraph.+- Text content belongs inside `Text`. Use `size`, `font`, `weight`, `italic`, `lineHeight`, `letterSpacing`, `textAlign`, `textAlignVertical`, `textDecoration`, and `textCase`. Decorations take CSS's names and values: `textDecorationStyle` (`solid`, `dotted`, `wavy`), `textDecorationColor` (`currentColor` follows the text), `textDecorationThickness` and `textUnderlineOffset` (pixels or `auto`), and `textDecorationSkipInk`. `lineHeight="auto"` follows the font, and `fills={[]}` paints no text. Verify fonts actually load before judging dimensions; do not assume every font is available.+- `Span` styles some characters of a `Text` with `Text`'s own prop names: `size`, `font`, `weight`, `italic`, `color`, `fills`, `lineHeight`, `letterSpacing`, `textDecoration`, and the decoration details. Spans nest; the inner one wins. `Paragraph` writes one paragraph: `list="ordered"` or `list="unordered"` makes it a list item nested at `level` 1–5, and `spacing`, `listSpacing`, and `indent` override the `Text`'s `paragraphSpacing`, `listSpacing`, and `paragraphIndent` for it; `hangingList` on the `Text` hangs list markers outside the text box. A `Text` holds only `Paragraph`s or none; without them, a line break in its text still starts a paragraph.- `Icon` uses an Iconify name, size, and color. Prefer icons to emoji when reliable vector output is needed. Image fills belong on appropriate leaf shapes, not containers whose children must remain visible.- Design JSX props are the portable authoring interface. Some CSS-style aliases are supported, but this is not a browser CSS engine; do not assume arbitrary HTML, classes, or styles work.@@ -89,8 +89,8 @@ The examples below are executed by the authoring-reference tests. Create the nam```jsx<Frame name="Release notes" w={280} h="hug" flex="col" gap={8} p={16} bg="#FFFFFF">-<Text name="Notes" w="fill" size={12} color="#252A31">- <Paragraph spacing={8}>Version 2 is <Span weight="bold" color="#3B6CF6">out now</Span>.</Paragraph>+<Text name="Notes" w="fill" size={12} color="#252A31" paragraphSpacing={4}>+ <Paragraph spacing={8}>Version 2 is <Span weight="bold" color="#3B6CF6" textDecoration="underline" textDecorationStyle="wavy" textUnderlineOffset={2}>out now</Span>.</Paragraph><Paragraph list="unordered">Faster export</Paragraph><Paragraph list="unordered" level={2}>PDF and SVG</Paragraph><Paragraph list="ordered">Fewer clicks</Paragraph>@@ -106,4 +106,4 @@ Generated from the renderer metadata. This inventory lists accepted names, not a**Helpers:** `solid`, `gradient`, `linearGradient`, `radialGradient`, `angularGradient`, `diamondGradient`, `shader`, `dropShadow`, `innerShadow`, `layerBlur`, `backgroundBlur`, `foregroundBlur`, `designVar`, `defineVars`.-**Properties:** `name`, `key`, `flex`, `flow`, `dir`, `gap`, `wrap`, `rowGap`, `columnGap`, `justify`, `justifyContent`, `items`, `align`, `alignItems`, `grow`, `w`, `h`, `width`, `height`, `minW`, `maxW`, `minH`, `maxH`, `x`, `y`, `top`, `left`, `position`, `constraints`, `p`, `padding`, `px`, `py`, `pt`, `pr`, `pb`, `pl`, `bg`, `fill`, `fills`, `background`, `backgroundColor`, `stroke`, `border`, `borderColor`, `strokeWidth`, `borderWidth`, `strokeAlign`, `strokeDash`, `strokeCap`, `strokeJoin`, `dashPattern`, `strokes`, `strokeWeights`, `rounded`, `borderRadius`, `roundedTL`, `roundedTR`, `roundedBL`, `roundedBR`, `cornerRadius`, `cornerSmoothing`, `opacity`, `blendMode`, `rotate`, `rotation`, `overflow`, `mask`, `visible`, `locked`, `shadow`, `blur`, `effects`, `size`, `fontSize`, `font`, `fontFamily`, `weight`, `fontWeight`, `italic`, `color`, `text`, `characters`, `content`, `value`, `title`, `textAlign`, `textAlignHorizontal`, `textHorizontalAlignment`, `textAlignVertical`, `textVerticalAlignment`, `textAutoResize`, `lineHeight`, `letterSpacing`, `textDecoration`, `textCase`, `list`, `level`, `spacing`, `listSpacing`, `indent`, `maxLines`, `truncate`, `grid`, `columns`, `rows`, `colStart`, `rowStart`, `col`, `row`, `colSpan`, `rowSpan`, `points`, `pointCount`, `innerRadius`, `label`, `style`, `bind`, `component`, `componentId`, `properties`, `propertyRefs`, `of`, `modelValue`, `open`, `disabled`, `filled`, `states`, `min`, `max`, `step`, `defaultValue`.\ No newline at end of file+**Properties:** `name`, `key`, `flex`, `flow`, `dir`, `gap`, `wrap`, `rowGap`, `columnGap`, `justify`, `justifyContent`, `items`, `align`, `alignItems`, `grow`, `w`, `h`, `width`, `height`, `minW`, `maxW`, `minH`, `maxH`, `x`, `y`, `top`, `left`, `position`, `constraints`, `p`, `padding`, `px`, `py`, `pt`, `pr`, `pb`, `pl`, `bg`, `fill`, `fills`, `background`, `backgroundColor`, `stroke`, `border`, `borderColor`, `strokeWidth`, `borderWidth`, `strokeAlign`, `strokeDash`, `strokeCap`, `strokeJoin`, `dashPattern`, `strokes`, `strokeWeights`, `rounded`, `borderRadius`, `roundedTL`, `roundedTR`, `roundedBL`, `roundedBR`, `cornerRadius`, `cornerSmoothing`, `opacity`, `blendMode`, `rotate`, `rotation`, `overflow`, `mask`, `visible`, `locked`, `shadow`, `blur`, `effects`, `size`, `fontSize`, `font`, `fontFamily`, `weight`, `fontWeight`, `italic`, `color`, `text`, `characters`, `content`, `value`, `title`, `textAlign`, `textAlignHorizontal`, `textHorizontalAlignment`, `textAlignVertical`, `textVerticalAlignment`, `textAutoResize`, `lineHeight`, `letterSpacing`, `textDecoration`, `textDecorationStyle`, `textDecorationColor`, `textDecorationThickness`, `textUnderlineOffset`, `textDecorationSkipInk`, `textCase`, `paragraphSpacing`, `paragraphIndent`, `hangingList`, `list`, `level`, `spacing`, `listSpacing`, `indent`, `maxLines`, `truncate`, `grid`, `columns`, `rows`, `colStart`, `rowStart`, `col`, `row`, `colSpan`, `rowSpan`, `points`, `pointCount`, `innerRadius`, `label`, `style`, `bind`, `component`, `componentId`, `properties`, `propertyRefs`, `of`, `modelValue`, `open`, `disabled`, `filled`, `states`, `min`, `max`, `step`, `defaultValue`.\ No newline at end of filediff --git a/packages/fig/src/node-change/convert.ts b/packages/fig/src/node-change/convert.tsindex 05109e434..5a12b8d56 100644--- a/packages/fig/src/node-change/convert.ts+++ b/packages/fig/src/node-change/convert.ts@@ -30,7 +30,12 @@ import {} from './plugin-data'import { importStyleRuns } from './style/runs'import { importParagraphStyles } from './text/lines'-import { convertLetterSpacing, convertLineHeight, mapTextDecoration } from './text/values'+import {+ convertLetterSpacing,+ convertLineHeight,+ isFigmaAutoLineHeight,+ mapTextDecoration+} from './text/values'import {alignGeometryWindingRules,resolveGeometryPaths,@@ -311,14 +316,18 @@ function convertPolygonProps(}/**- * Figma always writes a line height and lays text out at the one its styles resolve to, which- * the saved lines record. OpenPencil writes none for auto, whose lines differ in height when- * the text mixes font sizes, so the first of them would fix every line at its height.+ * A text's line height. Figma writes auto as 100 percent, and OpenPencil once wrote none for+ * it; a text in auto lines up each line at its own font's height. A height in pixels is the one+ * the saved lines were laid out at, which a style the text uses may set apart from its own.*/function importedTextLineHeight(nc: NodeChange): number | null {- if (!nc.lineHeight) return null+ if (!nc.lineHeight || isFigmaAutoLineHeight(nc.lineHeight)) return nullconst derivedLineHeight = nc.derivedTextData?.baselines?.[0]?.lineHeight- if (derivedLineHeight !== undefined && Number.isFinite(derivedLineHeight))+ if (+ nc.lineHeight.units === 'PIXELS' &&+ derivedLineHeight !== undefined &&+ Number.isFinite(derivedLineHeight)+ )return derivedLineHeightreturn convertLineHeight(nc.lineHeight, nc.fontSize)}diff --git a/packages/fig/src/node-change/derived-text/glyphs.ts b/packages/fig/src/node-change/derived-text/glyphs.tsindex 1a7562029..b0e5a1e05 100644--- a/packages/fig/src/node-change/derived-text/glyphs.ts+++ b/packages/fig/src/node-change/derived-text/glyphs.ts@@ -33,7 +33,11 @@ export function convertFigmaDerivedTextGlyphs(): DerivedTextGlyph[] {if (!derivedTextData || isUnshapedOpenPencilText(derivedTextData, characters)) return []const glyphs: DerivedTextGlyph[] = []- for (const glyph of derivedTextData.glyphs ?? []) {+ // Truncated text is laid out whole, with an ellipsis glyph where it is cut; Figma hides the+ // glyphs from `truncationStartIndex` on, so they are not drawn here either.+ const truncation = derivedTextData.truncationStartIndex ?? -1+ const saved = derivedTextData.glyphs ?? []+ for (const glyph of truncation >= 0 ? saved.slice(0, truncation) : saved) {const commandsBlob = glyph.commandsBlob === undefined ? undefined : blobs[glyph.commandsBlob]// Layout written without outlines, or with some missing, would draw text with gaps.if (!commandsBlob) return []diff --git a/packages/fig/src/node-change/serialize.ts b/packages/fig/src/node-change/serialize.tsindex 759b68b90..85a773506 100644--- a/packages/fig/src/node-change/serialize.ts+++ b/packages/fig/src/node-change/serialize.ts@@ -47,6 +47,7 @@ import {type KiwiNodeChange} from './export/node'import { exportTextData, fontVariationToKiwi } from './text/data-export'+import { FIGMA_AUTO_LINE_HEIGHT } from './text/values'import { toKiwiWindingRule } from './vector/geometry'function serializeCornerRadii(node: SceneNode, nc: KiwiNodeChange): void {@@ -141,7 +142,10 @@ function serializeTextProps(})}if (node.leadingTrim !== 'NONE') nc.leadingTrim = node.leadingTrim- if (node.lineHeight != null) nc.lineHeight = { value: node.lineHeight, units: 'PIXELS' }+ nc.lineHeight =+ node.lineHeight === null+ ? { ...FIGMA_AUTO_LINE_HEIGHT }+ : { value: node.lineHeight, units: 'PIXELS' }nc.letterSpacing = { value: node.letterSpacing, units: 'PIXELS' }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.tsindex 0e97c29e5..f93bff557 100644--- a/packages/fig/src/node-change/style/runs.ts+++ b/packages/fig/src/node-change/style/runs.ts@@ -47,8 +47,8 @@ function convertStyleOverride()}if (override.lineHeight) {- const lh = convertLineHeight(override.lineHeight, override.fontSize ?? fallbackFontSize)- if (lh != null) style.lineHeight = lh+ // 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)}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.tsindex 554868027..5fd143b24 100644--- a/packages/fig/src/node-change/text/data-export.ts+++ b/packages/fig/src/node-change/text/data-export.ts@@ -6,6 +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'export function fontVariationToKiwi(variation: SceneNode['fontVariations'][number]) {const axisTag = stringToFigmaAxisTag(variation.axis)@@ -58,8 +59,11 @@ function textStyleOverrideToKiwi(if (style.letterSpacing !== undefined) {override.letterSpacing = { value: style.letterSpacing, units: 'PIXELS' }}- if (style.lineHeight !== undefined && style.lineHeight !== null) {- override.lineHeight = { value: style.lineHeight, units: 'PIXELS' }+ if (style.lineHeight !== undefined) {+ override.lineHeight =+ style.lineHeight === null+ ? { ...FIGMA_AUTO_LINE_HEIGHT }+ : { value: style.lineHeight, units: 'PIXELS' }}applyTextDecorationOverrideFields(override, style, fillToKiwiPaint)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.tsindex 3a7fdfda7..b20a8b4dc 100644--- a/packages/fig/src/node-change/text/values.ts+++ b/packages/fig/src/node-change/text/values.ts@@ -11,11 +11,18 @@ export function mapTextDecoration(d?: string): TextDecoration {}}+/** How Figma writes an auto line height; a percent the user set is a `RAW` multiplier. */+export const FIGMA_AUTO_LINE_HEIGHT = { value: 100, units: 'PERCENT' } as const++export function isFigmaAutoLineHeight(lh?: { value: number; units: string }): boolean {+ 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 {- if (!lh) return null+ if (!lh || isFigmaAutoLineHeight(lh)) return nullif (lh.units === 'PIXELS') return lh.valueif (lh.units === 'PERCENT') return (lh.value / 100) * (fontSize ?? 14)if (lh.units === 'RAW') return lh.value * (fontSize ?? 14)diff --git a/packages/fig/tests/node-change/derived-text.test.ts b/packages/fig/tests/node-change/derived-text.test.tsindex 7de6e055b..d8865dc27 100644--- a/packages/fig/tests/node-change/derived-text.test.ts+++ b/packages/fig/tests/node-change/derived-text.test.ts@@ -247,6 +247,20 @@ function earlierOpenPencilData(characters: string, lineHeight: number): DerivedTdescribe('derived text reader', () => {const blobs = [new Uint8Array([0])]+ test('leaves out the glyphs Figma hides past the ellipsis of truncated text', () => {+ // Figma lays truncated text out whole and puts an ellipsis, with no character, where it is+ // cut; the glyphs after it, from `truncationStartIndex`, are not drawn.+ const characters = 'Long label'+ const data = earlierOpenPencilData(characters, 16)+ data.logicalIndexToCharacterOffsetMap = data.logicalIndexToCharacterOffsetMap?.slice(0, -1)+ const glyphs = data.glyphs ?? []+ glyphs.splice(4, 0, { ...glyphs[4], firstCharacter: undefined })+ data.truncationStartIndex = 5++ const read = convertFigmaDerivedTextGlyphs(data, blobs, characters)+ expect(read.map((glyph) => glyph.firstCharacter)).toEqual([0, 1, 2, 3, undefined])+ })+test("keeps a glyph's own advance through reading and saving", () => {const characters = 'Table item'const data = earlierOpenPencilData(characters, 16)diff --git a/skills/open-pencil/references/design-authoring.md b/skills/open-pencil/references/design-authoring.mdindex fbc916d4b..7b52ea215 100644--- a/skills/open-pencil/references/design-authoring.md+++ b/skills/open-pencil/references/design-authoring.md@@ -24,8 +24,8 @@ This reference describes scene creation, not React DOM output. Use the `render`- `stroke` describes one stroke, refined by `strokeWidth`, `strokeAlign` (`"inside"`, `"center"`, `"outside"`), `strokeDash`, `strokeCap`, and `strokeJoin`. `strokes` takes several, as objects with `color`, `weight`, `align`, `dash`, `cap`, `join`, and `visible`; `strokeWeights={{ top, right, bottom, left }}` sets per-side widths. `dashPattern` sets the node's own dash pattern, separate from the per-stroke `strokeDash`.- `rounded` and `roundedTL`/`roundedTR`/`roundedBL`/`roundedBR` control corners. `strokeWidth`, `opacity`, `rotate`, and `blendMode` control appearance. `overflow="hidden"` clips content; do not hide accidental text overflow to make a broken layout appear correct.- `effects` accepts structured effects such as `dropShadow`, `innerShadow`, and `layerBlur`. `shadow` takes a CSS `box-shadow` list, such as `shadow="0 4 8 #0002, inset 0 1 0 #fff"`, and `blur` a layer blur radius; both are convenient shorthands. Effect helpers take `radius`, as Figma's effects do; when a JSX string is rendered, an option a paint or effect helper does not support is reported as a warning.-- Text content belongs inside `Text`. Use `size`, `font`, `weight`, `italic`, `lineHeight`, `letterSpacing`, `textAlign`, `textAlignVertical`, `textDecoration`, and `textCase`. Verify fonts actually load before judging dimensions; do not assume every font is available.-- `Span` styles some characters of a `Text` with `Text`'s own prop names: `size`, `font`, `weight`, `italic`, `color`, `lineHeight`, `letterSpacing`, and `textDecoration`. Spans nest; the inner one wins. `Paragraph` writes one paragraph: `list="ordered"` or `list="unordered"` makes it a list item nested at `level` 1–5, and `spacing`, `listSpacing`, and `indent` give it spacing of its own. A `Text` holds only `Paragraph`s or none; without them, a line break in its text still starts a paragraph.+- Text content belongs inside `Text`. Use `size`, `font`, `weight`, `italic`, `lineHeight`, `letterSpacing`, `textAlign`, `textAlignVertical`, `textDecoration`, and `textCase`. Decorations take CSS's names and values: `textDecorationStyle` (`solid`, `dotted`, `wavy`), `textDecorationColor` (`currentColor` follows the text), `textDecorationThickness` and `textUnderlineOffset` (pixels or `auto`), and `textDecorationSkipInk`. `lineHeight="auto"` follows the font, and `fills={[]}` paints no text. Verify fonts actually load before judging dimensions; do not assume every font is available.+- `Span` styles some characters of a `Text` with `Text`'s own prop names: `size`, `font`, `weight`, `italic`, `color`, `fills`, `lineHeight`, `letterSpacing`, `textDecoration`, and the decoration details. Spans nest; the inner one wins. `Paragraph` writes one paragraph: `list="ordered"` or `list="unordered"` makes it a list item nested at `level` 1–5, and `spacing`, `listSpacing`, and `indent` override the `Text`'s `paragraphSpacing`, `listSpacing`, and `paragraphIndent` for it; `hangingList` on the `Text` hangs list markers outside the text box. A `Text` holds only `Paragraph`s or none; without them, a line break in its text still starts a paragraph.- `Icon` uses an Iconify name, size, and color. Prefer icons to emoji when reliable vector output is needed. Image fills belong on appropriate leaf shapes, not containers whose children must remain visible.- Design JSX props are the portable authoring interface. Some CSS-style aliases are supported, but this is not a browser CSS engine; do not assume arbitrary HTML, classes, or styles work.@@ -89,8 +89,8 @@ The examples below are executed by the authoring-reference tests. Create the nam```jsx<Frame name="Release notes" w={280} h="hug" flex="col" gap={8} p={16} bg="#FFFFFF">-<Text name="Notes" w="fill" size={12} color="#252A31">- <Paragraph spacing={8}>Version 2 is <Span weight="bold" color="#3B6CF6">out now</Span>.</Paragraph>+<Text name="Notes" w="fill" size={12} color="#252A31" paragraphSpacing={4}>+ <Paragraph spacing={8}>Version 2 is <Span weight="bold" color="#3B6CF6" textDecoration="underline" textDecorationStyle="wavy" textUnderlineOffset={2}>out now</Span>.</Paragraph><Paragraph list="unordered">Faster export</Paragraph><Paragraph list="unordered" level={2}>PDF and SVG</Paragraph><Paragraph list="ordered">Fewer clicks</Paragraph>@@ -106,4 +106,4 @@ Generated from the renderer metadata. This inventory lists accepted names, not a**Helpers:** `solid`, `gradient`, `linearGradient`, `radialGradient`, `angularGradient`, `diamondGradient`, `shader`, `dropShadow`, `innerShadow`, `layerBlur`, `backgroundBlur`, `foregroundBlur`, `designVar`, `defineVars`.-**Properties:** `name`, `key`, `flex`, `flow`, `dir`, `gap`, `wrap`, `rowGap`, `columnGap`, `justify`, `justifyContent`, `items`, `align`, `alignItems`, `grow`, `w`, `h`, `width`, `height`, `minW`, `maxW`, `minH`, `maxH`, `x`, `y`, `top`, `left`, `position`, `constraints`, `p`, `padding`, `px`, `py`, `pt`, `pr`, `pb`, `pl`, `bg`, `fill`, `fills`, `background`, `backgroundColor`, `stroke`, `border`, `borderColor`, `strokeWidth`, `borderWidth`, `strokeAlign`, `strokeDash`, `strokeCap`, `strokeJoin`, `dashPattern`, `strokes`, `strokeWeights`, `rounded`, `borderRadius`, `roundedTL`, `roundedTR`, `roundedBL`, `roundedBR`, `cornerRadius`, `cornerSmoothing`, `opacity`, `blendMode`, `rotate`, `rotation`, `overflow`, `mask`, `visible`, `locked`, `shadow`, `blur`, `effects`, `size`, `fontSize`, `font`, `fontFamily`, `weight`, `fontWeight`, `italic`, `color`, `text`, `characters`, `content`, `value`, `title`, `textAlign`, `textAlignHorizontal`, `textHorizontalAlignment`, `textAlignVertical`, `textVerticalAlignment`, `textAutoResize`, `lineHeight`, `letterSpacing`, `textDecoration`, `textCase`, `list`, `level`, `spacing`, `listSpacing`, `indent`, `maxLines`, `truncate`, `grid`, `columns`, `rows`, `colStart`, `rowStart`, `col`, `row`, `colSpan`, `rowSpan`, `points`, `pointCount`, `innerRadius`, `label`, `style`, `bind`, `component`, `componentId`, `properties`, `propertyRefs`, `of`, `modelValue`, `open`, `disabled`, `filled`, `states`, `min`, `max`, `step`, `defaultValue`.\ No newline at end of file+**Properties:** `name`, `key`, `flex`, `flow`, `dir`, `gap`, `wrap`, `rowGap`, `columnGap`, `justify`, `justifyContent`, `items`, `align`, `alignItems`, `grow`, `w`, `h`, `width`, `height`, `minW`, `maxW`, `minH`, `maxH`, `x`, `y`, `top`, `left`, `position`, `constraints`, `p`, `padding`, `px`, `py`, `pt`, `pr`, `pb`, `pl`, `bg`, `fill`, `fills`, `background`, `backgroundColor`, `stroke`, `border`, `borderColor`, `strokeWidth`, `borderWidth`, `strokeAlign`, `strokeDash`, `strokeCap`, `strokeJoin`, `dashPattern`, `strokes`, `strokeWeights`, `rounded`, `borderRadius`, `roundedTL`, `roundedTR`, `roundedBL`, `roundedBR`, `cornerRadius`, `cornerSmoothing`, `opacity`, `blendMode`, `rotate`, `rotation`, `overflow`, `mask`, `visible`, `locked`, `shadow`, `blur`, `effects`, `size`, `fontSize`, `font`, `fontFamily`, `weight`, `fontWeight`, `italic`, `color`, `text`, `characters`, `content`, `value`, `title`, `textAlign`, `textAlignHorizontal`, `textHorizontalAlignment`, `textAlignVertical`, `textVerticalAlignment`, `textAutoResize`, `lineHeight`, `letterSpacing`, `textDecoration`, `textDecorationStyle`, `textDecorationColor`, `textDecorationThickness`, `textUnderlineOffset`, `textDecorationSkipInk`, `textCase`, `paragraphSpacing`, `paragraphIndent`, `hangingList`, `list`, `level`, `spacing`, `listSpacing`, `indent`, `maxLines`, `truncate`, `grid`, `columns`, `rows`, `colStart`, `rowStart`, `col`, `row`, `colSpan`, `rowSpan`, `points`, `pointCount`, `innerRadius`, `label`, `style`, `bind`, `component`, `componentId`, `properties`, `propertyRefs`, `of`, `modelValue`, `open`, `disabled`, `filled`, `states`, `min`, `max`, `step`, `defaultValue`.\ No newline at end of filediff --git a/src/components/code-editor/layers/attributes.ts b/src/components/code-editor/layers/attributes.tsindex e7bcb2268..6736e14ee 100644--- a/src/components/code-editor/layers/attributes.ts+++ b/src/components/code-editor/layers/attributes.ts@@ -8,7 +8,7 @@ import {} from '@open-pencil/design-jsx'import type { PatchContext } from './context'-import { attributeName, isLiteralAttribute, type SyntaxNode } from './syntax'+import { attributeName, indentAt, isLiteralAttribute, reindent, type SyntaxNode } from './syntax'/** Alias → the name Design JSX writes, e.g. `width` → `w`. */const CANONICAL_NAMES = new Map(@@ -158,20 +158,50 @@ export function patchAttributes(if (anchor) ctx.changes.push({ from: anchor.to, insert: ` ${additions.join(' ')}` })}-export function patchText(ctx: PatchContext, node: SyntaxNode, text: string | null) {+/** Described text content as it is written inside an element indented by `indent`. */+function writtenContent(text: string | null, indent: string): string {+ if (!text) return ''+ // Content on lines of its own, such as paragraphs, ends where the closing tag is indented.+ return reindent(text, indent) + (text.endsWith('\n') ? indent : '')+}++/**+ * Writes a text's content from the canvas. Content still as the code was last in sync with,+ * spans and paragraphs included, is replaced as a whole, as is plain text the person wrote;+ * content with expressions or elements of the person's own is theirs and stays.+ */+export function patchText(+ ctx: PatchContext,+ node: SyntaxNode,+ base: string | null,+ text: string | null+) {const open = node.getChild('JSXOpenTag')const close = node.getChild('JSXCloseTag')if (!open || !close) return- // Text with expressions or elements in it is the author's; only plain text is replaced.- for (let child = open.nextSibling; child && child.from < close.from; child = child.nextSibling) {- if (child.name !== 'JSXText') return- }+ const indent = indentAt(ctx.state, node.from)const content = ctx.state.doc.sliceString(open.to, close.from)+ const insert = writtenContent(text, indent)+ const unchanged = content === writtenContent(base, indent)+ if (!unchanged && !isPlainContent(open, close)) return+ // Plain text the person spaced out keeps the spacing around it, unless paragraphs replace it.+ if (unchanged || insert.startsWith('\n')) {+ ctx.changes.push({ from: open.to, to: close.from, insert })+ return+ }const leading = content.length - content.trimStart().lengthconst trailing = content.length - content.trimEnd().lengthctx.changes.push({from: open.to + leading,to: Math.max(open.to + leading, close.from - trailing),- insert: text ?? ''+ insert})}++/** Whether only text sits between the tags, no expressions or elements. */+function isPlainContent(open: SyntaxNode, close: SyntaxNode): boolean {+ for (let child = open.nextSibling; child && child.from < close.from; child = child.nextSibling) {+ if (child.name !== 'JSXText') return false+ }+ return true+}diff --git a/src/components/code-editor/layers/patch.ts b/src/components/code-editor/layers/patch.tsindex 72830705c..754cc76d7 100644--- a/src/components/code-editor/layers/patch.ts+++ b/src/components/code-editor/layers/patch.ts@@ -56,7 +56,7 @@ export function layerPatch(state: EditorState, snippet: LayerSnippet): Transacticonst tag = node && openingTagOf(node)if (!node || !tag || next.tag !== base.tag) continuepatchAttributes(ctx, tag, base, next)- if (base.text !== next.text) patchText(ctx, node, next.text)+ if (base.text !== next.text) patchText(ctx, node, base.text, next.text)patchChildren(ctx, node, element, elements, base, next)}if (bases.size === 0) return nulldiff --git a/tests/e2e/code/layer-links.spec.ts b/tests/e2e/code/layer-links.spec.tsindex 401b55c5b..fa9b40a8a 100644--- a/tests/e2e/code/layer-links.spec.ts+++ b/tests/e2e/code/layer-links.spec.ts@@ -236,6 +236,39 @@ test('canvas edits patch code a person wrote and keep the rest as written', asyn)})+function richText(page: Page, name: string) {+ return page.evaluate((name) => {+ const store = window.openPencil?.getStore?.()+ const node = [...(store?.graph.getAllNodes() ?? [])].find((n) => n.name === name)+ return node ? { styleRuns: node.styleRuns, textParagraphs: node.textParagraphs } : null+ }, name)+}++test('rich text styled on the canvas is written into the code and kept by code edits', async () => {+ await buildScene(editor.page)+ await openCode(editor.page)+ await personalizeCode(editor.page)++ const styleRuns = [{ start: 6, length: 5, style: { fontWeight: 700 } }]+ await editLayer(editor.page, 'Fine print', { styleRuns })+ await expect(codeLine(editor.page, 'name="Fine print"')).toContainText(+ 'Terms <Span weight="bold">apply</Span></Text>'+ )++ const textParagraphs = [{ listType: 'UNORDERED', indentation: 1 }]+ await editLayer(editor.page, 'Fine print', { textParagraphs })+ await expect(+ codeLine(editor.page, '<Paragraph list="unordered">Terms <Span weight="bold">apply</Span>')+ ).toBeVisible()+ expect(await codeText(editor.page)).toContain('// Pricing card')++ // Code edited after that renders the text with its spans and paragraphs, not as plain text.+ await codeLine(editor.page, 'name="Card"').locator('span', { hasText: /^320$/ }).dblclick()+ await editor.page.keyboard.type('360')+ await expect.poll(() => cardSize(editor.page)).toBe('360x160')+ expect(await richText(editor.page, 'Fine print')).toEqual({ styleRuns, textParagraphs })+})+test('layers added or deleted on the canvas are written into the code', async () => {await buildScene(editor.page)await openCode(editor.page)diff --git a/tests/engine/clipboard/figma/html.test.ts b/tests/engine/clipboard/figma/html.test.tsindex 6a44657c7..7d0b5800f 100644--- a/tests/engine/clipboard/figma/html.test.ts+++ b/tests/engine/clipboard/figma/html.test.ts@@ -153,8 +153,9 @@ describe('buildFigmaClipboardHTML', () => {expectFigmaEditableTextDefaults(textNode)const glyphs = textNode.derivedTextData?.glyphs ?? []expect(glyphs.length).toBeGreaterThan(0)- // Bold and italic Inter are not loaded, so no glyph gets an outline from the wrong font.- expect(glyphs.every((glyph) => glyph.commandsBlob === undefined)).toBe(true)+ // Without bold and italic Inter loaded, the paragraph draws them in the face it has, and the+ // glyphs keep that face's outlines: Figma shows nothing for glyphs saved without them.+ expect(glyphs.every((glyph) => glyph.commandsBlob !== undefined)).toBe(true)expect(textNode.derivedTextData?.baselines).toHaveLength(1)expect(textNode.derivedTextData?.logicalIndexToCharacterOffsetMap?.length).toBe(text.text.length@@ -162,7 +163,7 @@ describe('buildFigmaClipboardHTML', () => {expect(textNode.derivedTextData?.derivedLines).toEqual([{ directionality: 'LTR' }])})- it('writes the fallback layout without outlines when the font is unavailable', async () => {+ it('writes text whose font is unavailable in the font that drew it', async () => {const graph = new SceneGraph()const page = graph.getPages()[0]graph.createNode('TEXT', page.id, {@@ -184,11 +185,11 @@ describe('buildFigmaClipboardHTML', () => {const textNode = parsed?.nodes.find((node) => node.type === 'TEXT')const baseline = textNode?.derivedTextData?.baselines?.[0]- // The text keeps its auto-resize, so Figma reflows it in its own font instead of fixing the box.+ // The text keeps its auto-resize, so Figma reflows it in its own font once it is edited.expect(textNode?.textAutoResize).toBe('HEIGHT')const glyphs = textNode?.derivedTextData?.glyphs ?? []expect(glyphs).toHaveLength('Analytics Overview'.length)- expect(glyphs.every((glyph) => glyph.commandsBlob === undefined)).toBe(true)+ expect(glyphs.every((glyph) => glyph.commandsBlob !== undefined)).toBe(true)expect(textNode?.derivedTextData?.baselines).toHaveLength(1)expect(baseline?.width).toBeLessThanOrEqual(552)expect(baseline?.lineHeight).toBe(67)diff --git a/tests/engine/io/fig/export/text.test.ts b/tests/engine/io/fig/export/text.test.tsindex 2cd6fd254..ac5ec9511 100644--- a/tests/engine/io/fig/export/text.test.ts+++ b/tests/engine/io/fig/export/text.test.ts@@ -274,7 +274,8 @@ describe('text node export', () => {)expect(textNc.textAutoResize).toBe('NONE')- expect(textNc.lineHeight).toBeUndefined()+ // Auto line height, written as Figma writes it.+ expect(textNc.lineHeight).toEqual({ value: 100, units: 'PERCENT' })expect(textNc.stackChildAlignSelf).toBeUndefined()})diff --git a/tests/engine/io/fig/import/legacy/text.test.ts b/tests/engine/io/fig/import/legacy/text.test.tsindex a5da5d28c..6246dd4ca 100644--- a/tests/engine/io/fig/import/legacy/text.test.ts+++ b/tests/engine/io/fig/import/legacy/text.test.ts@@ -99,6 +99,39 @@ describe('fig-import: text properties', () => {expect(n.lineHeight).toBe(16.94)})+ test('reads line heights as Figma writes them: auto as 100 percent, a percent as a multiplier', () => {+ // A 40px word on the first line: its height must not fix every line of an auto text.+ const derivedTextData = {+ baselines: [+ {+ firstCharacter: 0,+ endCharacter: 6,+ position: { x: 0, y: 38.5 },+ width: 100,+ lineY: 0,+ lineHeight: 48.4,+ lineAscent: 38+ }+ ]+ }+ const text = (lineHeight: NodeChange['lineHeight'], guid: number) =>+ node('TEXT', guid, 1, {+ textData: { characters: 'Mixed\nlines' },+ fontSize: 24,+ lineHeight,+ derivedTextData+ } as Partial<NodeChange>)+ const graph = materializeDocument([+ doc(),+ canvas(),+ text({ value: 100, units: 'PERCENT' }, 10),+ text({ value: 1.5, units: 'RAW' }, 11)+ ]).graph+ const [auto, raw] = graph.getChildren(graph.getPages()[0].id)+ expect(auto?.lineHeight).toBeNull()+ expect(raw?.lineHeight).toBe(36)+ })+test('applies shared text style refs', () => {const graph = materializeDocument([doc(),diff --git a/tests/engine/kiwi/serialize-fixes/line/height.test.ts b/tests/engine/kiwi/serialize-fixes/line/height.test.tsindex 82d9f9a43..020566c87 100644--- a/tests/engine/kiwi/serialize-fixes/line/height.test.ts+++ b/tests/engine/kiwi/serialize-fixes/line/height.test.ts@@ -26,7 +26,7 @@ describe('Fix 4: text lineHeight serialization', () => {expect(changes[0].lineHeight).toEqual({ value: 24, units: 'PIXELS' })})- test('text node without lineHeight omits lineHeight', () => {+ test('text node in auto line height writes it as Figma does', () => {const graph = new SceneGraph()const node = graph.createNode('TEXT', pageId(graph), {name: 'DefaultLH',@@ -41,7 +41,7 @@ describe('Fix 4: text lineHeight serialization', () => {})const changes = toKiwi(node, graph)- expect(changes[0].lineHeight).toBeUndefined()+ expect(changes[0].lineHeight).toEqual({ value: 100, units: 'PERCENT' })})test('lineHeight survives roundtrip through export/parse', async () => {diff --git a/tests/engine/text/fonts/loading.test.ts b/tests/engine/text/fonts/loading.test.tsindex f1201b707..d2300070b 100644--- a/tests/engine/text/fonts/loading.test.ts+++ b/tests/engine/text/fonts/loading.test.ts@@ -6,6 +6,7 @@ import type { CanvasKit, TypefaceFontProvider } from 'canvaskit-wasm'import {chooseLocalFontMatch,+ fontWeightMatchOrder,fontManager,isVariableFont,normalizeFontFamily,@@ -108,6 +109,26 @@ describe('chooseLocalFontMatch', () => {test('does not substitute nearby weights for explicit style requests', () => {expect(chooseLocalFontMatch(fonts, 'Inter', 'Bold')).toBeUndefined()})++ test('without a style, takes the face CSS font matching picks for regular', () => {+ const faces = [+ { family: 'Inter', style: 'Black' },+ { family: 'Inter', style: 'Light Italic' },+ { family: 'Inter', style: 'Medium' },+ { family: 'Inter', style: 'Light' }+ ]+ // Regular falls to medium before lighter weights, and the upright slant before italic.+ expect(chooseLocalFontMatch(faces, 'Inter')?.style).toBe('Medium')+ expect(chooseLocalFontMatch(faces.slice(0, 2), 'Inter')?.style).toBe('Black')+ })+})++describe('fontWeightMatchOrder', () => {+ test('tries weights in CSS font matching order', () => {+ expect(fontWeightMatchOrder(400)).toEqual([400, 500, 300, 200, 100, 600, 700, 800, 900])+ expect(fontWeightMatchOrder(700)).toEqual([700, 800, 900, 600, 500, 400, 300, 200, 100])+ expect(fontWeightMatchOrder(300)).toEqual([300, 200, 100, 400, 500, 600, 700, 800, 900])+ })})describe('FontManager loaded font cache', () => {