AI-native design editor. Open-source Figma alternative.
feat(figma-api): style text by character range as Figma does (#1071)
Danila Poyarkovb566df1b519d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4139c6128..9687c87a8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,7 @@### Breaking changes+- In scripts, a text node's `fontSize`, `fontName`, `fontWeight`, `fills`, `letterSpacing`, `lineHeight`, and `textDecoration` read `figma.mixed` while its characters differ, as in Figma, instead of the text's first value, and setting one restyles every character instead of only characters without a style of their own. `fills` is typed `readonly Fill[] | symbol`, so scripts that index it narrow it first.- `SceneNode` from `@open-pencil/scene-graph` has `textParagraphs`, `listSpacing`, `paragraphSpacing`, `paragraphIndent`, and `hangingList`, so code that builds `SceneNode` objects itself must include them. `SkiaRenderer.buildParagraph` returns a `TextLayout`, which answers the `Paragraph` queries the renderer and text editor use for the whole text and draws with `draw(canvas, x, y)`, instead of a CanvasKit `Paragraph`.- `AUTO_LAYOUT_BREAK_THRESHOLD` is removed from `@open-pencil/core/constants`: a layer dragged out of auto layout now leaves by how far its own edge is past the frame, not by a cursor margin.- `SceneNode` from `@open-pencil/scene-graph` has `targetAspectRatio`, the size whose proportions a locked layer keeps, so code that builds `SceneNode` objects itself must include it.@@ -51,6 +52,9 @@### 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.+- 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.- Move a layer in an auto layout row or column with the arrow keys, as in Figma: Right and Left move it one slot along a row, Down and Up along a column, Shift too, and the arrows across the flow do nothing. With several layers selected, each moves one slot and one at the end stays; a run of keys is one undo step.@@ -175,6 +179,9 @@### Fixed+- 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.- 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/AGENTS.md b/packages/core/AGENTS.mdindex 14f8c2f49..c06663021 100644--- a/packages/core/AGENTS.md+++ b/packages/core/AGENTS.md@@ -81,6 +81,10 @@ Canvas is CanvasKit (Skia WASM) on a WebGL surface, not DOM.- Paragraph construction is typed against `packages/core/src/canvas/text/paragraph/inputs.ts`; the same inputs drive preparation-cache invalidation. Add a mutation case when extending that contract. Drawing borrows native paragraphs; the renderer owns their bounded cache and destruction.- Text lays out through `buildParagraph` into a `TextLayout` (`packages/core/src/canvas/text/layout/`): one native paragraph for plain text, or one per paragraph with its list indent, marker, and spacing, since Skia has no hanging indent. Drawing, measurement, the text editor, saved glyphs (`shapeText`), and text outlines all read that layout rather than laying text out again (`packages/core/tests/canvas/text/lists.test.ts`).+### Text decorations++- Underlines and strikethroughs come from `textDecorationRects` (`packages/core/src/canvas/text/decorations.ts`), Figma's geometry over laid-out or saved glyphs, both for drawing and for the rects `.fig` files save, which Figma draws decorations from; Skia's paragraph decorations stay off. Drawn decorations are kept with the prepared text, whose paragraph inputs cover them, or by saved glyphs in the renderer's `derivedDecorationCache` (`packages/core/tests/canvas/text/decorations.test.ts`).+### Geometry and overlays- Use `@open-pencil/core/geometry` for world/screen transforms, inverses, bounds, and handle placement instead of interpreting ancestor rotations or reflections independently.@@ -101,5 +105,5 @@ Pixel-affecting features need committed visual coverage, not only mock or geomet- **Behavior follows Figma.** Read the Plugin API documentation for the member, and for anything observable (geometry, ordering, defaults, errors) run the same script in live Figma and record the observed result in the test. `figma-use` and `tests/figma/` are the live oracle; `tests/fixtures/figma-oracles/` holds recorded values.- **User actions are shared code.** When an editor command does the same thing (group, ungroup, boolean, flatten, instance creation, component sync), call the implementation under `packages/core/src/editor/` or its shared helper. Do not reimplement geometry, placement, or propagation here; new geometry helpers belong in Scene Graph.- Geometry getters lay out what the graph's edits touched since the last read, as Figma does, through `flushPendingLayout` in `packages/core/src/figma-api/pending-layout.ts`; a new geometry getter calls it first (`packages/core/tests/figma-api/pending-layout.test.ts`).-- Node proxies live in `packages/core/src/figma-api/proxy.ts` and `packages/core/src/figma-api/accessors/`; `packages/core/src/figma-api/render-bounds.ts` implements Figma's `absoluteRenderBounds` semantics and is the only geometry that is Figma-specific.-- `packages/core/src/figma-api/index.ts` stays under the 600-line limit by moving whole domains into sibling modules such as `components.ts` and `text.ts`, not by extracting generic helpers into this folder.+- Node proxies live in `packages/core/src/figma-api/proxy.ts` and `packages/core/src/figma-api/accessors/`; per-character text styles are modelled in `packages/core/src/text/character-style.ts`, which the editor's selection styling shares, and read for scripts in `packages/core/src/figma-api/text/style.ts`, which node getters, range methods, and segments all use (`packages/core/tests/figma-api/text/styles.test.ts`); `packages/core/src/figma-api/render-bounds.ts` implements Figma's `absoluteRenderBounds` semantics and is the only geometry that is Figma-specific.+- `packages/core/src/figma-api/index.ts` stays under the 600-line limit by moving whole domains into sibling modules such as `components.ts` and `text/`, not by extracting generic helpers into this folder.diff --git a/packages/core/src/canvas/renderer.ts b/packages/core/src/canvas/renderer.tsindex 035aa3644..06e163806 100644--- a/packages/core/src/canvas/renderer.ts+++ b/packages/core/src/canvas/renderer.ts@@ -39,6 +39,7 @@ import * as RenderPipeline from './renderer/pipeline'import type { SceneBacking, SceneBackingBuild } from './renderer/retained-backing/types'import * as RendererState from './renderer/state'import * as RenderText from './text'+import type { SavedDecorationCache } from './text/decorations'import { createDerivedGlyphPathCache, createGlyphSilhouetteCache } from './text/derived'import { TextPreparationCache } from './text/preparation/cache'export type {@@ -147,6 +148,7 @@ export class SkiaRenderer {/** Path-text glyph silhouettes (stroke-and-union, font units) keyed by blob hash + relative weight. */glyphSilhouetteCache = createGlyphSilhouetteCache()derivedGlyphPathCache = createDerivedGlyphPathCache()+ derivedDecorationCache: SavedDecorationCache = new WeakMap()renderingSceneBacking = falsescenePicture: SkPicture | null = nullscenePictureVersion = -1diff --git a/packages/core/src/canvas/scene.ts b/packages/core/src/canvas/scene.tsindex 29715e7f8..b0e3d0d12 100644--- a/packages/core/src/canvas/scene.ts+++ b/packages/core/src/canvas/scene.ts@@ -41,6 +41,7 @@ import {normalizeDashPattern} from './strokes'import { textVerticalOffset, withTextParagraph } from './text'+import { drawTextLayout } from './text/decorations'import {canDrawSavedText,drawDerivedText,@@ -921,8 +922,9 @@ function drawPaintedText(r: SkiaRenderer, canvas: Canvas, node: SceneNode): boolhalfLeading: true,foregroundPaint: r.fillPaint},- (paragraph) => {- paragraph.draw(canvas, 0, textVerticalOffset(node, paragraph.getHeight()))+ (paragraph, prepared) => {+ const y = textVerticalOffset(node, paragraph.getHeight())+ drawTextLayout(r.ck, canvas, node, prepared, y, r.fillPaint)return true})@@ -995,10 +997,16 @@ export function renderText(r: SkiaRenderer, canvas: Canvas, node: SceneNode, filreturn}if (r.fontsLoaded && r.fontProvider) {- withTextParagraph(r, node, r.fillPaint.getColor(), { halfLeading: true }, (paragraph) => {- const paragraphY = textVerticalOffset(node, paragraph.getHeight())- paragraph.draw(canvas, 0, paragraphY)- })+ withTextParagraph(+ r,+ node,+ r.fillPaint.getColor(),+ { halfLeading: true },+ (paragraph, prepared) => {+ const paragraphY = textVerticalOffset(node, paragraph.getHeight())+ drawTextLayout(r.ck, canvas, node, prepared, paragraphY, r.fillPaint)+ }+ )} else if (r.textFont) {const fontSize = node.fontSize || r.DEFAULT_FONT_SIZEconst paragraphY = textVerticalOffset(node, fontSize)diff --git a/packages/core/src/canvas/text/decorations.ts b/packages/core/src/canvas/text/decorations.tsnew file mode 100644index 000000000..f6022a65b--- /dev/null+++ b/packages/core/src/canvas/text/decorations.ts@@ -0,0 +1,367 @@+import type { Canvas, CanvasKit, Paint } from 'canvaskit-wasm'+import { isEqual } from 'es-toolkit/predicate'++import type {+ DerivedTextGlyph,+ Fill,+ SceneNode,+ TextDecorationStyle+} from '@open-pencil/scene-graph'+import { resolveRGBAForPreview } from '@open-pencil/scene-graph/color'++import { outlineInk, savedGlyphInk, type InkSpan } from '#core/canvas/text/ink'+import { laidOutGlyphs, type LaidOutGlyph } from '#core/canvas/text/placed'+import type { PreparedText } from '#core/canvas/text/preparation/cache'+import { transformTextCase } from '#core/text/case'+import { characterStyles, TEXT_STYLE_KEYS, type CharacterStyle } from '#core/text/character-style'+import { weightToStyle } from '#core/text/fonts'+import { fontDecorationMetricsSync, type FontDecorationMetrics } from '#core/text/opentype'++/**+ * Figma's Inter, measured from the decorations it saves, for text drawn without its font: its+ * glyphs come from the file, but the font's own metrics are not at hand.+ */+const UNLOADED_FONT_METRICS: FontDecorationMetrics = {+ underlineTop: 0.19887,+ underlineThickness: 0.06818,+ strikethroughTop: -0.32742,+ strikethroughThickness: 0.06818+}++/** A glyph where it stands, as saved and freshly laid-out glyphs both give it. */+export type PlacedGlyph = Pick<+ DerivedTextGlyph,+ 'x' | 'y' | 'firstCharacter' | 'advance' | 'scaleX'+>++/** A placed glyph that can tell where its ink crosses a band, when its outline is known. */+export interface DecoratedGlyph extends PlacedGlyph {+ ink?: (top: number, bottom: number) => InkSpan | null+}++/** Decorated characters on one line: its baseline, their extent, and the glyphs drawing them. */+interface LineSpan {+ baseline: number+ x1: number+ x2: number+ glyphs: { glyph: DecoratedGlyph; advance: number }[]+}++/** One underline or strikethrough on one line, as Figma saves it. */+export interface TextDecorationRect {+ /** The first character it decorates, by whose style Figma saves it. */+ firstCharacter: number+ x: number+ y: number+ width: number+ height: number+ style: TextDecorationStyle+ /** The decoration's own paints, or the text's when it has none. */+ fills: Fill[]+}++/** Whether any character of the text is underlined or struck through. */+export function hasDecoration(node: SceneNode): boolean {+ return (+ node.textDecoration !== 'NONE' ||+ node.styleRuns.some((run) => run.style.textDecoration && run.style.textDecoration !== 'NONE')+ )+}++/** Whether two characters' decorations are one line: Figma joins characters of one style. */+function sameDecoration(a: CharacterStyle, b: CharacterStyle): boolean {+ return (+ a.textDecoration === b.textDecoration &&+ a.textDecorationStyle === b.textDecorationStyle &&+ a.textDecorationThickness === b.textDecorationThickness &&+ a.textUnderlineOffset === b.textUnderlineOffset &&+ a.fontFamily === b.fontFamily &&+ a.fontWeight === b.fontWeight &&+ a.italic === b.italic &&+ a.fontSize === b.fontSize &&+ isEqual(a.textDecorationFills, b.textDecorationFills) &&+ isEqual(a.fills, b.fills)+ )+}++/** A glyph's advance; one saved without it reaches the next glyph on its line. */+function glyphAdvance(glyph: PlacedGlyph, next: PlacedGlyph | undefined): number {+ if (glyph.advance !== undefined) return glyph.advance * (glyph.scaleX ?? 1)+ return next?.y === glyph.y ? next.x - glyph.x : 0+}++/** Where the glyphs drawing `text[start, end)` sit, one span per line. */+function lineSpans(+ glyphs: readonly DecoratedGlyph[],+ byCharacter: ReadonlyMap<number, number[]>,+ start: number,+ end: number+): LineSpan[] {+ const lines = new Map<number, LineSpan>()+ for (let character = start; character < end; character++) {+ for (const index of byCharacter.get(character) ?? []) {+ const glyph = glyphs[index]+ const advance = glyphAdvance(glyph, glyphs.at(index + 1))+ const line = lines.get(glyph.y)+ if (line) {+ line.x1 = Math.min(line.x1, glyph.x)+ line.x2 = Math.max(line.x2, glyph.x + advance)+ line.glyphs.push({ glyph, advance })+ } else {+ lines.set(glyph.y, {+ baseline: glyph.y,+ x1: glyph.x,+ x2: glyph.x + advance,+ glyphs: [{ glyph, advance }]+ })+ }+ }+ }+ return [...lines.values()]+}++/**+ * Where an underline breaks for descenders, as Figma skips ink: around each glyph's ink in the+ * band the underline covers before its baseline is rounded, kept within the glyph's own box and+ * widened by `pad` on each side.+ */+function inkGaps(line: LineSpan, top: number, height: number, pad: number): InkSpan[] {+ const bandTop = line.baseline + top+ const gaps: InkSpan[] = []+ for (const { glyph, advance } of line.glyphs) {+ const ink = glyph.ink?.(bandTop, bandTop + height)+ if (!ink) continue+ const left = Math.max(ink[0], glyph.x)+ const right = Math.min(ink[1], glyph.x + advance)+ if (right >= left) gaps.push([left - pad, right + pad])+ }+ return gaps.toSorted((a, b) => a[0] - b[0])+}++/** The parts of `[x1, x2]` outside every gap, but for pieces narrower than `minWidth`. */+function withoutGaps(+ x1: number,+ x2: number,+ gaps: readonly InkSpan[],+ minWidth: number+): InkSpan[] {+ const parts: InkSpan[] = []+ let from = x1+ for (const [left, right] of gaps) {+ if (left > from) parts.push([from, Math.min(left, x2)])+ from = Math.max(from, right)+ if (from >= x2) break+ }+ if (from < x2) parts.push([from, x2])+ if (gaps.length === 0) return parts+ return parts.filter(([left, right]) => right - left >= minWidth)+}++function decorationRects(+ style: CharacterStyle,+ firstCharacter: number,+ lines: LineSpan[]+): TextDecorationRect[] {+ const metrics =+ fontDecorationMetricsSync(style.fontFamily, weightToStyle(style.fontWeight, style.italic)) ??+ UNLOADED_FONT_METRICS+ const size = style.fontSize+ const underline = style.textDecoration === 'UNDERLINE'+ // Figma measures from the baseline rounded to a whole pixel. An underline's offset and+ // thickness replace the font's; a strikethrough always takes the font's, and is solid.+ const top = underline+ ? (style.textUnderlineOffset ?? metrics.underlineTop * size)+ : metrics.strikethroughTop * size+ const height = underline+ ? (style.textDecorationThickness ?? metrics.underlineThickness * size)+ : metrics.strikethroughThickness * size+ const fills = style.textDecorationFills.length > 0 ? style.textDecorationFills : style.fills+ const skipInk = underline && style.textDecorationSkipInk+ // Figma widens a solid underline's gaps by its thickness and drops the slivers they leave; a+ // dotted or wavy one's by 0.6 of it, keeping every piece (measured from 12px to 88px).+ const solid = !underline || style.textDecorationStyle === 'SOLID'+ const pad = solid ? height : height * 0.6+ const minWidth = solid ? height : 0+ return lines.flatMap((line) => {+ const gaps = skipInk ? inkGaps(line, top, height, pad) : []+ const parts = withoutGaps(line.x1, line.x2, gaps, minWidth)+ return parts.map(([x1, x2]) => ({+ firstCharacter,+ x: x1,+ y: Math.round(line.baseline) + top,+ width: x2 - x1,+ height,+ style: underline ? style.textDecorationStyle : 'SOLID',+ fills+ }))+ })+}++/**+ * The underlines and strikethroughs of a text over its glyphs, placed as Figma places them:+ * one per line for each run of characters decorated alike, from the font's metrics, with+ * underlines broken where descenders cross them.+ */+export function textDecorationRects(+ node: SceneNode,+ glyphs: readonly DecoratedGlyph[]+): TextDecorationRect[] {+ if (!hasDecoration(node)) return []+ const text = node.text+ const styles = characterStyles(node, 0, text.length)+ const byCharacter = new Map<number, number[]>()+ for (const [index, glyph] of glyphs.entries()) {+ if (glyph.firstCharacter === undefined) continue+ const indices = byCharacter.get(glyph.firstCharacter)+ if (indices) indices.push(index)+ else byCharacter.set(glyph.firstCharacter, [index])+ }+ const rects: TextDecorationRect[] = []+ let start = 0+ while (start < text.length) {+ const style = styles[start]+ if (style.textDecoration === 'NONE' || text[start] === '\n') {+ start+++ continue+ }+ let end = start + 1+ while (end < text.length && text[end] !== '\n' && sameDecoration(styles[end], style)) end+++ rects.push(...decorationRects(style, start, lineSpans(glyphs, byCharacter, start, end)))+ start = end+ }+ return rects+}++/** Saved glyphs, whose ink comes from their saved outlines. */+export function savedDecoratedGlyphs(glyphs: readonly DerivedTextGlyph[]): DecoratedGlyph[] {+ return glyphs.map((glyph) => ({+ ...glyph,+ ink: (top, bottom) => savedGlyphInk(glyph.commandsBlob, glyph, top, bottom)+ }))+}++/** Laid-out glyphs, whose ink comes from their font when it drew them. */+export function laidOutDecoratedGlyphs(glyphs: readonly LaidOutGlyph[]): DecoratedGlyph[] {+ return glyphs.map((glyph) => ({+ x: glyph.x,+ y: glyph.y,+ firstCharacter: glyph.firstCharacter,+ advance: glyph.advance,+ ink: (top, bottom) => {+ const commands = glyph.source?.outline(glyph.id, glyph.fontSize)+ return commands ? outlineInk(commands, glyph.x, glyph.y, top, bottom) : null+ }+ }))+}++function solidColor(fills: Fill[]): Fill | undefined {+ return fills.find((fill) => fill.visible && fill.type === 'SOLID')+}++function drawDots(canvas: Canvas, rect: TextDecorationRect, paint: Paint) {+ const radius = rect.height / 2+ const y = rect.y + radius+ for (let x = rect.x + radius; x <= rect.x + rect.width - radius; x += rect.height * 2) {+ canvas.drawCircle(x, y, radius, paint)+ }+}++function drawWave(ck: CanvasKit, canvas: Canvas, rect: TextDecorationRect, paint: Paint) {+ // A cosine through the rect's middle that starts in a trough, as Figma draws it.+ const amplitude = rect.height / 2+ const period = rect.height * 3.5+ const y = rect.y + rect.height / 2+ const step = Math.max(0.25, period / 32)+ const path = new ck.PathBuilder()+ path.moveTo(rect.x, y + amplitude)+ for (let x = rect.x + step; x < rect.x + rect.width; x += step) {+ path.lineTo(x, y + amplitude * Math.cos(((x - rect.x) / period) * Math.PI * 2))+ }+ const end = rect.x + rect.width+ path.lineTo(end, y + amplitude * Math.cos(((end - rect.x) / period) * Math.PI * 2))+ const wave = path.detachAndDelete()+ paint.setStyle(ck.PaintStyle.Stroke)+ paint.setStrokeWidth((rect.height * 2) / 3)+ canvas.drawPath(wave, paint)+ wave.delete()+}++/** Draws decorations in their own paints, or in `textPaint` where the text's has no colour. */+export function drawTextDecorations(+ ck: CanvasKit,+ canvas: Canvas,+ rects: readonly TextDecorationRect[],+ textPaint: Paint+): void {+ for (const rect of rects) {+ const fill = solidColor(rect.fills)+ const paint = textPaint.copy()+ try {+ paint.setAntiAlias(true)+ paint.setStyle(ck.PaintStyle.Fill)+ if (fill?.type === 'SOLID') {+ const { r: red, g, b, a } = resolveRGBAForPreview(fill.color).color+ paint.setShader(null)+ paint.setColor(ck.Color4f(red, g, b, a * fill.opacity))+ }+ if (rect.style === 'DOTTED') drawDots(canvas, rect, paint)+ else if (rect.style === 'WAVY') drawWave(ck, canvas, rect, paint)+ else canvas.drawRect(ck.XYWHRect(rect.x, rect.y, rect.width, rect.height), paint)+ } finally {+ paint.delete()+ }+ }+}++/** Decorations of saved glyphs, by the glyphs, with what they were found from. */+export type SavedDecorationCache = WeakMap<+ readonly DerivedTextGlyph[],+ { inputs: unknown[]; rects: TextDecorationRect[] }+>++/**+ * The decorations of text drawn from its saved glyphs. A change that moves or reshapes glyphs+ * replaces them, so only the character styles, and the fonts whose metrics place lines, can+ * change the decorations of the same glyphs.+ */+export function savedTextDecorationRects(+ cache: SavedDecorationCache,+ node: SceneNode,+ glyphs: readonly DerivedTextGlyph[],+ fontGeneration: number+): TextDecorationRect[] {+ const inputs = [+ node.text,+ node.styleRuns,+ fontGeneration,+ ...TEXT_STYLE_KEYS.map((key) => node[key])+ ]+ const cached = cache.get(glyphs)+ if (cached?.inputs.every((value, index) => value === inputs[index])) return cached.rects+ const rects = textDecorationRects(node, savedDecoratedGlyphs(glyphs))+ cache.set(glyphs, { inputs, rects })+ return rects+}++/**+ * Draws laid-out text and its decorations, `y` below the node's top. The decorations are kept+ * with the prepared text, which its cache replaces when an input of the text changes.+ */+export function drawTextLayout(+ ck: CanvasKit,+ canvas: Canvas,+ node: SceneNode,+ prepared: PreparedText,+ y: number,+ textPaint: Paint+): void {+ const layout = prepared.paragraph+ layout.draw(canvas, 0, y)+ if (!hasDecoration(node)) return+ if (prepared.decorations?.y !== y) {+ const glyphs = laidOutGlyphs(node, layout, transformTextCase(node.text, node.textCase), y)+ const rects = glyphs ? textDecorationRects(node, laidOutDecoratedGlyphs(glyphs)) : []+ prepared.decorations = { y, rects }+ }+ drawTextDecorations(ck, canvas, prepared.decorations.rects, textPaint)+}diff --git a/packages/core/src/canvas/text/derived.ts b/packages/core/src/canvas/text/derived.tsindex 777a801c9..c31ba89c1 100644--- a/packages/core/src/canvas/text/derived.ts+++ b/packages/core/src/canvas/text/derived.ts@@ -1,4 +1,4 @@-import type { Canvas, Paint, Path } from 'canvaskit-wasm'+import type { Canvas, Path } from 'canvaskit-wasm'import { fromUint8Array } from 'js-base64'import {@@ -10,13 +10,16 @@ import {type DerivedTextGlyph,type SceneNode,type Stroke,- type StyleRun,- type TextDecorationStyle,type TextParagraphRange} from '@open-pencil/scene-graph'import { ResourceCache } from '#core/cache/resource'import type { SkiaRenderer } from '#core/canvas/renderer'+import {+ drawTextDecorations,+ hasDecoration,+ savedTextDecorationRects+} from '#core/canvas/text/decorations'import { geometryBlobToPath } from '#core/vector'const MAX_GLYPH_SILHOUETTES = 512@@ -44,18 +47,6 @@ export function createGlyphSilhouetteCache(): ResourceCache<string, Path> {return new ResourceCache({ maxEntries: MAX_GLYPH_SILHOUETTES, dispose: (path) => path.delete() })}-interface DecorationRange {- x1: number- x2: number-}--interface DecorationSpan extends DecorationRange {- style: TextDecorationStyle- thickness: number- offset: number- fills: Fill[]-}-export function snapDerivedGlyphBaseline(y: number): number {return Math.round(y)}@@ -66,211 +57,6 @@ export function shouldUseHardDerivedGlyphCoverage(return node.fontSize === 20 && node.fontWeight === 400}-export function derivedUnderlineRect(node: Pick<SceneNode, 'width'>, baselineY: number) {- return {- x1: 0,- y1: baselineY + 2.75,- x2: Math.max(0, node.width - 0.75),- y2: baselineY + 3.75- }-}--/**- * Where the drawn text starts and ends, from its glyphs, when every glyph knows its advance;- * text narrower than its layer, or aligned to the centre or the end, does not reach its edges.- */-function derivedTextExtent(node: SceneNode): { x1: number; x2: number } | null {- const glyphs = node.derivedTextGlyphs ?? []- if (glyphs.length === 0) return null- // A loop rather than spreading into Math.min/max, which long texts would overflow.- let x1 = Infinity- let x2 = -Infinity- for (const glyph of glyphs) {- if (glyph.advance === undefined) return null- x1 = Math.min(x1, glyph.x)- x2 = Math.max(x2, glyph.x + glyph.advance * (glyph.scaleX ?? 1))- }- return { x1, x2 }-}--function styleRunX(node: SceneNode, index: number): number {- const glyph = node.derivedTextGlyphs?.[index]- if (glyph) return glyph.x- if (index >= node.text.length) return derivedTextExtent(node)?.x2 ?? node.width- if (node.text.length === 0) return 0- return (node.width * index) / node.text.length-}--function styleRunDecorationRange(node: SceneNode, run: StyleRun): DecorationRange | null {- const hasDecorationOverride =- run.style.textDecoration !== undefined ||- run.style.textDecorationStyle !== undefined ||- run.style.textDecorationThickness !== undefined ||- run.style.textDecorationFills !== undefined ||- run.style.textUnderlineOffset !== undefined- if (!hasDecorationOverride) return null- return {- x1: styleRunX(node, run.start),- x2: styleRunX(node, run.start + run.length)- }-}--function styleRunDecorationSpan(node: SceneNode, run: StyleRun): DecorationSpan | null {- const decoration = run.style.textDecoration ?? node.textDecoration- const hasDecorationOverride =- run.style.textDecoration !== undefined ||- run.style.textDecorationStyle !== undefined ||- run.style.textDecorationThickness !== undefined ||- run.style.textDecorationFills !== undefined ||- run.style.textUnderlineOffset !== undefined- if (decoration !== 'UNDERLINE' || !hasDecorationOverride) return null- return {- x1: styleRunX(node, run.start),- x2: styleRunX(node, run.start + run.length),- style: run.style.textDecorationStyle ?? node.textDecorationStyle,- thickness: run.style.textDecorationThickness ?? node.textDecorationThickness ?? 1,- offset: run.style.textUnderlineOffset ?? node.textUnderlineOffset ?? 0,- fills: run.style.textDecorationFills ?? node.textDecorationFills- }-}--function isDecorationRange(span: DecorationRange | null): span is DecorationRange {- return span !== null-}--function isDecorationSpan(span: DecorationSpan | null): span is DecorationSpan {- return span !== null-}--function baseDecorationSpan(node: SceneNode): DecorationSpan | null {- if (node.textDecoration !== 'UNDERLINE') return null- const rect = derivedUnderlineRect(node, 0)- const extent = derivedTextExtent(node)- return {- x1: extent?.x1 ?? rect.x1,- x2: extent?.x2 ?? rect.x2,- style: node.textDecorationStyle,- thickness: node.textDecorationThickness ?? rect.y2 - rect.y1,- offset: node.textUnderlineOffset ?? 0,- fills: node.textDecorationFills- }-}--function splitBaseDecorationSpan(- base: DecorationSpan,- overrides: DecorationRange[]-): DecorationSpan[] {- const spans: DecorationSpan[] = []- let cursor = base.x1- for (const override of overrides.toSorted((a, b) => a.x1 - b.x1)) {- if (override.x1 > cursor) spans.push({ ...base, x1: cursor, x2: override.x1 })- cursor = Math.max(cursor, override.x2)- }- if (cursor < base.x2) spans.push({ ...base, x1: cursor, x2: base.x2 })- return spans-}--function derivedDecorationSpans(node: SceneNode): DecorationSpan[] {- const overrideRanges = node.styleRuns- .map((run) => styleRunDecorationRange(node, run))- .filter(isDecorationRange)- const overrides = node.styleRuns- .map((run) => styleRunDecorationSpan(node, run))- .filter(isDecorationSpan)- const base = baseDecorationSpan(node)- return base ? [...splitBaseDecorationSpan(base, overrideRanges), ...overrides] : overrides-}--function firstVisibleFillColor(fills: Fill[]) {- const fill = fills.find((item) => item.visible && item.type === 'SOLID')- return fill?.color ?? null-}--function configureDecorationPaint(r: SkiaRenderer, span: DecorationSpan, paint: Paint): void {- const color = firstVisibleFillColor(span.fills)- if (color)- paint.setColor(r.ck.Color4f(color.r, color.g, color.b, color.a * (span.fills[0]?.opacity ?? 1)))- else paint.setColor(r.fillPaint.getColor())- paint.setAntiAlias(true)- paint.setStyle(r.ck.PaintStyle.Stroke)- paint.setStrokeWidth(span.thickness)-}--function drawSolidDecoration(- r: SkiaRenderer,- canvas: Canvas,- paint: Paint,- span: DecorationSpan,- y: number-): void {- paint.setStyle(r.ck.PaintStyle.Fill)- canvas.drawRect(r.ltrb(span.x1, y, span.x2, y + span.thickness), paint)-}--function drawDottedDecoration(- r: SkiaRenderer,- canvas: Canvas,- paint: Paint,- span: DecorationSpan,- y: number-): void {- paint.setStyle(r.ck.PaintStyle.Fill)- const dotSize = 1- const step = dotSize * 2- const dotY = y - span.thickness / 3- for (let x = span.x1; x <= span.x2; x += step) {- canvas.drawRect(r.ck.LTRBRect(x, dotY, x + dotSize, dotY + span.thickness), paint)- }-}--function drawWavyDecoration(- r: SkiaRenderer,- canvas: Canvas,- paint: Paint,- span: DecorationSpan,- y: number-): void {- const amplitude = Math.max(0.5, span.thickness * 0.5)- const wavelength = Math.max(6, span.thickness * 5)- const path = new r.ck.PathBuilder()- path.moveTo(span.x1, y)- for (let x = span.x1; x <= span.x2; x += 2) {- path.lineTo(x, y + Math.sin(((x - span.x1) / wavelength) * Math.PI * 2) * amplitude)- }- path.lineTo(span.x2, y)- const immutablePath = path.detachAndDelete()- canvas.drawPath(immutablePath, paint)- immutablePath.delete()-}--function derivedDecorationY(node: SceneNode, span: DecorationSpan, baselineY: number): number {- const hasRichDecoration = span.style !== 'SOLID' || span.fills.length > 0- if (!hasRichDecoration) return derivedUnderlineRect(node, baselineY).y1 + span.offset- return baselineY + node.fontSize / 2 - span.thickness / 4 + span.offset-}--function drawDerivedDecorations(- r: SkiaRenderer,- canvas: Canvas,- node: SceneNode,- baselineY: number-): void {- const spans = derivedDecorationSpans(node)- if (spans.length === 0) return- const paint = new r.ck.Paint()- try {- for (const span of spans) {- const y = derivedDecorationY(node, span, baselineY)- configureDecorationPaint(r, span, paint)- if (span.style === 'DOTTED') drawDottedDecoration(r, canvas, paint, span, y)- else if (span.style === 'WAVY') drawWavyDecoration(r, canvas, paint, span, y)- else drawSolidDecoration(r, canvas, paint, span, y)- }- } finally {- paint.delete()- }-}-/*** Path-text glyphs carry non-zero Figma `Glyph.rotation` (radians). Used to* disable axis-aligned assumptions (baseline snap, underline decorations).@@ -489,10 +275,8 @@ export function drawDerivedText(r: SkiaRenderer, canvas: Canvas, node: SceneNodeconst snapBaselines = !hasRotatedDerivedGlyphs(node)const savedTextEligible = savedTextEligibility(node)const markerCharacters = markerStyleCharacters(node)- let underlineBaselineY = 0for (const [index, glyph] of node.derivedTextGlyphs.entries()) {const glyphY = snapBaselines ? snapDerivedGlyphBaseline(glyph.y) : glyph.y- underlineBaselineY = Math.max(underlineBaselineY, glyphY)const path = derivedGlyphPath(r, glyph.commandsBlob)canvas.save()applyGlyphEmTransform(canvas, glyph, glyphY)@@ -521,7 +305,11 @@ export function drawDerivedText(r: SkiaRenderer, canvas: Canvas, node: SceneNodecanvas.restore()}- // Underline math assumes a single horizontal baseline — skip for path text.- if (snapBaselines) drawDerivedDecorations(r, canvas, node, underlineBaselineY)+ // Decorations follow horizontal lines; path text has none.+ if (snapBaselines && hasDecoration(node)) {+ const glyphs = node.derivedTextGlyphs+ const rects = savedTextDecorationRects(r.derivedDecorationCache, node, glyphs, r.fontGeneration)+ drawTextDecorations(r.ck, canvas, rects, r.fillPaint)+ }return true}diff --git a/packages/core/src/canvas/text/index.ts b/packages/core/src/canvas/text/index.tsindex 0525d9a92..ab85baf52 100644--- a/packages/core/src/canvas/text/index.ts+++ b/packages/core/src/canvas/text/index.ts@@ -12,6 +12,7 @@ import {missingGlyphsByScript} from '#core/text/resolver'+import { drawTextLayout } from './decorations'import { buildParagraph } from './layout/build'import { resolveParagraphLayoutWidth } from './paragraph'import { withPreparedText } from './preparation'@@ -20,12 +21,7 @@ import type { FontReadinessRenderer, TextRenderer } from './renderer'export { buildParagraph } from './layout/build'export type { TextLayout } from './layout'export type { ParagraphBuildOptions } from './paint'-export {- textDecorationStyleValue,- textFontFeatures,- textFontVariations,- textHeightBehaviorValue-} from './paragraph'+export { textFontFeatures, textFontVariations, textHeightBehaviorValue } from './paragraph'export { withTextParagraph } from './preparation'function demandFace(@@ -236,9 +232,11 @@ export function buildTextPicture(r: TextRenderer, node: SceneNode): Uint8Array |const recCanvas = recorder.beginRecording(bounds)const layout = buildParagraph(r, node)+ const paint = new ck.Paint()try {- layout.draw(recCanvas, 0, 0)+ drawTextLayout(ck, recCanvas, node, { paragraph: layout }, 0, paint)} finally {+ paint.delete()layout.delete()}diff --git a/packages/core/src/canvas/text/ink.ts b/packages/core/src/canvas/text/ink.tsnew file mode 100644index 000000000..39cc1694a--- /dev/null+++ b/packages/core/src/canvas/text/ink.ts@@ -0,0 +1,146 @@+import { geometryCommandCoordCount } from '@open-pencil/scene-graph'++import type { OutlineCommand } from '#core/text/opentype'++/** Straight pieces a curve is followed in: a fraction of a pixel off at display sizes. */+const CURVE_STEPS = 24++/** Where a glyph's ink crosses a horizontal band: its leftmost and rightmost x there. */+export type InkSpan = [number, number]++/** Collects the x where outline edges run through the band `[top, bottom]`. */+class BandInk {+ private left = Infinity+ private right = -Infinity+ private x = 0+ private y = 0++ constructor(+ private readonly top: number,+ private readonly bottom: number+ ) {}++ moveTo(x: number, y: number): void {+ this.x = x+ this.y = y+ }++ lineTo(x: number, y: number): void {+ const { x: x0, y: y0, top, bottom } = this+ if (y0 >= top && y0 <= bottom) this.include(x0)+ if (y >= top && y <= bottom) this.include(x)+ for (const edge of [top, bottom]) {+ if ((y0 - edge) * (y - edge) < 0) this.include(x0 + ((edge - y0) / (y - y0)) * (x - x0))+ }+ this.x = x+ this.y = y+ }++ quadTo(x1: number, y1: number, x: number, y: number): void {+ const { x: x0, y: y0 } = this+ for (let step = 1; step <= CURVE_STEPS; step++) {+ const t = step / CURVE_STEPS+ const u = 1 - t+ this.lineTo(u * u * x0 + 2 * u * t * x1 + t * t * x, u * u * y0 + 2 * u * t * y1 + t * t * y)+ }+ }++ cubicTo(x1: number, y1: number, x2: number, y2: number, x: number, y: number): void {+ const { x: x0, y: y0 } = this+ for (let step = 1; step <= CURVE_STEPS; step++) {+ const t = step / CURVE_STEPS+ const u = 1 - t+ const a = u * u * u+ const b = 3 * u * u * t+ const c = 3 * u * t * t+ const d = t * t * t+ this.lineTo(a * x0 + b * x1 + c * x2 + d * x, a * y0 + b * y1 + c * y2 + d * y)+ }+ }++ span(): InkSpan | null {+ return this.left <= this.right ? [this.left, this.right] : null+ }++ private include(x: number): void {+ this.left = Math.min(this.left, x)+ this.right = Math.max(this.right, x)+ }+}++/**+ * The ink of a font outline in the band, given in pixels below the baseline as opentype.js+ * draws it, for a glyph at `x`, `y`.+ */+export function outlineInk(+ commands: readonly OutlineCommand[],+ x: number,+ y: number,+ top: number,+ bottom: number+): InkSpan | null {+ const ink = new BandInk(top, bottom)+ let startX = 0+ let startY = 0+ for (const command of commands) {+ const px = x + (command.x ?? 0)+ const py = y + (command.y ?? 0)+ if (command.type === 'M') {+ ink.moveTo(px, py)+ startX = px+ startY = py+ } else if (command.type === 'L') ink.lineTo(px, py)+ else if (command.type === 'Q') ink.quadTo(x + (command.x1 ?? 0), y + (command.y1 ?? 0), px, py)+ else if (command.type === 'C') {+ ink.cubicTo(+ x + (command.x1 ?? 0),+ y + (command.y1 ?? 0),+ x + (command.x2 ?? 0),+ y + (command.y2 ?? 0),+ px,+ py+ )+ } else if (command.type === 'Z') ink.lineTo(startX, startY)+ }+ return ink.span()+}++/**+ * The ink of a saved glyph in the band: its outline is in ems with y up, drawn at `size` and+ * stretched by `scaleX` and `scaleY`.+ */+export function savedGlyphInk(+ blob: Uint8Array,+ glyph: { x: number; y: number; fontSize: number; scaleX?: number; scaleY?: number },+ top: number,+ bottom: number+): InkSpan | null {+ const ink = new BandInk(top, bottom)+ const view = new DataView(blob.buffer, blob.byteOffset, blob.byteLength)+ const sx = glyph.fontSize * (glyph.scaleX ?? 1)+ const sy = glyph.fontSize * (glyph.scaleY ?? 1)+ const points: number[] = []+ let startX = 0+ let startY = 0+ let offset = 0+ while (offset < blob.length) {+ const command = blob[offset++]+ const count = geometryCommandCoordCount(command)+ if (count === null || offset + count * 8 > blob.length) break+ points.length = 0+ for (let index = 0; index < count; index++) {+ points.push(glyph.x + view.getFloat32(offset, true) * sx)+ points.push(glyph.y - view.getFloat32(offset + 4, true) * sy)+ offset += 8+ }+ if (command === 0) ink.lineTo(startX, startY)+ else if (command === 1) {+ ink.moveTo(points[0], points[1])+ startX = points[0]+ startY = points[1]+ } else if (command === 2) ink.lineTo(points[0], points[1])+ else if (command === 3) ink.quadTo(points[0], points[1], points[2], points[3])+ else ink.cubicTo(points[0], points[1], points[2], points[3], points[4], points[5])+ }+ return ink.span()+}diff --git a/packages/core/src/canvas/text/outlines.ts b/packages/core/src/canvas/text/outlines.tsindex 601c55931..72829a6f0 100644--- a/packages/core/src/canvas/text/outlines.ts+++ b/packages/core/src/canvas/text/outlines.ts@@ -55,7 +55,7 @@ function appendOutlineCommand(*/function shapedOutlines(r: SkiaRenderer, node: SceneNode): TextOutlineGlyph[] | null {if (!r.fontProvider || !getTextOutlineSupport(node).supported) return null- const shaped = shapeText(r.ck, r.fontProvider, node, { decorations: false })+ const shaped = shapeText(r.ck, r.fontProvider, node)if (!shaped) return nullconst outlines: TextOutlineGlyph[] = []for (const glyph of shaped.glyphs) {diff --git a/packages/core/src/canvas/text/paragraph/index.ts b/packages/core/src/canvas/text/paragraph/index.tsindex cfa15bff9..2d0c9b70e 100644--- a/packages/core/src/canvas/text/paragraph/index.ts+++ b/packages/core/src/canvas/text/paragraph/index.ts@@ -89,31 +89,6 @@ export function textFontFeatures(}))}-function textDecorationValue(ck: CanvasKit, decoration: string): number {- switch (decoration) {- case 'UNDERLINE':- return ck.UnderlineDecoration- case 'STRIKETHROUGH':- return ck.LineThroughDecoration- default:- return ck.NoDecoration- }-}--export function textDecorationStyleValue<T>(- ck: { DecorationStyle: { Solid: T; Dotted: T; Wavy: T } },- style: SceneNode['textDecorationStyle'] | undefined-): T {- switch (style) {- case 'DOTTED':- return ck.DecorationStyle.Dotted- case 'WAVY':- return ck.DecorationStyle.Wavy- default:- return ck.DecorationStyle.Solid- }-}-export function textHeightBehaviorValue<T>(ck: { TextHeightBehavior: { DisableAll: T } },leadingTrim: SceneNode['leadingTrim']@@ -141,17 +116,6 @@ function blockHeightBehavior(return ck.TextHeightBehavior.All}-function textDecorationColor(- ck: CanvasKit,- fills: SceneNode['textDecorationFills'] | undefined,- fallback: Float32Array-): Float32Array {- const fill = fills?.find((item) => item.visible && item.type === 'SOLID')- if (!fill) return fallback- const color = resolveRGBAForPreview(fill.color).color- return ck.Color4f(color.r, color.g, color.b, color.a * fill.opacity)-}-function styleRunColor(ck: CanvasKit,style: SceneNode['styleRuns'][number]['style'],@@ -204,17 +168,6 @@ function pushStyleRun(),fontFeatures: textFontFeatures(style.fontFeatures ?? node.fontFeatures),letterSpacing: style.letterSpacing ?? (node.letterSpacing || 0),- decoration: textDecorationValue(ck, style.textDecoration ?? node.textDecoration),- decorationStyle: textDecorationStyleValue(- ck,- style.textDecorationStyle ?? node.textDecorationStyle- ),- decorationThickness: style.textDecorationThickness ?? node.textDecorationThickness ?? undefined,- decorationColor: textDecorationColor(- ck,- style.textDecorationFills ?? node.textDecorationFills,- baseColor- ),heightMultiplier: runLineHeight ? runLineHeight / runFontSize : undefined,halfLeading})@@ -327,10 +280,6 @@ export function buildSkParagraph(),fontFeatures: textFontFeatures(node.fontFeatures),letterSpacing: node.letterSpacing || 0,- decoration: textDecorationValue(ck, node.textDecoration),- decorationStyle: textDecorationStyleValue(ck, node.textDecorationStyle),- decorationThickness: node.textDecorationThickness ?? undefined,- decorationColor: textDecorationColor(ck, node.textDecorationFills, baseColor),heightMultiplier: node.lineHeight ? node.lineHeight / baseFontSize : undefined,halfLeading}diff --git a/packages/core/src/canvas/text/paragraph/inputs.ts b/packages/core/src/canvas/text/paragraph/inputs.tsindex d24154672..32677855b 100644--- a/packages/core/src/canvas/text/paragraph/inputs.ts+++ b/packages/core/src/canvas/text/paragraph/inputs.ts@@ -1,6 +1,9 @@import type { SceneNode } from '@open-pencil/scene-graph'-/** Paragraph construction is typed against this list, which also drives cache invalidation. */+/**+ * Paragraph construction is typed against this list, which also drives cache invalidation; the+ * decoration fields keep the decorations a prepared text holds current with it.+ */export const PARAGRAPH_INPUT_KEYS = ['text','fontFamily',@@ -21,6 +24,8 @@ export const PARAGRAPH_INPUT_KEYS = ['textDecorationStyle','textDecorationThickness','textDecorationFills',+ 'textDecorationSkipInk',+ 'textUnderlineOffset','textTruncation','maxLines','textParagraphs',diff --git a/packages/core/src/canvas/text/placed.ts b/packages/core/src/canvas/text/placed.tsnew file mode 100644index 000000000..54519887a--- /dev/null+++ b/packages/core/src/canvas/text/placed.ts@@ -0,0 +1,126 @@+import type { Paragraph } from 'canvaskit-wasm'++import type { SceneNode } from '@open-pencil/scene-graph'++import type { TextLayout, TextLayoutMarker } from '#core/canvas/text/layout'+import { utf16IndicesByUtf8 } from '#core/canvas/text/utf8'+import { weightToStyle } from '#core/text/fonts'+import { glyphOutlineSourceSync, type GlyphOutlineSource } from '#core/text/opentype'++type GlyphRun = ReturnType<Paragraph['getShapedLines']>[number]['runs'][number]++/** A glyph of laid-out text where the renderer draws it, with the font its outline comes from. */+export interface LaidOutGlyph {+ /** The glyph ID the shaper chose. */+ id: number+ x: number+ /** The baseline of its line. */+ y: number+ fontSize: number+ /** The character it draws, left out for a list marker. */+ firstCharacter?: number+ advance: number+ /** Where its line starts. */+ lineLeft: number+ /** The font that drew it, or `null` when the shaper may have used another. */+ source: GlyphOutlineSource | null+}++function fontStyleAt(node: SceneNode, index: number): { family: string; style: string } {+ 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)+ }+}++/**+ * 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.+ */+function runOutlineSource(+ node: SceneNode,+ text: string,+ run: GlyphRun,+ characterAt: (offset: number) => number+): GlyphOutlineSource | null {+ if (run.fakeBold || run.fakeItalic || run.glyphs.length === 0) return null+ 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+}++/**+ * A list marker's glyphs as Figma saves them: placed beside their item and drawing no+ * character of the text.+ */+function markerGlyphs(marker: TextLayoutMarker, offsetY: number): LaidOutGlyph[] {+ const source = glyphOutlineSourceSync(marker.face.family, marker.face.style)+ const baseline = marker.paragraph.getLineMetrics().at(0)?.baseline ?? 0+ const glyphs: LaidOutGlyph[] = []+ for (const line of marker.paragraph.getShapedLines()) {+ for (const run of line.runs) {+ const trusted = !run.fakeBold && !run.fakeItalic+ for (let index = 0; index < run.glyphs.length; index++) {+ const x = run.positions[index * 2]+ glyphs.push({+ id: run.glyphs[index],+ x: marker.x + x,+ y: marker.y + baseline + offsetY,+ fontSize: run.size,+ advance: run.positions[(index + 1) * 2] - x,+ lineLeft: marker.x,+ source: trusted ? source : null+ })+ }+ }+ }+ return glyphs+}++/**+ * Every glyph of laid-out `text`, `offsetY` below the layout's top, in drawing order: an item's+ * marker before the glyphs of its first line, as Figma saves them. Returns `null` when the+ * layout's lines do not match its shaped lines.+ */+export function laidOutGlyphs(+ node: SceneNode,+ layout: TextLayout,+ text: string,+ offsetY: number+): LaidOutGlyph[] | null {+ const lines = layout.getShapedLines()+ const metrics = layout.getLineMetrics()+ if (lines.length === 0 || lines.length !== metrics.length) return null+ const characterAt = utf16IndicesByUtf8(text)+ const markers = new Map(layout.getMarkers().map((marker) => [marker.lineNumber, marker]))+ const glyphs: LaidOutGlyph[] = []+ for (const [lineIndex, line] of lines.entries()) {+ 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)+ for (let index = 0; index < run.glyphs.length; index++) {+ const x = run.positions[index * 2]+ glyphs.push({+ id: run.glyphs[index],+ x,+ // Run positions round the baseline to whole pixels; line metrics keep it exact.+ y: baseline + offsetY,+ fontSize: run.size,+ firstCharacter: characterAt(run.offsets[index]),+ advance: run.positions[(index + 1) * 2] - x,+ lineLeft: left,+ source+ })+ }+ }+ }+ return glyphs+}diff --git a/packages/core/src/canvas/text/preparation/cache.ts b/packages/core/src/canvas/text/preparation/cache.tsindex 43605f50a..41c5fc241 100644--- a/packages/core/src/canvas/text/preparation/cache.ts+++ b/packages/core/src/canvas/text/preparation/cache.ts@@ -13,6 +13,7 @@ const MAX_PREPARED_TEXT_UNITS = 262_144// Layout measures a text at a few widths; more than this means the widths are not repeating.const MAX_MEASURED_WIDTHS = 16+import type { TextDecorationRect } from '#core/canvas/text/decorations'import type { TextLayout } from '#core/canvas/text/layout'import { PARAGRAPH_INPUT_KEYS, shapingInputs } from '#core/canvas/text/paragraph/inputs'@@ -21,6 +22,8 @@ type PreparationInput = SceneNode[(typeof PARAGRAPH_INPUT_KEYS)[number]]export interface PreparedText {paragraph: TextLayoutmissingGlyphs?: ReturnType<typeof missingGlyphOccurrences>+ /** The underlines and strikethroughs drawn `y` below the text's top, found once per layout. */+ decorations?: { y: number; rects: TextDecorationRect[] }}/** What shaping a node's text showed, valid while its `shapingInputs` stay the same. */diff --git a/packages/core/src/canvas/text/preparation/index.ts b/packages/core/src/canvas/text/preparation/index.tsindex 1c88c2b15..614ea9a83 100644--- a/packages/core/src/canvas/text/preparation/index.ts+++ b/packages/core/src/canvas/text/preparation/index.ts@@ -51,14 +51,14 @@ export function withTextParagraph<T>(node: SceneNode,color: Float32Array,options: ParagraphBuildOptions,- draw: (paragraph: TextLayout) => T+ draw: (paragraph: TextLayout, prepared: PreparedText) => T): T {return withPreparedText(r,node,`draw:${Boolean(options.halfLeading)}:${color.join(',')}`,() => r.buildParagraph(node, color, options),- (prepared) => draw(prepared.paragraph),+ (prepared) => draw(prepared.paragraph, prepared),!options.foregroundPaint)}diff --git a/packages/core/src/canvas/text/shape.ts b/packages/core/src/canvas/text/shape.tsindex 6e643005d..a5ad1a8b0 100644--- a/packages/core/src/canvas/text/shape.ts+++ b/packages/core/src/canvas/text/shape.ts@@ -1,58 +1,22 @@-import type { CanvasKit, Paragraph, TypefaceFontProvider } from 'canvaskit-wasm'+import type { CanvasKit, TypefaceFontProvider } from 'canvaskit-wasm'import {EMPTY_EXPORT_RUNTIME,type FigNodeChangeExportRuntime,+ type PlacedTextGlyph,type ShapedText,- type ShapedTextGlyph+ type ShapedTextGlyph,+ type TextDecorationRecord} from '@open-pencil/fig/node-change'import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'import { buildParagraph, textVerticalOffset } from '#core/canvas/text'-import type { TextLayoutMarker } from '#core/canvas/text/layout'-import { utf16IndicesByUtf8 } from '#core/canvas/text/utf8'+import { textDecorationRects, type DecoratedGlyph } from '#core/canvas/text/decorations'+import { outlineInk, savedGlyphInk } from '#core/canvas/text/ink'+import { laidOutGlyphs } from '#core/canvas/text/placed'import { getCanvasKit } from '#core/canvaskit'import { transformTextCase } from '#core/text/case'-import { fontManager, weightToStyle } from '#core/text/fonts'-import { glyphOutlineSourceSync, type GlyphOutlineSource } from '#core/text/opentype'--type GlyphRun = ReturnType<Paragraph['getShapedLines']>[number]['runs'][number]--function fontStyleAt(node: SceneNode, index: number): { family: string; style: string } {- 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)- }-}--/**- * 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.- */-function runOutlineSource(- node: SceneNode,- text: string,- run: GlyphRun,- characterAt: (offset: number) => number-): GlyphOutlineSource | null {- if (run.fakeBold || run.fakeItalic || run.glyphs.length === 0) return null- 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-}--function hasDecoration(node: SceneNode): boolean {- return (- node.textDecoration !== 'NONE' ||- node.styleRuns.some((run) => run.style.textDecoration && run.style.textDecoration !== 'NONE')- )-}+import { fontManager } from '#core/text/fonts'/*** Whether saved glyphs could stand for this text: truncation and case changes that alter its@@ -67,59 +31,6 @@ function canShape(node: SceneNode, text: string): boolean {)}-function shapedRunGlyphs(- run: GlyphRun,- source: GlyphOutlineSource | null,- line: { left: number; baseline: number },- characterOffsets: Array<number | undefined>,- characterAt: (offset: number) => number-): ShapedTextGlyph[] {- const glyphs: ShapedTextGlyph[] = []- for (let index = 0; index < run.glyphs.length; index++) {- const commands = source?.outline(run.glyphs[index], run.size) ?? null- const x = run.positions[index * 2]- const nextX = run.positions[(index + 1) * 2]- const firstCharacter = characterAt(run.offsets[index])- glyphs.push({- commands,- x,- // Run positions round the baseline to whole pixels; line metrics keep it exact.- y: line.baseline,- fontSize: run.size,- firstCharacter,- advance: nextX - x- })- characterOffsets[firstCharacter] ??= x - line.left- }- return glyphs-}--/**- * A list marker's glyphs as Figma saves them: placed beside their item and drawing no- * character of the text.- */-function markerGlyphs(marker: TextLayoutMarker, offsetY: number): ShapedTextGlyph[] {- const source = glyphOutlineSourceSync(marker.face.family, marker.face.style)- const baseline = marker.paragraph.getLineMetrics().at(0)?.baseline ?? 0- const glyphs: ShapedTextGlyph[] = []- for (const line of marker.paragraph.getShapedLines()) {- for (const run of line.runs) {- const trusted = !run.fakeBold && !run.fakeItalic- for (let index = 0; index < run.glyphs.length; index++) {- const x = run.positions[index * 2]- glyphs.push({- commands: trusted ? (source?.outline(run.glyphs[index], run.size) ?? null) : null,- x: marker.x + x,- y: marker.y + baseline + offsetY,- fontSize: run.size,- advance: run.positions[(index + 1) * 2] - x- })- }- }- }- return glyphs-}-/** Characters inside a glyph cluster or without a glyph take the offset of the one before. */function completeCharacterOffsets(offsets: Array<number | undefined>): number[] {let previous = 0@@ -132,16 +43,14 @@ function completeCharacterOffsets(offsets: Array<number | undefined>): number[]/*** Lay a text node out as the renderer draws it and pair each shaped glyph with the outline of* the glyph ID CanvasKit chose, so ligatures and contextual forms keep their shapes. When a run's- * font is missing, variable, or a fallback, or the glyphs could not draw the text's decorations,- * no glyph gets an outline: the layout still stands, and readers draw the text themselves.- * Outlines that carry no decorations, as outlined text has none, set `decorations: false`.+ * font is missing, variable, or a fallback, no glyph gets an outline: the layout still stands,+ * and readers draw the text themselves.* Returns `null` for text saved glyphs cannot represent at all.*/export function shapeText(ck: CanvasKit,fontProvider: TypefaceFontProvider,- node: SceneNode,- { decorations = true }: { decorations?: boolean } = {}+ node: SceneNode): ShapedText | null {const text = transformTextCase(node.text, node.textCase)if (!canShape(node, text)) return null@@ -150,36 +59,26 @@ export function shapeText(halfLeading: true})try {- const lines = paragraph.getShapedLines()- const metrics = paragraph.getLineMetrics()- if (lines.length === 0 || lines.length !== metrics.length) return null-const offsetY = textVerticalOffset(node, paragraph.getHeight())- const characterAt = utf16IndicesByUtf8(text)- const markers = new Map(paragraph.getMarkers().map((marker) => [marker.lineNumber, marker]))- const glyphs: ShapedTextGlyph[] = []+ const placed = laidOutGlyphs(node, paragraph, text, offsetY)+ if (!placed) return null+ const metrics = paragraph.getLineMetrics()const characterOffsets: Array<number | undefined> = Array.from({ length: text.length })- for (const [lineIndex, line] of lines.entries()) {- // Figma saves an item's marker before the glyphs of its first line.- const marker = markers.get(lineIndex)- if (marker) glyphs.push(...markerGlyphs(marker, offsetY))- for (const run of line.runs) {- glyphs.push(- ...shapedRunGlyphs(- run,- runOutlineSource(node, text, run, characterAt),- { left: metrics[lineIndex].left, baseline: metrics[lineIndex].baseline + offsetY },- characterOffsets,- characterAt- )- )+ const glyphs: ShapedTextGlyph[] = placed.map((glyph) => {+ if (glyph.firstCharacter !== undefined) {+ characterOffsets[glyph.firstCharacter] ??= glyph.x - glyph.lineLeft}- }- // Outlines from some runs only would draw the text with characters missing, and saved- // glyphs draw decorations on one baseline.- const outlined =- glyphs.every((glyph) => glyph.commands) &&- !(decorations && lines.length > 1 && hasDecoration(node))+ return {+ commands: glyph.source?.outline(glyph.id, glyph.fontSize) ?? null,+ x: glyph.x,+ y: glyph.y,+ fontSize: glyph.fontSize,+ firstCharacter: glyph.firstCharacter,+ advance: glyph.advance+ }+ })+ // Outlines from some runs only would draw the text with characters missing.+ const outlined = glyphs.every((glyph) => glyph.commands)return {glyphs: outlined ? glyphs : glyphs.map((glyph) => ({ ...glyph, commands: null })),baselines: metrics.map((line) => ({@@ -198,6 +97,27 @@ export function shapeText(}}+function decoratedGlyph(glyph: PlacedTextGlyph): DecoratedGlyph {+ const { commandsBlob, commands } = glyph+ return {+ ...glyph,+ ink: (top, bottom) => {+ if (commandsBlob) return savedGlyphInk(commandsBlob, glyph, top, bottom)+ return commands ? outlineInk(commands, glyph.x, glyph.y, top, bottom) : null+ }+ }+}++/** Decorations as Figma saves them, over glyphs saved or just shaped. */+function textDecorations(+ node: SceneNode,+ glyphs: readonly PlacedTextGlyph[]+): TextDecorationRecord[] {+ return textDecorationRects(node, glyphs.map(decoratedGlyph)).map(+ ({ firstCharacter, x, y, width, height }) => ({ firstCharacter, x, y, width, height })+ )+}+function needsShaping(graph: SceneGraph): boolean {for (const node of graph.nodes.values()) {if (node.type === 'TEXT' && node.text && !node.derivedTextGlyphs?.length) return true@@ -214,13 +134,16 @@ export async function withFigExportRuntime<T>(ck: CanvasKit | undefined,write: (runtime: FigNodeChangeExportRuntime) => Promise<T>): Promise<T> {- if (!needsShaping(graph)) return write(EMPTY_EXPORT_RUNTIME)+ if (!needsShaping(graph)) return write({ ...EMPTY_EXPORT_RUNTIME, textDecorations })const canvasKit = ck ?? (await getCanvasKit())const reusable = fontManager.providerFor(canvasKit)const provider = reusable ?? canvasKit.TypefaceFontProvider.Make()if (!reusable) fontManager.attachProvider(canvasKit, provider)try {- return await write({ shapeText: (node) => shapeText(canvasKit, provider, node) })+ return await write({+ shapeText: (node) => shapeText(canvasKit, provider, node),+ textDecorations+ })} finally {if (!reusable) {fontManager.detachProvider(provider)diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.tsindex f0760ee1d..d4f091299 100644--- a/packages/core/src/editor/create.ts+++ b/packages/core/src/editor/create.ts@@ -2,7 +2,7 @@ import type { CanvasKit } from 'canvaskit-wasm'import { createNanoEvents } from 'nanoevents'import type { Emitter } from 'nanoevents'-import { SceneGraph } from '@open-pencil/scene-graph'+import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'import { UndoManager } from '@open-pencil/scene-graph/undo'import type { SkiaRenderer } from '#core/canvas/renderer'@@ -50,6 +50,7 @@ import { createDefaultEditorState } from './state'import { createStructureActions } from './structure'import { createTextActions } from './text'import { createPendingTextLayout } from './text/pending-layout'+import { createTextSelectionStyle } from './text/selection-style'import type {EditorContext,EditorEventName,@@ -285,6 +286,7 @@ export function createEditor(options?: EditorOptions) {const structureBridge = createStructureBridge(structure, selection)const undoBridge = createUndoBridge(undoActions, selection, nodes.flushNudge)const lintFixBridge = createLintFixBridge(ctx, nodes, structure, clipboard)+ const textSelectionStyle = createTextSelectionStyle(ctx, text.runTextEditStep)// The edited text follows changes made outside the editor, such as a panel field being// dragged, so its caret and selection move with the text instead of after the change.@@ -414,8 +416,15 @@ export function createEditor(options?: EditorOptions) {// Structure (group, reorder, reparent, z-order)...structure,- // Nodes (update, layout)+ // Nodes (update, layout); while text is edited, character styles go to its selection...nodes,+ updateNode: (id: string, changes: Partial<SceneNode>) =>+ textSelectionStyle.updateNode(id, changes, nodes.updateNode),+ updateNodeWithUndo: (id: string, changes: Partial<SceneNode>, label = 'Update') =>+ textSelectionStyle.updateNodeWithUndo(id, changes, (target, next) =>+ nodes.updateNodeWithUndo(target, next, label)+ ),+ getTextSelectionStyle: textSelectionStyle.selectionStyle,// Alignment (align, flip, rotate)...alignment,@@ -441,6 +450,13 @@ export function createEditor(options?: EditorOptions) {// Undo — bridge functions that need cross-module refs...undoBridge,+ commitNodeUpdate: (id: string, previous: Partial<SceneNode>, label = 'Update') =>+ textSelectionStyle.commitNodeUpdate(+ id,+ previous,+ (target, values) => undoBridge.commitNodeUpdate(target, values, label),+ (target, next) => nodes.updateNodeWithUndo(target, next, label)+ ),// While text is edited, what was typed undoes first and the editor keeps the result.undoAction: () => text.runTextEditStep(undoBridge.undoAction),redoAction: () => text.runTextEditStep(undoBridge.redoAction),diff --git a/packages/core/src/editor/text/selection-style.ts b/packages/core/src/editor/text/selection-style.tsnew file mode 100644index 000000000..da77c7be6--- /dev/null+++ b/packages/core/src/editor/text/selection-style.ts@@ -0,0 +1,122 @@+import { omit, pick } from 'es-toolkit/object'+import { isEqual } from 'es-toolkit/predicate'++import type { CharacterStyleOverride, SceneNode, StyleRun } from '@open-pencil/scene-graph'++import type { EditorContext } from '#core/editor/types'+import {+ characterStyles,+ styleRunsWithPatch,+ TEXT_STYLE_KEYS,+ type TextStyleKey+} from '#core/text/character-style'++type NodeUpdate = (id: string, changes: Partial<SceneNode>) => void++function styleKeys(changes: Partial<SceneNode>): TextStyleKey[] {+ return TEXT_STYLE_KEYS.filter((key) => Object.hasOwn(changes, key))+}++/**+ * While text is edited with characters selected, a property its characters can each have, such+ * as a fill or font size, styles the selected characters instead of the layer, as in Figma. A+ * change that applies a text style still applies to the layer.+ */+export function createTextSelectionStyle(+ ctx: EditorContext,+ runTextEditStep: (change: () => void) => void+) {+ /**+ * The style runs a previewed change started from, which its commit records as undone to, and+ * the runs it last left; anything else changing them since ends the preview.+ */+ let preview: { nodeId: string; start: StyleRun[]; shown: StyleRun[] } | null = null++ function previewOf(id: string) {+ const node = ctx.graph.getNode(id)+ // Graph values are replaced rather than written into, so the runs it left are still its own.+ return preview?.nodeId === id && node?.styleRuns === preview.shown ? preview : null+ }++ function selectedRange(id: string): [number, number] | null {+ if (ctx.state.editingTextId !== id) return null+ return ctx.getTextEditor()?.getSelectionRange() ?? null+ }++ function rangeChanges(id: string, changes: Partial<SceneNode>): Partial<SceneNode> | null {+ const range = selectedRange(id)+ const node = ctx.graph.getNode(id)+ const keys = styleKeys(changes)+ if (!range || !node || keys.length === 0 || Object.hasOwn(changes, 'textStyleId')) return null+ const patch = pick(changes, keys) as CharacterStyleOverride+ return { ...omit(changes, keys), styleRuns: styleRunsWithPatch(node, ...range, patch) }+ }++ /** A change shown before it is committed, such as a dragged field. */+ function updateNode(id: string, changes: Partial<SceneNode>, update: NodeUpdate) {+ const ranged = rangeChanges(id, changes)+ if (!ranged) {+ update(id, changes)+ return+ }+ const current = previewOf(id)+ let start = current?.start ?? []+ // What was typed becomes a step of its own before the preview starts.+ if (!current) {+ runTextEditStep(() => {+ start = structuredClone(ctx.graph.getNode(id)?.styleRuns ?? [])+ })+ }+ update(id, ranged)+ preview = { nodeId: id, start, shown: ctx.graph.getNode(id)?.styleRuns ?? [] }+ }++ function updateNodeWithUndo(id: string, changes: Partial<SceneNode>, update: NodeUpdate) {+ const ranged = rangeChanges(id, changes)+ if (!ranged) {+ update(id, changes)+ return+ }+ preview = null+ runTextEditStep(() => update(id, ranged))+ }++ /**+ * Records a previewed change, given the values it replaced. The selected characters had+ * styles of their own, so the step undoes to the runs the preview started from.+ */+ function commitNodeUpdate(+ id: string,+ previous: Partial<SceneNode>,+ commit: NodeUpdate,+ updateWithUndo: NodeUpdate+ ) {+ const current = previewOf(id)+ const keys = styleKeys(previous)+ preview = null+ if (!current || keys.length === 0) {+ commit(id, previous)+ return+ }+ const previewed = current.shown+ // Back to where the preview started, so the edit session records nothing of its own.+ ctx.graph.updateNode(id, { styleRuns: current.start })+ runTextEditStep(() => {+ if (!isEqual(previewed, current.start)) updateWithUndo(id, { styleRuns: previewed })+ commit(id, omit(previous, keys))+ })+ }++ /**+ * The style of the selected characters as the layer's own properties, for the panel to show;+ * characters styled differently show the first one's.+ */+ function selectionStyle(node: SceneNode): Partial<SceneNode> | null {+ const range = selectedRange(node.id)+ if (!range) return null+ const [style] = characterStyles(node, range[0], range[0] + 1)+ return { ...style }+ }++ return { updateNode, updateNodeWithUndo, commitNodeUpdate, selectionStyle }+}diff --git a/packages/core/src/figma-api/accessors/text.ts b/packages/core/src/figma-api/accessors/text/index.tssimilarity index 52%rename from packages/core/src/figma-api/accessors/text.tsrename to packages/core/src/figma-api/accessors/text/index.tsindex fea1dbef1..1e085739e 100644--- a/packages/core/src/figma-api/accessors/text.ts+++ b/packages/core/src/figma-api/accessors/text/index.ts@@ -1,30 +1,27 @@-import type { SceneGraph, SceneNode, TextParagraphSpacingField } from '@open-pencil/scene-graph'+import type {+ CharacterStyleOverride,+ SceneNode,+ TextParagraphSpacingField+} from '@open-pencil/scene-graph'import {- nodeId,raw,updateNode,type NodeProxyInternals,type ProxyThis} from '#core/figma-api/accessor-utils'-import type { FigmaFontName } from '#core/figma-api/fonts'+import { styleNameToWeight, type FigmaFontName } from '#core/figma-api/fonts'import {- getFontName,- getLetterSpacing,- getLineHeight,getParagraphSpacing,letterSpacingValue,lineHeightValue,paragraphStylesForCharacters,- setFontName,spacingProblem,type FigmaLetterSpacing,type FigmaLineHeight} from '#core/figma-api/text'--function graph(target: ProxyThis, internals: NodeProxyInternals): SceneGraph {- return target[internals.graph] as SceneGraph-}+import { getTextStyle, type TextSegmentField } from '#core/figma-api/text/style'+import { textStyleChanges } from '#core/text/character-style'/*** Getter/setter pair for a spacing Figma keeps at zero or more. It reads `mixed` while paragraphs@@ -45,6 +42,35 @@ function spacing(internals: NodeProxyInternals, name: TextParagraphSpacingField,}}+/**+ * Getter/setter pair for a style characters can override: it reads `mixed` while they differ,+ * and setting it gives every character the value, as Figma's node setters do.+ */+function characterStyle<T>(+ internals: NodeProxyInternals,+ field: TextSegmentField,+ mixed: symbol,+ changes: (node: SceneNode, value: T) => Partial<SceneNode>,+ sized?: (value: T) => ((fontSize: number) => CharacterStyleOverride) | undefined+) {+ return {+ get(this: ProxyThis): unknown {+ return getTextStyle(raw(this, internals), field, mixed)+ },+ set(this: ProxyThis, value: T) {+ const node = raw(this, internals)+ updateNode(this, internals, textStyleChanges(node, changes(node, value), sized?.(value)))+ }+ }+}++/** A length given in percent of the font size, which characters of each size resolve. */+function percentOf(value: unknown): number | null {+ if (!value || typeof value !== 'object') return null+ const length = value as { unit?: unknown; value?: unknown }+ return length.unit === 'PERCENT' && typeof length.value === 'number' ? length.value / 100 : null+}+/** Getter/setter pair for a text property stored verbatim on the node. */function field<Field extends keyof SceneNode>(internals: NodeProxyInternals, name: Field) {return {@@ -72,15 +98,13 @@ export function installTextNodeProxyAccessors(updateNode(this, internals, { text: value, textParagraphs })}},- fontName: {- get(this: ProxyThis): FigmaFontName {- return getFontName(raw(this, internals))- },- set(this: ProxyThis, value: FigmaFontName) {- setFontName(graph(this, internals), nodeId(this, internals), value)- }- },- fontSize: field(internals, 'fontSize'),+ fontName: characterStyle<FigmaFontName>(internals, 'fontName', mixed, (_node, value) => {+ const { weight, italic } = styleNameToWeight(value.style)+ return { fontFamily: value.family, fontWeight: weight, italic }+ }),+ fontSize: characterStyle<number>(internals, 'fontSize', mixed, (_node, fontSize) => ({+ fontSize+ })),textStyleId: {get(this: ProxyThis): string {return raw(this, internals).textStyleId ?? ''@@ -89,33 +113,42 @@ export function installTextNodeProxyAccessors(updateNode(this, internals, { textStyleId: value || null })}},- fontWeight: field(internals, 'fontWeight'),+ fontWeight: characterStyle<number>(internals, 'fontWeight', mixed, (_node, fontWeight) => ({+ fontWeight+ })),textAlignHorizontal: field(internals, 'textAlignHorizontal'),textAlignVertical: field(internals, 'textAlignVertical'),textDirection: field(internals, 'textDirection'),textAutoResize: field(internals, 'textAutoResize'),// Figma's plugin API reads and writes these as { unit, value }; a bare object stored on the// node instead of pixels would leave the text unmeasurable.- letterSpacing: {- get(this: ProxyThis): FigmaLetterSpacing {- return getLetterSpacing(raw(this, internals))- },- set(this: ProxyThis, value: FigmaLetterSpacing | number) {- updateNode(this, internals, {- letterSpacing: letterSpacingValue(raw(this, internals), value)- })+ letterSpacing: characterStyle<FigmaLetterSpacing | number>(+ internals,+ 'letterSpacing',+ mixed,+ (node, value) => ({ letterSpacing: letterSpacingValue(node, value) }),+ (value) => {+ const percent = percentOf(value)+ return percent === null ? undefined : (fontSize) => ({ letterSpacing: percent * fontSize })}- },- lineHeight: {- get(this: ProxyThis): FigmaLineHeight {- return getLineHeight(raw(this, internals))- },- set(this: ProxyThis, value: FigmaLineHeight | number | null) {- updateNode(this, internals, { lineHeight: lineHeightValue(raw(this, internals), value) })+ ),+ lineHeight: characterStyle<FigmaLineHeight | number | null>(+ internals,+ 'lineHeight',+ mixed,+ (node, value) => ({ lineHeight: lineHeightValue(node, value) }),+ (value) => {+ const percent = percentOf(value)+ return percent === null ? undefined : (fontSize) => ({ lineHeight: percent * fontSize })}- },+ ),textCase: field(internals, 'textCase'),- textDecoration: field(internals, 'textDecoration'),+ textDecoration: characterStyle<SceneNode['textDecoration']>(+ internals,+ 'textDecoration',+ mixed,+ (_node, textDecoration) => ({ textDecoration })+ ),maxLines: field(internals, 'maxLines'),listSpacing: spacing(internals, 'listSpacing', mixed),paragraphSpacing: spacing(internals, 'paragraphSpacing', mixed),diff --git a/packages/core/src/figma-api/accessors/text/ranges.ts b/packages/core/src/figma-api/accessors/text/ranges.tsnew file mode 100644index 000000000..fc5985792--- /dev/null+++ b/packages/core/src/figma-api/accessors/text/ranges.ts@@ -0,0 +1,466 @@+import { uniqBy } from 'es-toolkit/array'++import type {+ CharacterStyleOverride,+ Fill,+ SceneNode,+ TextDecoration,+ TextDecorationStyle+} from '@open-pencil/scene-graph'++import {+ assertProxyEditable,+ graph,+ raw,+ updateNode,+ type NodeProxyInternals,+ type ProxyThis+} from '#core/figma-api/accessor-utils'+import { figmaPaintToFill, type FigmaPaint } from '#core/figma-api/accessors/visual'+import { styleNameToWeight, type FigmaFontName } from '#core/figma-api/fonts'+import {+ getRangeIndentation,+ getRangeListOptions,+ getRangeParagraphSpacing,+ setRangeIndentation,+ setRangeListOptions,+ setRangeParagraphSpacing,+ type FigmaLetterSpacing+} from '#core/figma-api/text'+import {+ assertTextRange,+ getRangeTextStyle,+ getStyledTextSegments,+ rangeHasUnderline,+ type FigmaDecorationColor,+ type FigmaTextLength,+ type StyledTextSegment,+ type TextSegmentField+} from '#core/figma-api/text/style'+import { styleRunsWithPatch, type TextStylePatch } from '#core/text/character-style'++const DECORATIONS = new Set<TextDecoration>(['NONE', 'UNDERLINE', 'STRIKETHROUGH'])+const DECORATION_STYLES = new Set<TextDecorationStyle>(['SOLID', 'DOTTED', 'WAVY'])+const LENGTH_UNITS = new Set(['PIXELS', 'PERCENT'])+const PAINT_TYPES = new Set([+ 'SOLID',+ 'SHADER',+ 'GRADIENT_LINEAR',+ 'GRADIENT_RADIAL',+ 'GRADIENT_ANGULAR',+ 'GRADIENT_DIAMOND',+ 'IMAGE',+ 'VIDEO'+])+const SOLID_PAINT_KEYS = new Set([+ 'type',+ 'color',+ 'opacity',+ 'visible',+ 'blendMode',+ 'boundVariables'+])++/** Figma's message for a value its schema rejects. */+function invalid(method: string, problem: string, property = 'value'): Error {+ return new Error(`in ${method}: Property "${property}" failed validation: ${problem}`)+}++function received(value: unknown): string {+ if (typeof value === 'number' && Number.isNaN(value)) return 'nan'+ if (Array.isArray(value)) return 'array'+ return value === null ? 'null' : typeof value+}++function numberProblem(value: unknown, at = ''): string | null {+ if (value === undefined) return `Required value missing${at}`+ if (typeof value !== 'number' || Number.isNaN(value)) {+ return `Expected number, received ${received(value)}${at}`+ }+ return null+}++/** A length in pixels for a font size: a percent is of the size of the characters it styles. */+type SizedLength<T> = (fontSize: number) => T++function lengthFor(value: { unit: 'PIXELS' | 'PERCENT'; value: number }): SizedLength<number> {+ return (fontSize) => (value.unit === 'PERCENT' ? (value.value / 100) * fontSize : value.value)+}++/** A letter spacing Figma takes: pixels or percent, never automatic. */+function letterSpacingLength(method: string, value: unknown): SizedLength<number> {+ const length = value as Partial<FigmaTextLength & { value: number }> | null+ if (!length || typeof length !== 'object') {+ throw invalid(method, `Expected object, received ${received(value)}`)+ }+ if (!LENGTH_UNITS.has(String(length.unit))) {+ throw invalid(+ method,+ `Invalid enum value. Expected 'PIXELS' | 'PERCENT', received '${String(length.unit)}' at .unit`+ )+ }+ const problem = numberProblem(length.value, ' at .value')+ if (problem) throw invalid(method, problem)+ return lengthFor(length as { unit: 'PIXELS' | 'PERCENT'; value: number })+}++/** A length that may also be automatic, as line heights and decoration sizes are. */+function lengthOrAuto(method: string, value: unknown): SizedLength<number | null> {+ const length = value as Partial<FigmaTextLength & { value: number }> | null+ if (!length || typeof length !== 'object') {+ throw invalid(method, `Expected object, received ${received(value)}`)+ }+ if (length.unit === 'AUTO') return () => null+ if (!LENGTH_UNITS.has(String(length.unit))) {+ throw invalid(+ method,+ `Invalid discriminator value. Expected 'PIXELS' | 'PERCENT' | 'AUTO' at .unit`+ )+ }+ const problem = numberProblem(length.value, ' at .value')+ if (problem) throw invalid(method, problem)+ return lengthFor(length as { unit: 'PIXELS' | 'PERCENT'; value: number })+}++function stringProblem(value: unknown, at: string): string | null {+ return typeof value === 'string' ? null : `Expected string, received ${received(value)} at ${at}`+}++/** A font name Figma takes: a family and style; a style left out reads as regular. */+function fontNameStyle(method: string, value: unknown): CharacterStyleOverride {+ if (!value || typeof value !== 'object') {+ throw invalid(method, `Expected object, received ${received(value)}`)+ }+ const fontName = value as Partial<Record<keyof FigmaFontName, unknown>>+ const style = fontName.style ?? 'Regular'+ const problem = stringProblem(fontName.family, '.family') ?? stringProblem(style, '.style')+ if (problem) throw invalid(method, problem)+ const { weight, italic } = styleNameToWeight(style as string)+ return { fontFamily: fontName.family as string, fontWeight: weight, italic }+}++/** A number from 0 to 1, as Figma takes colour channels and opacity. */+function unitProblem(value: unknown, at: string): string | null {+ const problem = numberProblem(value, ` at ${at}`)+ if (problem) return problem+ if ((value as number) < 0) return `Number must be greater than or equal to 0 at ${at}`+ if ((value as number) > 1) return `Number must be less than or equal to 1 at ${at}`+ return null+}++/** A solid paint's colour and opacity as Figma checks them; a colour's alpha may be left out. */+function solidPaintProblem(paint: { color?: unknown; opacity?: unknown }, at: string) {+ const { color, opacity } = paint+ if (color === undefined) return `Required value missing at ${at}.color`+ if (!color || typeof color !== 'object') {+ return `Expected object, received ${received(color)} at ${at}.color`+ }+ const channels = color as Partial<Record<'r' | 'g' | 'b' | 'a', unknown>>+ for (const channel of ['r', 'g', 'b', 'a'] as const) {+ if (channel === 'a' && channels.a === undefined) continue+ const problem = unitProblem(channels[channel], `${at}.color.${channel}`)+ if (problem) return problem+ }+ return opacity === undefined ? null : unitProblem(opacity, `${at}.opacity`)+}++function paintProblem(paint: unknown, index: number): string | null {+ if (!paint || typeof paint !== 'object') {+ return `Expected object, received ${received(paint)} at index ${index}`+ }+ const { type } = paint as { type?: unknown }+ if (!PAINT_TYPES.has(type as string)) {+ return `Invalid discriminator value. Expected ${[...PAINT_TYPES].map((name) => `'${name}'`).join(' | ')} at [${index}].type`+ }+ return type === 'SOLID' ? solidPaintProblem(paint, `[${index}]`) : null+}++function fillsFromPaints(method: string, value: unknown): CharacterStyleOverride['fills'] {+ if (!Array.isArray(value)) throw invalid(method, `Expected array, received ${received(value)}`)+ for (const [index, paint] of value.entries()) {+ const problem = paintProblem(paint, index)+ if (problem) throw invalid(method, problem)+ }+ return (value as FigmaPaint[]).map(figmaPaintToFill)+}++/**+ * A decoration colour Figma takes: `AUTO`, or a solid paint. A paint matching but for keys it+ * does not know reports only those; any other is reported against both choices.+ */+function decorationColorFills(method: string, value: unknown): Fill[] {+ const color = (value as { value?: unknown } | null)?.value+ if (color === 'AUTO') return []+ const issues: string[] = []+ if (!color || typeof color !== 'object') {+ issues.push(`Expected object, received ${received(color)} at .value`)+ } else {+ const paint = color as Partial<Record<'type' | 'color', unknown>>+ if (paint.type !== 'SOLID')+ issues.push('Invalid literal value, expected "SOLID" at .value.type')+ if (paint.color === undefined) issues.push('Required value missing at .value.color')+ else if (!paint.color || typeof paint.color !== 'object') {+ issues.push(`Expected object, received ${received(paint.color)} at .value.color`)+ }+ const unknown = Object.keys(paint).filter((key) => !SOLID_PAINT_KEYS.has(key))+ if (unknown.length > 0) {+ const keys = unknown.map((key) => `'${key}'`).join(', ')+ if (issues.length === 0) {+ throw invalid(+ method,+ `Unrecognized key(s) in object: ${keys} at .value`,+ 'textDecorationColor'+ )+ }+ issues.push(`Unrecognized key(s) in object: ${keys} at .value`)+ }+ }+ if (issues.length === 0) {+ // A solid paint whose channels are out of range fails on them alone.+ const problem = solidPaintProblem(color as { color?: unknown; opacity?: unknown }, '.value')+ if (problem) throw invalid(method, problem, 'textDecorationColor')+ return [figmaPaintToFill(color as FigmaPaint)]+ }+ const paintIssues =+ issues.length === 1+ ? ` ${issues[0]}`+ : ` Multiple issues:\n${issues.map((issue) => ` ${issue}`).join('\n')}`+ throw invalid(+ method,+ `Expected one of the following, but none matched:\n${paintIssues}\n` ++ ' Invalid literal value, expected "AUTO" at .value',+ 'textDecorationColor'+ )+}++function enumValue<T extends string>(method: string, value: unknown, allowed: ReadonlySet<T>): T {+ if (!(allowed as ReadonlySet<unknown>).has(value)) {+ throw invalid(+ method,+ `Invalid enum value. Expected ${[...allowed].map((name) => `'${name}'`).join(' | ')}, received '${String(value)}'`+ )+ }+ return value as T+}++type RangeSetter = (+ method: string,+ node: SceneNode,+ start: number,+ end: number,+ value: unknown+) => TextStylePatch++/** Decoration styles only apply to underlined text; Figma rejects a range with none. */+function underlineStyle(+ name: string,+ patch: (method: string, value: unknown) => TextStylePatch+): RangeSetter {+ return (method, node, start, end, value) => {+ const style = patch(method, value)+ if (!rangeHasUnderline(node, start, end)) {+ throw new Error(+ `in ${method}: Cannot set text decoration ${name} on a non-underlined text range`+ )+ }+ return style+ }+}++/** Range setters by method, each returning the style it gives the range. */+const RANGE_SETTERS: Record<string, RangeSetter> = {+ setRangeFontSize: (method, _node, _start, _end, value) => {+ const problem = numberProblem(value)+ if (problem) throw invalid(method, problem)+ if ((value as number) < 1) throw invalid(method, 'Number must be greater than or equal to 1')+ return { fontSize: value as number }+ },+ setRangeFontName: (method, _node, _start, _end, value) => fontNameStyle(method, value),+ setRangeFills: (method, _node, _start, _end, value) => ({+ fills: fillsFromPaints(method, value)+ }),+ setRangeLetterSpacing: (method, _node, _start, _end, value) => {+ const length = letterSpacingLength(method, value)+ return (fontSize) => ({ letterSpacing: length(fontSize) })+ },+ setRangeLineHeight: (method, _node, _start, _end, value) => {+ const length = lengthOrAuto(method, value)+ return (fontSize) => ({ lineHeight: length(fontSize) })+ },+ setRangeTextDecoration: (method, _node, _start, _end, value) => ({+ textDecoration: enumValue(method, value, DECORATIONS)+ }),+ setRangeTextDecorationStyle: underlineStyle('style', (method, value) => ({+ textDecorationStyle: enumValue(method, value, DECORATION_STYLES)+ })),+ setRangeTextDecorationOffset: underlineStyle('offset', (method, value) => {+ const length = lengthOrAuto(method, value)+ return (fontSize) => ({ textUnderlineOffset: length(fontSize) })+ }),+ setRangeTextDecorationThickness: underlineStyle('thickness', (method, value) => {+ const length = lengthOrAuto(method, value)+ return (fontSize) => ({ textDecorationThickness: length(fontSize) })+ }),+ setRangeTextDecorationColor: underlineStyle('color', (method, value) => ({+ textDecorationFills: decorationColorFills(method, value)+ })),+ setRangeTextDecorationSkipInk: underlineStyle('skip ink', (method, value) => {+ if (typeof value !== 'boolean')+ throw invalid(method, `Expected boolean, received ${received(value)}`)+ return { textDecorationSkipInk: value }+ })+}++/** Range getters by method and the segment field each reads. */+const RANGE_GETTERS: Record<string, TextSegmentField> = {+ getRangeFontSize: 'fontSize',+ getRangeFontName: 'fontName',+ getRangeFontWeight: 'fontWeight',+ getRangeFills: 'fills',+ getRangeLetterSpacing: 'letterSpacing',+ getRangeLineHeight: 'lineHeight',+ getRangeTextDecoration: 'textDecoration',+ getRangeTextDecorationStyle: 'textDecorationStyle',+ getRangeTextDecorationOffset: 'textDecorationOffset',+ getRangeTextDecorationThickness: 'textDecorationThickness',+ getRangeTextDecorationColor: 'textDecorationColor',+ getRangeTextDecorationSkipInk: 'textDecorationSkipInk',+ getRangeOpenTypeFeatures: 'openTypeFeatures'+}++type RangeGetter<T> = (start: number, end: number) => T | symbol+type RangeSetterMethod<T> = (start: number, end: number, value: T) => void++/** Figma's per-character and per-paragraph text methods, as the node proxy exposes them. */+export interface TextRangeMethods {+ getStyledTextSegments: (+ fields: TextSegmentField[],+ start?: number,+ end?: number+ ) => StyledTextSegment[]+ getRangeAllFontNames: (start: number, end: number) => FigmaFontName[]+ getRangeFontSize: RangeGetter<number>+ setRangeFontSize: RangeSetterMethod<number>+ getRangeFontName: RangeGetter<FigmaFontName>+ setRangeFontName: RangeSetterMethod<FigmaFontName>+ getRangeFontWeight: RangeGetter<number>+ getRangeFills: RangeGetter<Fill[]>+ setRangeFills: RangeSetterMethod<FigmaPaint[]>+ getRangeLetterSpacing: RangeGetter<FigmaLetterSpacing>+ setRangeLetterSpacing: RangeSetterMethod<FigmaLetterSpacing>+ getRangeLineHeight: RangeGetter<FigmaTextLength>+ setRangeLineHeight: RangeSetterMethod<FigmaTextLength>+ getRangeTextDecoration: RangeGetter<TextDecoration>+ setRangeTextDecoration: RangeSetterMethod<TextDecoration>+ getRangeTextDecorationStyle: RangeGetter<TextDecorationStyle | null>+ setRangeTextDecorationStyle: RangeSetterMethod<TextDecorationStyle>+ getRangeTextDecorationOffset: RangeGetter<FigmaTextLength | null>+ setRangeTextDecorationOffset: RangeSetterMethod<FigmaTextLength>+ getRangeTextDecorationThickness: RangeGetter<FigmaTextLength | null>+ setRangeTextDecorationThickness: RangeSetterMethod<FigmaTextLength>+ getRangeTextDecorationColor: RangeGetter<FigmaDecorationColor | null>+ setRangeTextDecorationColor: RangeSetterMethod<{ value: 'AUTO' } | { value: FigmaPaint }>+ getRangeTextDecorationSkipInk: RangeGetter<boolean | null>+ setRangeTextDecorationSkipInk: RangeSetterMethod<boolean>+ getRangeOpenTypeFeatures: RangeGetter<Record<string, boolean>>+ getRangeListOptions: RangeGetter<TextListOptions>+ setRangeListOptions: RangeSetterMethod<TextListOptions>+ getRangeIndentation: RangeGetter<number>+ setRangeIndentation: RangeSetterMethod<number>+ getRangeListSpacing: RangeGetter<number>+ setRangeListSpacing: RangeSetterMethod<number>+ getRangeParagraphSpacing: RangeGetter<number>+ setRangeParagraphSpacing: RangeSetterMethod<number>+ getRangeParagraphIndent: RangeGetter<number>+ setRangeParagraphIndent: RangeSetterMethod<number>+}++const PARAGRAPH_SPACING_METHODS = {+ ListSpacing: 'listSpacing',+ ParagraphSpacing: 'paragraphSpacing',+ ParagraphIndent: 'paragraphIndent'+} as const++/** Installs Figma's per-character and per-paragraph text methods on the node proxy. */+export function installTextRangeMethods(+ prototype: object,+ internals: NodeProxyInternals,+ mixed: symbol+): void {+ const methods: PropertyDescriptorMap = {}+ for (const [method, field] of Object.entries(RANGE_GETTERS)) {+ methods[method] = {+ value(this: ProxyThis, start: number, end: number) {+ return getRangeTextStyle(method, raw(this, internals), field, start, end, mixed)+ }+ }+ }+ for (const [method, setter] of Object.entries(RANGE_SETTERS)) {+ methods[method] = {+ value(this: ProxyThis, start: number, end: number, value: unknown) {+ const node = raw(this, internals)+ assertTextRange(method, node, start, end)+ const patch = setter(method, node, start, end, value)+ updateNode(this, internals, { styleRuns: styleRunsWithPatch(node, start, end, patch) })+ }+ }+ }+ methods.getRangeAllFontNames = {+ value(this: ProxyThis, start: number, end: number) {+ const node = raw(this, internals)+ assertTextRange('getRangeAllFontNames', node, start, end)+ const names = getStyledTextSegments(node, ['fontName'], start, end).map(+ (segment) => segment.fontName as FigmaFontName+ )+ return uniqBy(names, (name) => `${name.family}\u0000${name.style}`)+ }+ }+ methods.getStyledTextSegments = {+ value(this: ProxyThis, fields: TextSegmentField[], start?: number, end?: number) {+ return getStyledTextSegments(raw(this, internals), fields, start, end)+ }+ }+ methods.getRangeListOptions = {+ value(this: ProxyThis, start: number, end: number) {+ return getRangeListOptions(raw(this, internals), start, end, mixed)+ }+ }+ methods.setRangeListOptions = {+ value(this: ProxyThis, start: number, end: number, value: TextListOptions) {+ assertProxyEditable(this, internals)+ setRangeListOptions(graph(this, internals), raw(this, internals), start, end, value)+ }+ }+ methods.getRangeIndentation = {+ value(this: ProxyThis, start: number, end: number) {+ return getRangeIndentation(raw(this, internals), start, end, mixed)+ }+ }+ methods.setRangeIndentation = {+ value(this: ProxyThis, start: number, end: number, value: number) {+ assertProxyEditable(this, internals)+ setRangeIndentation(graph(this, internals), raw(this, internals), start, end, value)+ }+ }+ for (const [name, field] of Object.entries(PARAGRAPH_SPACING_METHODS)) {+ methods[`getRange${name}`] = {+ value(this: ProxyThis, start: number, end: number) {+ return getRangeParagraphSpacing(raw(this, internals), field, start, end, mixed)+ }+ }+ methods[`setRange${name}`] = {+ value(this: ProxyThis, start: number, end: number, value: number) {+ assertProxyEditable(this, internals)+ setRangeParagraphSpacing(+ graph(this, internals),+ raw(this, internals),+ field,+ start,+ end,+ value+ )+ }+ }+ }+ Object.defineProperties(prototype, methods)+}diff --git a/packages/core/src/figma-api/accessors/visual.ts b/packages/core/src/figma-api/accessors/visual.tsindex e035af7b1..f09cd3411 100644--- a/packages/core/src/figma-api/accessors/visual.ts+++ b/packages/core/src/figma-api/accessors/visual.ts@@ -16,6 +16,8 @@ import {type ProxyThis} from '#core/figma-api/accessor-utils'import { parseFigmaEffects, toFigmaEffect, type FigmaEffect } from '#core/figma-api/effects'+import { getTextStyle } from '#core/figma-api/text/style'+import { textStyleChanges } from '#core/text/character-style'function styleReference(internals: NodeProxyInternals,@@ -65,11 +67,21 @@ export function installVisualNodeProxyAccessors(): void {Object.defineProperties(prototype, {fills: {- get(this: ProxyThis): readonly Fill[] {- return Object.freeze(copyFills(raw(this, internals).fills))+ // Text reads mixed while its characters are filled differently, and setting it fills them all.+ get(this: ProxyThis): readonly Fill[] | symbol {+ const node = raw(this, internals)+ if (node.type !== 'TEXT') return Object.freeze(copyFills(node.fills))+ const fills = getTextStyle(node, 'fills', mixed)+ return typeof fills === 'symbol' ? fills : Object.freeze(fills as Fill[])},set(this: ProxyThis, value: readonly Fill[]) {- updateNode(this, internals, { fills: value.map(figmaPaintToFill) })+ const node = raw(this, internals)+ const fills = value.map(figmaPaintToFill)+ updateNode(+ this,+ internals,+ node.type === 'TEXT' ? textStyleChanges(node, { fills }) : { fills }+ )}},strokes: {diff --git a/packages/core/src/figma-api/compatibility.ts b/packages/core/src/figma-api/compatibility.tsindex 50e6c9c04..af36254b4 100644--- a/packages/core/src/figma-api/compatibility.ts+++ b/packages/core/src/figma-api/compatibility.ts@@ -115,13 +115,24 @@ type TextListKeys =| 'setRangeListSpacing'| 'setRangeParagraphSpacing'| 'setRangeParagraphIndent'+ | 'setRangeFontSize'+ | 'setRangeFontName'+ | 'setRangeLetterSpacing'+ | 'setRangeLineHeight'+ | 'setRangeTextDecoration'+ | 'setRangeTextDecorationStyle'+ | 'setRangeTextDecorationOffset'+ | 'setRangeTextDecorationThickness'+ | 'setRangeTextDecorationSkipInk'| 'hangingList'type TextListSurfaceMatch = Expect<Extends<Pick<FigmaNodeProxy, TextListKeys>, Pick<TextNode, TextListKeys>>>const _textListSurfaceMatch: TextListSurfaceMatch = true-// Figma's mixed values are its own `figma.mixed` unique symbol; ours are a plain symbol.+// Figma's mixed values are its own `figma.mixed` unique symbol; ours are a plain symbol. Fills+// and decoration colours read and take the paints OpenPencil models, as `fills` does, and Figma+// types OpenType features as every feature while it returns only those set, so they stay out.type WithoutMixed<T> = T extends (...args: infer A) => infer R? (...args: A) => Exclude<R, symbol>: Exclude<T, symbol>@@ -131,6 +142,23 @@ type TextMixedKeys =| 'getRangeListSpacing'| 'getRangeParagraphSpacing'| 'getRangeParagraphIndent'+ | 'getRangeFontSize'+ | 'getRangeFontName'+ | 'getRangeFontWeight'+ | 'getRangeLetterSpacing'+ | 'getRangeLineHeight'+ | 'getRangeTextDecoration'+ | 'getRangeTextDecorationStyle'+ | 'getRangeTextDecorationOffset'+ | 'getRangeTextDecorationThickness'+ | 'getRangeTextDecorationSkipInk'+ | 'getRangeAllFontNames'+ | 'fontSize'+ | 'fontName'+ | 'fontWeight'+ | 'letterSpacing'+ | 'lineHeight'+ | 'textDecoration'| 'listSpacing'| 'paragraphSpacing'| 'paragraphIndent'diff --git a/packages/core/src/figma-api/proxy.ts b/packages/core/src/figma-api/proxy.tsindex e36b1a82c..49b11a82b 100644--- a/packages/core/src/figma-api/proxy.ts+++ b/packages/core/src/figma-api/proxy.ts@@ -29,6 +29,7 @@ import { installBasicNodeProxyAccessors } from './accessors/basic'import { installLayoutNodeProxyAccessors } from './accessors/layout'import { installStrokeNodeProxyAccessors } from './accessors/strokes'import { installTextNodeProxyAccessors } from './accessors/text'+import { installTextRangeMethods, type TextRangeMethods } from './accessors/text/ranges'import { installVariableModeNodeProxyAccessors } from './accessors/variables'import {installVectorNodeProxyAccessors,@@ -104,7 +105,7 @@ export class FigmaNodeProxy {declare readonly absoluteBoundingBox: Rectdeclare readonly absoluteRenderBounds: Rect | null- declare fills: readonly Fill[]+ declare fills: readonly Fill[] | symboldeclare strokes: readonly Stroke[]declare effects: readonly FigmaEffect[]declare opacity: number@@ -169,17 +170,17 @@ export class FigmaNodeProxy {declare strokeRightWeight: numberdeclare characters: string- declare fontSize: number- declare fontName: FigmaFontName- declare fontWeight: number+ declare fontSize: number | symbol+ declare fontName: FigmaFontName | symbol+ declare fontWeight: number | symboldeclare textAlignHorizontal: stringdeclare textAlignVertical: stringdeclare textDirection: stringdeclare textAutoResize: string- declare letterSpacing: FigmaLetterSpacing- declare lineHeight: FigmaLineHeight+ declare letterSpacing: FigmaLetterSpacing | symbol+ declare lineHeight: FigmaLineHeight | symboldeclare textCase: string- declare textDecoration: string+ declare textDecoration: SceneNode['textDecoration'] | symboldeclare maxLines: number | nulldeclare listSpacing: number | symboldeclare paragraphSpacing: number | symbol@@ -188,6 +189,44 @@ export class FigmaNodeProxy {declare textTruncation: stringdeclare autoRename: boolean+ // Per-character and per-paragraph methods: accessors/text/ranges.ts.+ declare getStyledTextSegments: TextRangeMethods['getStyledTextSegments']+ declare getRangeAllFontNames: TextRangeMethods['getRangeAllFontNames']+ declare getRangeFontSize: TextRangeMethods['getRangeFontSize']+ declare setRangeFontSize: TextRangeMethods['setRangeFontSize']+ declare getRangeFontName: TextRangeMethods['getRangeFontName']+ declare setRangeFontName: TextRangeMethods['setRangeFontName']+ declare getRangeFontWeight: TextRangeMethods['getRangeFontWeight']+ declare getRangeFills: TextRangeMethods['getRangeFills']+ declare setRangeFills: TextRangeMethods['setRangeFills']+ declare getRangeLetterSpacing: TextRangeMethods['getRangeLetterSpacing']+ declare setRangeLetterSpacing: TextRangeMethods['setRangeLetterSpacing']+ declare getRangeLineHeight: TextRangeMethods['getRangeLineHeight']+ declare setRangeLineHeight: TextRangeMethods['setRangeLineHeight']+ declare getRangeTextDecoration: TextRangeMethods['getRangeTextDecoration']+ declare setRangeTextDecoration: TextRangeMethods['setRangeTextDecoration']+ declare getRangeTextDecorationStyle: TextRangeMethods['getRangeTextDecorationStyle']+ declare setRangeTextDecorationStyle: TextRangeMethods['setRangeTextDecorationStyle']+ declare getRangeTextDecorationOffset: TextRangeMethods['getRangeTextDecorationOffset']+ declare setRangeTextDecorationOffset: TextRangeMethods['setRangeTextDecorationOffset']+ declare getRangeTextDecorationThickness: TextRangeMethods['getRangeTextDecorationThickness']+ declare setRangeTextDecorationThickness: TextRangeMethods['setRangeTextDecorationThickness']+ declare getRangeTextDecorationColor: TextRangeMethods['getRangeTextDecorationColor']+ declare setRangeTextDecorationColor: TextRangeMethods['setRangeTextDecorationColor']+ declare getRangeTextDecorationSkipInk: TextRangeMethods['getRangeTextDecorationSkipInk']+ declare setRangeTextDecorationSkipInk: TextRangeMethods['setRangeTextDecorationSkipInk']+ declare getRangeOpenTypeFeatures: TextRangeMethods['getRangeOpenTypeFeatures']+ declare getRangeListOptions: TextRangeMethods['getRangeListOptions']+ declare setRangeListOptions: TextRangeMethods['setRangeListOptions']+ declare getRangeIndentation: TextRangeMethods['getRangeIndentation']+ declare setRangeIndentation: TextRangeMethods['setRangeIndentation']+ declare getRangeListSpacing: TextRangeMethods['getRangeListSpacing']+ declare setRangeListSpacing: TextRangeMethods['setRangeListSpacing']+ declare getRangeParagraphSpacing: TextRangeMethods['getRangeParagraphSpacing']+ declare setRangeParagraphSpacing: TextRangeMethods['setRangeParagraphSpacing']+ declare getRangeParagraphIndent: TextRangeMethods['getRangeParagraphIndent']+ declare setRangeParagraphIndent: TextRangeMethods['setRangeParagraphIndent']+constructor(id: string, graph: SceneGraph, api: NodeProxyHost) {this[INTERNAL_ID] = idthis[INTERNAL_GRAPH] = graph@@ -223,72 +262,6 @@ export class FigmaNodeProxy {TextProxy.deleteCharacters(this[INTERNAL_GRAPH], this._raw(), start, end)}- getRangeListOptions(start: number, end: number): TextListOptions | symbol {- return TextProxy.getRangeListOptions(this._raw(), start, end, MIXED)- }-- setRangeListOptions(start: number, end: number, value: TextListOptions): void {- assertNodeEditable(this[INTERNAL_GRAPH], this[INTERNAL_ID])- TextProxy.setRangeListOptions(this[INTERNAL_GRAPH], this._raw(), start, end, value)- }-- getRangeIndentation(start: number, end: number): number | symbol {- return TextProxy.getRangeIndentation(this._raw(), start, end, MIXED)- }-- setRangeIndentation(start: number, end: number, value: number): void {- assertNodeEditable(this[INTERNAL_GRAPH], this[INTERNAL_ID])- TextProxy.setRangeIndentation(this[INTERNAL_GRAPH], this._raw(), start, end, value)- }-- getRangeListSpacing(start: number, end: number): number | symbol {- return TextProxy.getRangeParagraphSpacing(this._raw(), 'listSpacing', start, end, MIXED)- }-- setRangeListSpacing(start: number, end: number, value: number): void {- assertNodeEditable(this[INTERNAL_GRAPH], this[INTERNAL_ID])- TextProxy.setRangeParagraphSpacing(- this[INTERNAL_GRAPH],- this._raw(),- 'listSpacing',- start,- end,- value- )- }-- getRangeParagraphSpacing(start: number, end: number): number | symbol {- return TextProxy.getRangeParagraphSpacing(this._raw(), 'paragraphSpacing', start, end, MIXED)- }-- setRangeParagraphSpacing(start: number, end: number, value: number): void {- assertNodeEditable(this[INTERNAL_GRAPH], this[INTERNAL_ID])- TextProxy.setRangeParagraphSpacing(- this[INTERNAL_GRAPH],- this._raw(),- 'paragraphSpacing',- start,- end,- value- )- }-- getRangeParagraphIndent(start: number, end: number): number | symbol {- return TextProxy.getRangeParagraphSpacing(this._raw(), 'paragraphIndent', start, end, MIXED)- }-- setRangeParagraphIndent(start: number, end: number, value: number): void {- assertNodeEditable(this[INTERNAL_GRAPH], this[INTERNAL_ID])- TextProxy.setRangeParagraphSpacing(- this[INTERNAL_GRAPH],- this._raw(),- 'paragraphIndent',- start,- end,- value- )- }-get isMask(): boolean {return this._raw().isMask}@@ -575,6 +548,7 @@ const proxyInternals = {installStrokeNodeProxyAccessors(FigmaNodeProxy.prototype, proxyInternals)installTextNodeProxyAccessors(FigmaNodeProxy.prototype, proxyInternals, MIXED)+installTextRangeMethods(FigmaNodeProxy.prototype, proxyInternals, MIXED)installLayoutNodeProxyAccessors(FigmaNodeProxy.prototype, proxyInternals)installVariableModeNodeProxyAccessors(FigmaNodeProxy.prototype, proxyInternals)installComponentPropertyAccessors(FigmaNodeProxy.prototype, proxyInternals)diff --git a/packages/core/src/figma-api/text.ts b/packages/core/src/figma-api/text/index.tssimilarity index 83%rename from packages/core/src/figma-api/text.tsrename to packages/core/src/figma-api/text/index.tsindex 6025b8478..da5bb672c 100644--- a/packages/core/src/figma-api/text.ts+++ b/packages/core/src/figma-api/text/index.ts@@ -21,21 +21,7 @@ import type {TextParagraphStyle} from '@open-pencil/scene-graph'-import { styleNameToWeight, weightToStyleName, type FigmaFontName } from './fonts'--export function getFontName(node: SceneNode): FigmaFontName {- return { family: node.fontFamily, style: weightToStyleName(node.fontWeight, node.italic) }-}--export function setFontName(graph: SceneGraph, nodeId: string, fontName: FigmaFontName): void {- const { weight, italic } = styleNameToWeight(fontName.style)- graph.updateNode(nodeId, {- fontFamily: fontName.family,- fontWeight: weight,- italic- })- recordInstanceOverride(graph, nodeId, ['fontFamily', 'fontWeight'])-}+import { assertTextRange } from './style'/** Figma's plugin API line height: automatic, or a size in pixels or percent of the font size. */export type FigmaLineHeight = { unit: 'AUTO' } | { unit: 'PIXELS' | 'PERCENT'; value: number }@@ -50,10 +36,6 @@ function pixels(value: { unit: 'PIXELS' | 'PERCENT'; value: number }, fontSize:return value.unit === 'PERCENT' ? (value.value / 100) * fontSize : value.value}-export function getLineHeight(node: SceneNode): FigmaLineHeight {- return node.lineHeight == null ? { unit: 'AUTO' } : { unit: 'PIXELS', value: node.lineHeight }-}-/*** Accepts Figma's object, or a bare number of pixels or `null` for automatic, as earlier* OpenPencil scripts wrote it.@@ -66,10 +48,6 @@ export function lineHeightValue(return value.unit === 'AUTO' ? null : pixels(value, node.fontSize)}-export function getLetterSpacing(node: SceneNode): FigmaLetterSpacing {- return { unit: 'PIXELS', value: node.letterSpacing }-}-/** Accepts Figma's object, or a bare number of pixels as earlier OpenPencil scripts wrote it. */export function letterSpacingValue(node: SceneNode, value: FigmaLetterSpacing | number): number {return typeof value === 'number' ? value : pixels(value, node.fontSize)@@ -108,24 +86,6 @@ export function deleteCharacters(type ListType = TextListOptions['type']const LIST_TYPES: ReadonlySet<string> = new Set<ListType>(['NONE', 'ORDERED', 'UNORDERED'])-/** Figma's checks on a character range, with its messages. */-function assertTextRange(method: string, node: SceneNode, start: number, end: number): void {- if (start < 0) {- throw new Error(- `in ${method}: Property "start" failed validation: Number must be greater than or equal to 0`- )- }- if (end <= start) {- throw new Error(`in ${method}: Empty range selected. 'end' must be greater than 'start'`)- }- if (start >= node.text.length || end > node.text.length) {- throw new Error(- `in ${method}: Range outside of available characters. 'start' must be less than ` +- `node.characters.length and 'end' must be less than or equal to node.characters.length`- )- }-}-/** The styles of the paragraphs a range touches: a newline belongs to the paragraph it ends. */function rangeParagraphStyles(node: SceneNode, start: number, end: number): TextParagraphStyle[] {const first = paragraphIndexAt(node.text, start)diff --git a/packages/core/src/figma-api/text/style.ts b/packages/core/src/figma-api/text/style.tsnew file mode 100644index 000000000..490b2717a--- /dev/null+++ b/packages/core/src/figma-api/text/style.ts@@ -0,0 +1,249 @@+import { isEqual } from 'es-toolkit/predicate'++import {+ paragraphIndexAt,+ paragraphSpacingAt,+ paragraphStyleAt,+ type Fill,+ type SceneNode+} from '@open-pencil/scene-graph'+import { copyFills } from '@open-pencil/scene-graph/copy'++import { weightToStyleName } from '#core/figma-api/fonts'+import { characterStyles, nodeStyle, type CharacterStyle } from '#core/text/character-style'++/** The fields `getStyledTextSegments` takes, in the order Figma lists them. */+export const TEXT_SEGMENT_FIELDS = [+ 'fontSize',+ 'fontName',+ 'fontWeight',+ 'fontStyle',+ 'textDecoration',+ 'textDecorationStyle',+ 'textDecorationSkipInk',+ 'textDecorationOffset',+ 'textDecorationThickness',+ 'textDecorationColor',+ 'textCase',+ 'lineHeight',+ 'letterSpacing',+ 'fills',+ 'textStyleId',+ 'fillStyleId',+ 'listOptions',+ 'indentation',+ 'hyperlink',+ 'openTypeFeatures',+ 'boundVariables',+ 'textStyleOverrides',+ 'paragraphSpacing',+ 'listSpacing',+ 'paragraphIndent',+ 'textWrapStyle'+] as const++export type TextSegmentField = (typeof TEXT_SEGMENT_FIELDS)[number]++/** A size Figma reads as automatic or in pixels; the node keeps pixels. */+export type FigmaTextLength = { unit: 'AUTO' } | { unit: 'PIXELS' | 'PERCENT'; value: number }++function pixels(value: number | null): FigmaTextLength {+ return value === null ? { unit: 'AUTO' } : { unit: 'PIXELS', value }+}++function underlined(style: CharacterStyle): boolean {+ return style.textDecoration === 'UNDERLINE'+}++/** Figma's paint for an underline colour of its own, or automatic, following the text. */+function decorationColor(style: CharacterStyle) {+ const paint = style.textDecorationFills.at(0)+ return paint ? { value: copyFills([paint])[0] } : { value: 'AUTO' as const }+}++function fontFeatureMap(style: CharacterStyle): Record<string, boolean> {+ return Object.fromEntries(style.fontFeatures.map((feature) => [feature.tag, feature.enabled]))+}++type FieldContext = { node: SceneNode; style: CharacterStyle; paragraph: number }++/** The decoration's own style reads null where the text is not underlined. */+function whenUnderlined(read: (style: CharacterStyle) => unknown) {+ return ({ style }: FieldContext) => (underlined(style) ? read(style) : null)+}++function spacing(field: 'paragraphSpacing' | 'listSpacing' | 'paragraphIndent') {+ return ({ node, paragraph }: FieldContext) => paragraphSpacingAt(node, paragraph, field)+}++/**+ * Figma's value of each field for one character. Fields the model keeps for the whole text, such+ * as text case, read the text's value; fields it has no place for read Figma's defaults.+ */+const FIELD_READERS: Record<TextSegmentField, (context: FieldContext) => unknown> = {+ fontSize: ({ style }) => style.fontSize,+ fontName: ({ style }) => ({+ family: style.fontFamily,+ style: weightToStyleName(style.fontWeight, style.italic)+ }),+ fontWeight: ({ style }) => style.fontWeight,+ fontStyle: ({ style }) => (style.italic ? 'ITALIC' : 'REGULAR'),+ textDecoration: ({ style }) => style.textDecoration,+ textDecorationStyle: whenUnderlined((style) => style.textDecorationStyle),+ textDecorationSkipInk: whenUnderlined((style) => style.textDecorationSkipInk),+ textDecorationOffset: whenUnderlined((style) => pixels(style.textUnderlineOffset)),+ textDecorationThickness: whenUnderlined((style) => pixels(style.textDecorationThickness)),+ textDecorationColor: whenUnderlined(decorationColor),+ textCase: ({ node }) => node.textCase,+ lineHeight: ({ style }) => pixels(style.lineHeight),+ letterSpacing: ({ style }) => ({ unit: 'PIXELS', value: style.letterSpacing }),+ fills: ({ style }) => copyFills(style.fills),+ textStyleId: ({ node }) => node.textStyleId ?? '',+ fillStyleId: ({ node }) => node.fillStyleId ?? '',+ listOptions: ({ node, paragraph }) => ({+ type: paragraphStyleAt(node.textParagraphs, paragraph).listType+ }),+ indentation: ({ node, paragraph }) =>+ paragraphStyleAt(node.textParagraphs, paragraph).indentation,+ hyperlink: () => null,+ openTypeFeatures: ({ style }) => fontFeatureMap(style),+ boundVariables: () => ({}),+ textStyleOverrides: () => [],+ paragraphSpacing: spacing('paragraphSpacing'),+ listSpacing: spacing('listSpacing'),+ paragraphIndent: spacing('paragraphIndent'),+ textWrapStyle: () => 'AUTO'+}++function readField(+ node: SceneNode,+ style: CharacterStyle,+ paragraph: number,+ field: TextSegmentField+): unknown {+ return FIELD_READERS[field]({ node, style, paragraph })+}++/** Figma's messages for a range a text method cannot use. */+export function assertTextRange(method: string, node: SceneNode, start: number, end: number) {+ if (start < 0) {+ throw new Error(+ `in ${method}: Property "start" failed validation: Number must be greater than or equal to 0`+ )+ }+ if (end <= start) {+ throw new Error(`in ${method}: Empty range selected. 'end' must be greater than 'start'`)+ }+ if (start >= node.text.length || end > node.text.length) {+ throw new Error(+ `in ${method}: Range outside of available characters. 'start' must be less than ` ++ `node.characters.length and 'end' must be less than or equal to node.characters.length`+ )+ }+}++/** One field's values for `text[start, end)`, character by character. */+function fieldValues(+ node: SceneNode,+ field: TextSegmentField,+ start: number,+ end: number+): unknown[] {+ const styles = characterStyles(node, start, end)+ let paragraph = paragraphIndexAt(node.text, start)+ return styles.map((style, offset) => {+ const value = readField(node, style, paragraph, field)+ // A newline belongs to the paragraph it ends.+ if (node.text[start + offset] === '\n') paragraph+++ return value+ })+}++/** The value every character of the range shares, or `mixed`. */+export function getRangeTextStyle(+ method: string,+ node: SceneNode,+ field: TextSegmentField,+ start: number,+ end: number,+ mixed: symbol+): unknown {+ assertTextRange(method, node, start, end)+ const [first, ...rest] = fieldValues(node, field, start, end)+ return rest.every((value) => isEqual(value, first)) ? first : mixed+}++/** The value every character of the text shares, or `mixed`; empty text reads its own style. */+export function getTextStyle(node: SceneNode, field: TextSegmentField, mixed: symbol): unknown {+ if (node.text.length === 0) return readField(node, nodeStyle(node), 0, field)+ const [first, ...rest] = fieldValues(node, field, 0, node.text.length)+ return rest.every((value) => isEqual(value, first)) ? first : mixed+}++export type StyledTextSegment = {+ characters: string+ start: number+ end: number+} & Partial<Record<TextSegmentField, unknown>>++export function getStyledTextSegments(+ node: SceneNode,+ fields: readonly TextSegmentField[],+ start?: number,+ end?: number+): StyledTextSegment[] {+ const method = 'getStyledTextSegments'+ for (const [index, field] of fields.entries()) {+ if (!(TEXT_SEGMENT_FIELDS as readonly string[]).includes(field)) {+ throw new Error(+ `in ${method}: Property "${method}" failed validation: Invalid enum value. Expected ` ++ `${TEXT_SEGMENT_FIELDS.map((name) => `'${name}'`).join(' | ')}, received '${String(field)}' at index ${index}`+ )+ }+ }+ if ((start === undefined) !== (end === undefined)) {+ throw new Error(`in ${method}: Invalid range. Must provide both 'start' and 'end'`)+ }+ const from = start ?? 0+ const to = end ?? node.text.length+ if (start !== undefined) assertTextRange(method, node, from, to)+ if (to === from) return []++ const ordered = TEXT_SEGMENT_FIELDS.filter((field) => fields.includes(field))+ const columns = ordered.map((field) => fieldValues(node, field, from, to))+ const segments: StyledTextSegment[] = []+ let first = 0+ for (const last of segmentEnds(columns, to - from)) {+ const segment: StyledTextSegment = {+ characters: node.text.slice(from + first, from + last),+ start: from + first,+ end: from + last+ }+ for (const [column, field] of ordered.entries()) segment[field] = columns[column][first]+ segments.push(segment)+ first = last+ }+ return segments+}++/** Where segments end: wherever any requested field changes, and at the end of the range. */+function segmentEnds(columns: readonly unknown[][], length: number): number[] {+ const ends: number[] = []+ let first = 0+ for (let offset = 1; offset < length; offset++) {+ const start = first+ if (columns.some((values) => !isEqual(values[offset], values[start]))) {+ ends.push(offset)+ first = offset+ }+ }+ ends.push(length)+ return ends+}++/** Whether any character of the range is underlined, which Figma's decoration setters need. */+export function rangeHasUnderline(node: SceneNode, start: number, end: number): boolean {+ return characterStyles(node, start, end).some(underlined)+}++export type FigmaDecorationColor = { value: 'AUTO' } | { value: Fill }diff --git a/packages/core/src/text/character-style.ts b/packages/core/src/text/character-style.tsnew file mode 100644index 000000000..57cf13029--- /dev/null+++ b/packages/core/src/text/character-style.ts@@ -0,0 +1,181 @@+import { omit } from 'es-toolkit/object'+import { isEqual } from 'es-toolkit/predicate'++import type { CharacterStyleOverride, SceneNode, StyleRun } from '@open-pencil/scene-graph'++/** A character's style: the text's own, with its run's overrides over it. */+export type CharacterStyle = Required<+ Pick<+ CharacterStyleOverride,+ | 'fontFamily'+ | 'fontWeight'+ | 'italic'+ | 'fontSize'+ | 'letterSpacing'+ | 'fills'+ | 'textDecoration'+ | 'textDecorationStyle'+ | 'textDecorationFills'+ | 'textDecorationSkipInk'+ | 'fontFeatures'+ >+> & {+ lineHeight: number | null+ textDecorationThickness: number | null+ textUnderlineOffset: number | null+}++export type TextStyleKey = (typeof TEXT_STYLE_KEYS)[number]++export const TEXT_STYLE_KEYS = [+ 'fontFamily',+ 'fontWeight',+ 'italic',+ 'fontSize',+ 'letterSpacing',+ 'lineHeight',+ 'fills',+ 'textDecoration',+ 'textDecorationStyle',+ 'textDecorationThickness',+ 'textDecorationFills',+ 'textDecorationSkipInk',+ 'textUnderlineOffset',+ 'fontFeatures'+] as const satisfies readonly (keyof CharacterStyle)[]++export function nodeStyle(node: SceneNode): CharacterStyle {+ return {+ fontFamily: node.fontFamily,+ fontWeight: node.fontWeight,+ italic: node.italic,+ fontSize: node.fontSize,+ letterSpacing: node.letterSpacing,+ lineHeight: node.lineHeight,+ fills: node.fills,+ textDecoration: node.textDecoration,+ textDecorationStyle: node.textDecorationStyle,+ textDecorationThickness: node.textDecorationThickness,+ textDecorationFills: node.textDecorationFills,+ textDecorationSkipInk: node.textDecorationSkipInk,+ textUnderlineOffset: node.textUnderlineOffset,+ fontFeatures: node.fontFeatures+ }+}++/** Every character's style, from the text's own and the runs over it. */+export function characterStyles(node: SceneNode, start: number, end: number): CharacterStyle[] {+ const base = nodeStyle(node)+ const styles = Array.from({ length: end - start }, () => base)+ for (const run of node.styleRuns) {+ const from = Math.max(start, run.start)+ const to = Math.min(end, run.start + run.length)+ for (let index = from; index < to; index++) {+ styles[index - start] = { ...styles[index - start], ...definedOverrides(run.style) }+ }+ }+ return styles+}++function definedOverrides(style: CharacterStyleOverride): Partial<CharacterStyle> {+ const defined: Partial<Record<keyof CharacterStyle, unknown>> = {}+ for (const key of TEXT_STYLE_KEYS) {+ if (style[key] !== undefined) defined[key] = style[key]+ }+ return defined as Partial<CharacterStyle>+}++/** Style runs with no override that only repeats the text's own value. */+function withoutRedundantOverrides(node: SceneNode, runs: StyleRun[]): StyleRun[] {+ const base = nodeStyle(node)+ const result: StyleRun[] = []+ for (const run of runs) {+ const style = omit(+ run.style,+ TEXT_STYLE_KEYS.filter(+ (key) => run.style[key] !== undefined && isEqual(run.style[key], base[key])+ )+ )+ if (Object.keys(style).length === 0) continue+ const previous = result.at(-1)+ if (+ previous &&+ previous.start + previous.length === run.start &&+ isEqual(previous.style, style)+ ) {+ previous.length += run.length+ } else {+ result.push({ start: run.start, length: run.length, style })+ }+ }+ return result+}++/**+ * A style for a range, or one per font size for a length given in percent of the font size,+ * which characters of each size resolve to their own length.+ */+export type TextStylePatch = CharacterStyleOverride | ((fontSize: number) => CharacterStyleOverride)++/** Style runs with `patch` over `text[start, end)`, as Figma restyles a range. */+export function styleRunsWithPatch(+ node: SceneNode,+ start: number,+ end: number,+ patch: TextStylePatch+): StyleRun[] {+ const length = node.text.length+ const chars: CharacterStyleOverride[] = Array.from({ length }, () => ({}))+ for (const run of node.styleRuns) {+ for (let index = run.start; index < run.start + run.length && index < length; index++) {+ chars[index] = { ...chars[index], ...run.style }+ }+ }+ const sized = typeof patch === 'function' ? patch : null+ const patches = new Map<number, CharacterStyleOverride>()+ for (let index = start; index < end; index++) {+ let style = sized ? undefined : (patch as CharacterStyleOverride)+ if (sized) {+ const fontSize = chars[index].fontSize ?? node.fontSize+ style = patches.get(fontSize) ?? sized(fontSize)+ patches.set(fontSize, style)+ }+ chars[index] = { ...chars[index], ...style }+ }+ // A newline takes the style of the character before it, as in Figma: a range that ends a+ // paragraph styles its newline too, and a newline cannot be styled on its own.+ for (let index = 1; index < length; index++) {+ if (node.text[index] === '\n') chars[index] = chars[index - 1]+ }+ const runs: StyleRun[] = []+ for (const [index, style] of chars.entries()) {+ const previous = runs.at(-1)+ if (previous && isEqual(previous.style, style)) previous.length+++ else runs.push({ start: index, length: 1, style })+ }+ return withoutRedundantOverrides(+ node,+ runs.filter((run) => Object.keys(run.style).length > 0)+ )+}++/**+ * The change that sets a style for the whole text, as Figma's node setters do: the text takes+ * the value and no range keeps one of its own.+ */+export function textStyleChanges(+ node: SceneNode,+ changes: Partial<Pick<SceneNode, TextStyleKey>>,+ sized?: (fontSize: number) => CharacterStyleOverride+): Partial<SceneNode> {+ const keys = Object.keys(changes) as TextStyleKey[]+ const runs = node.styleRuns.map((run) => ({ ...run, style: omit(run.style, keys) }))+ const updated = { ...node, ...changes }+ const styleRuns = withoutRedundantOverrides(updated, runs)+ // A percent gives characters of another size their own length.+ if (!sized) return { ...changes, styleRuns }+ return {+ ...changes,+ styleRuns: styleRunsWithPatch({ ...updated, styleRuns }, 0, node.text.length, sized)+ }+}diff --git a/packages/core/src/text/opentype.ts b/packages/core/src/text/opentype.tsindex d9487fc9f..81429b868 100644--- a/packages/core/src/text/opentype.ts+++ b/packages/core/src/text/opentype.ts@@ -26,7 +26,11 @@ interface OutlineFont {unitsPerEm: numberascender: numberdescender: number- tables: { os2?: { sTypoLineGap?: number }; fvar?: unknown }+ tables: {+ os2?: { sTypoLineGap?: number; yStrikeoutPosition?: number; yStrikeoutSize?: number }+ post?: { underlinePosition?: number; underlineThickness?: number }+ fvar?: unknown+ }glyphs: { get(index: number): OutlineGlyph | undefined }charToGlyphIndex(char: string): numbercharToGlyph(char: string): OutlineGlyph@@ -121,6 +125,44 @@ export function measureTextWithOpenType(return { width: Math.ceil(singleLineWidth), height: lineH }}+/**+ * Where a font draws its underline and strikethrough, in ems: each line's top edge below the+ * baseline (negative above it) and its thickness. Figma places an underline's top half its+ * thickness below the font's underline position, and a strikethrough's top at its strikeout+ * position.+ */+export interface FontDecorationMetrics {+ underlineTop: number+ underlineThickness: number+ strikethroughTop: number+ strikethroughThickness: number+}++/** The decoration metrics of a loaded font, or `null` when it is not loaded or lacks them. */+export function fontDecorationMetricsSync(+ family: string,+ style: string+): FontDecorationMetrics | null {+ const font = getParsedFont(family, style)+ const post = font?.tables.post+ const os2 = font?.tables.os2+ if (+ !font ||+ post?.underlinePosition === undefined ||+ !post.underlineThickness ||+ os2?.yStrikeoutPosition === undefined ||+ !os2.yStrikeoutSize+ )+ return null+ const em = font.unitsPerEm+ return {+ underlineTop: (post.underlineThickness / 2 - post.underlinePosition) / em,+ underlineThickness: post.underlineThickness / em,+ strikethroughTop: -os2.yStrikeoutPosition / em,+ strikethroughThickness: os2.yStrikeoutSize / em+ }+}+export interface GlyphOutlineMetrics {commands: OutlineCommand[]x: numberdiff --git a/packages/core/src/tools/modify/text.ts b/packages/core/src/tools/modify/text.tsindex 3a728998b..f8a001914 100644--- a/packages/core/src/tools/modify/text.ts+++ b/packages/core/src/tools/modify/text.ts@@ -1,12 +1,10 @@import * as v from 'valibot'-import type { CharacterStyleOverride, SceneNode } from '@open-pencil/scene-graph'+import type { SceneNode } from '@open-pencil/scene-graph'import { parseColor } from '@open-pencil/scene-graph/color'-import { styleToWeight } from '#core/text/fonts'-import { applyStyleToRange } from '#core/text/style-runs'import { toolNumber, nodeIdInput } from '#core/tools/input'-import { defineTool, nodeNotFound } from '#core/tools/schema'+import { defineTool, nodeNotFound, toolFailure } from '#core/tools/schema'export const setText = defineTool({name: 'set_text',@@ -43,10 +41,16 @@ export const setFont = defineTool({if (!node) return nodeNotFound(args.id)if (args.size !== undefined) node.fontSize = args.sizeif (args.family || args.style) {- const current = node.fontName+ // Text set in several fonts takes the given family or style for all of it, keeping the+ // rest from its first character.+ const fontName =+ typeof node.fontName === 'symbol' && node.characters.length > 0+ ? node.getRangeFontName(0, 1)+ : node.fontName+ const current = typeof fontName === 'symbol' ? null : fontNamenode.fontName = {- family: args.family ?? current.family,- style: args.style ?? current.style+ family: args.family ?? current?.family ?? '',+ style: args.style ?? current?.style ?? 'Regular'}}return { id: args.id, fontName: node.fontName, fontSize: node.fontSize }@@ -70,22 +74,30 @@ export const setFontRange = defineTool({execute: (figma, args) => {const node = figma.getNodeById(args.id)if (!node) return nodeNotFound(args.id)- const override: CharacterStyleOverride = {}- if (args.family) override.fontFamily = args.family- if (args.size) override.fontSize = args.size- if (args.style) {- const s = args.style.toLowerCase()- if (s.includes('italic')) override.italic = true- override.fontWeight = styleToWeight(args.style)+ const { start, end } = args+ if (!args.family && !args.size && !args.style && !args.color) {+ return { error: 'set_font_range needs at least one of family, size, style, or color' }}- if (args.color) {- override.fills = [{ type: 'SOLID', color: parseColor(args.color), opacity: 1, visible: true }]+ // The range methods reject an empty range or one past the text, before changing anything.+ try {+ if (args.size) node.setRangeFontSize(start, end, args.size)+ if (args.family || args.style) {+ const current = node.getRangeFontName(start, start + 1)+ const fontName = typeof current === 'symbol' ? null : current+ node.setRangeFontName(start, end, {+ family: args.family ?? fontName?.family ?? '',+ style: args.style ?? fontName?.style ?? 'Regular'+ })+ }+ if (args.color) {+ node.setRangeFills(start, end, [+ { type: 'SOLID', color: parseColor(args.color), opacity: 1, visible: true }+ ])+ }+ } catch (error) {+ return toolFailure(error)}- const raw = figma.graph.getNode(node.id)- if (!raw) return { error: `Node "${args.id}" not found` }- const runs = applyStyleToRange(raw.styleRuns, args.start, args.end, override, raw.text.length)- figma.graph.updateNode(node.id, { styleRuns: runs })- return { id: args.id, range: { start: args.start, end: args.end } }+ return { id: args.id, range: { start, end } }}})diff --git a/packages/core/tests/canvas/text/decorations.test.ts b/packages/core/tests/canvas/text/decorations.test.tsnew file mode 100644index 000000000..de484aaa3--- /dev/null+++ b/packages/core/tests/canvas/text/decorations.test.ts@@ -0,0 +1,113 @@+import { describe, expect, test } from 'bun:test'++import { toUint8Array } from 'js-base64'+import * as v from 'valibot'++import { join } from 'node:path'++import { expectDefined } from '#core-tests/helpers/assert'+import { FIXTURES } from '#core-tests/helpers/paths'++import { SceneGraph, type SceneNode, type Vector } from '@open-pencil/scene-graph'++import { savedDecoratedGlyphs, textDecorationRects } from '#core/canvas/text/decorations'++const Rect = v.object({ x: v.number(), y: v.number(), w: v.number(), h: v.number() })+const Oracle = v.object({+ outlines: v.array(v.string()),+ cases: v.array(+ v.object({+ name: v.string(),+ text: v.string(),+ fontSize: v.number(),+ textDecoration: v.picklist(['NONE', 'UNDERLINE', 'STRIKETHROUGH']),+ textDecorationStyle: v.picklist(['SOLID', 'DOTTED', 'WAVY']),+ styleRuns: v.array(+ v.object({ start: v.number(), length: v.number(), style: v.record(v.string(), v.unknown()) })+ ),+ glyphs: v.array(+ v.object({+ outline: v.number(),+ x: v.number(),+ y: v.number(),+ fontSize: v.number(),+ firstCharacter: v.optional(v.number()),+ advance: v.optional(v.number())+ })+ ),+ figmaRects: v.array(Rect)+ })+ )+})++const oracle = v.parse(+ v.pipe(v.string(), v.parseJson(), Oracle),+ await Bun.file(join(FIXTURES, 'figma-oracles/text-decorations.json')).text()+)++function oracleCase(name: string) {+ const found = expectDefined(+ oracle.cases.find((item) => item.name === name),+ name+ )+ const graph = new SceneGraph()+ const node = graph.createNode('TEXT', graph.getPages()[0].id, {+ text: found.text,+ // Not a loaded font, so the metrics are Figma's Inter, as for any text drawn from saved+ // glyphs without its font.+ fontFamily: '__FigmaInter__',+ fontSize: found.fontSize,+ textDecoration: found.textDecoration,+ textDecorationStyle: found.textDecorationStyle,+ styleRuns: found.styleRuns as SceneNode['styleRuns']+ })+ const glyphs = found.glyphs.map(({ outline, ...glyph }) => ({+ ...glyph,+ commandsBlob: toUint8Array(expectDefined(oracle.outlines[outline], 'outline'))+ }))+ return { node, glyphs, figmaRects: found.figmaRects }+}++function byPosition<T extends Vector>(rects: T[]): T[] {+ return rects.toSorted((a, b) => a.y - b.y || a.x - b.x)+}++/** Checks rects against Figma's to within `tolerance` pixels. */+function expectFigmaRects(name: string, tolerance: number) {+ const { node, glyphs, figmaRects } = oracleCase(name)+ const ours = byPosition(textDecorationRects(node, savedDecoratedGlyphs(glyphs)))+ const figma = byPosition(figmaRects)+ expect(ours).toHaveLength(figma.length)+ for (const [index, rect] of ours.entries()) {+ const expected = figma[index]+ expect(Math.abs(rect.x - expected.x)).toBeLessThan(tolerance)+ expect(Math.abs(rect.x + rect.width - (expected.x + expected.w))).toBeLessThan(tolerance)+ expect(Math.abs(rect.y - expected.y)).toBeLessThan(0.002)+ expect(Math.abs(rect.height - expected.h)).toBeLessThan(0.002)+ }+}++// Figma's own glyphs and the decoration rects it saved with them (2026-10-11).+describe('text decorations as Figma saves them', () => {+ test('place underlines, strikethroughs, offsets, and thicknesses from the font', () => {+ expectFigmaRects('deco-decorations', 0.02)+ })++ test('break underlines around descenders, widened by the thickness', () => {+ expectFigmaRects('skip-Inter-24', 0.02)+ expectFigmaRects('skip-Inter-96', 0.08)+ })++ test('break dotted and wavy underlines by less, keeping narrow pieces', () => {+ expectFigmaRects('skip-WAVY-24', 0.02)+ expectFigmaRects('skip-DOTTED-24', 0.02)+ })++ test('keep underlines whole when skip ink is off', () => {+ const { node, glyphs } = oracleCase('skip-Inter-24')+ node.textDecorationSkipInk = false+ const rects = textDecorationRects(node, savedDecoratedGlyphs(glyphs))+ expect(rects).toHaveLength(1)+ expect(rects[0].x).toBe(0)+ })+})diff --git a/packages/core/tests/canvas/text/derived.test.ts b/packages/core/tests/canvas/text/derived.test.tsindex 7ca99cf12..e3253cdc7 100644--- a/packages/core/tests/canvas/text/derived.test.ts+++ b/packages/core/tests/canvas/text/derived.test.ts@@ -32,9 +32,12 @@ function squareCommandsBlob(): Uint8Array {return blob}-/** The highest coverage on the underline rows at column `x` of a rendered text layer. */+/**+ * The highest coverage on the underline row at column `x` of a rendered text layer: 10px text+ * on a baseline at 12 is underlined from 13.99 to 14.67, as Figma places it.+ */function underlineAlpha(pixels: ArrayLike<number>, width: number, x: number): number {- return Math.max(...[15, 16].map((y) => pixels[(y * width + x) * 4 + 3]))+ return pixels[(14 * width + x) * 4 + 3]}describe('derived text decorations', () => {@@ -49,7 +52,14 @@ describe('derived text decorations', () => {textDecoration: 'UNDERLINE',fills: [{ type: 'SOLID', color: { r: 0, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }],derivedTextGlyphs: [- { commandsBlob: squareCommandsBlob(), x: 2, y: 12, fontSize: 10, advance: 10 }+ {+ commandsBlob: squareCommandsBlob(),+ x: 2,+ y: 12,+ fontSize: 10,+ firstCharacter: 0,+ advance: 10+ }]})const surface = expectDefined(ck.MakeSurface(1, 1), 'surface')diff --git a/packages/core/tests/canvas/text/shape.test.ts b/packages/core/tests/canvas/text/shape.test.tsindex 2036f8ef9..6cf7382ad 100644--- a/packages/core/tests/canvas/text/shape.test.ts+++ b/packages/core/tests/canvas/text/shape.test.ts@@ -94,14 +94,14 @@ describe('text shaping for saved glyphs', () => {expect(shaped.glyphs.every((glyph) => glyph.commands === null)).toBe(true)})- test('keeps the layout but no outlines for decorations across lines', async () => {+ test('keeps outlines for decorations across lines, which Figma draws from saved rects', async () => {const shaped = expectDefined(await shape({ text: SENTENCE, textDecoration: 'UNDERLINE' }),'shaped text')expect(shaped.baselines).toHaveLength(2)- expect(shaped.glyphs.every((glyph) => glyph.commands === null)).toBe(true)+ expect(shaped.glyphs.every((glyph) => glyph.commands !== null)).toBe(true)})test('does not shape truncated text', async () => {diff --git a/packages/core/tests/design-jsx/export-round-trip.test.ts b/packages/core/tests/design-jsx/export-round-trip.test.tsindex 903820d86..2bd35b8e2 100644--- a/packages/core/tests/design-jsx/export-round-trip.test.ts+++ b/packages/core/tests/design-jsx/export-round-trip.test.ts@@ -114,3 +114,47 @@ describe('shader paints', () => {)})})++describe('rich text round trip', () => {+ const RICH_FIELDS = ['text', 'styleRuns', 'textParagraphs'] as const++ async function expectRoundTrip(graph: SceneGraph, id: string) {+ const jsx = sceneNodeToJSX(id, graph)+ const [result] = await renderJSX(graph, jsx)+ const copy = getNodeOrThrow(graph, expectDefined(result, 'render result').id)+ expect(pick(copy, RICH_FIELDS)).toEqual(pick(getNodeOrThrow(graph, id), RICH_FIELDS))+ expect(sceneNodeToJSX(copy.id, graph)).toBe(jsx)+ }++ test('spans and paragraphs written as JSX come back the same', async () => {+ const graph = new SceneGraph()+ const [source] = await renderJSX(+ graph,+ `<Text size={24} color="#111111">+ <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>+ <Paragraph list="unordered"><Span size={18} font="Roboto" lineHeight={28}>Dot</Span></Paragraph>+ <Paragraph />+</Text>`+ )+ const node = getNodeOrThrow(graph, expectDefined(source, 'render result').id)+ expect(node.styleRuns.length).toBeGreaterThan(0)+ expect(node.textParagraphs).toHaveLength(4)+ await expectRoundTrip(graph, node.id)+ })++ test('styled text from the scene exports and renders back the same', async () => {+ const graph = new SceneGraph()+ const [source] = await renderJSX(graph, '<Text color="#000">Placeholder</Text>')+ const id = expectDefined(source, 'render result').id+ graph.updateNode(id, {+ text: 'Plain {braces} bold\nnext line',+ styleRuns: [+ { start: 15, length: 5, style: { fontWeight: 700 } },+ { start: 20, length: 4, style: { fontSize: 20 } }+ ]+ })+ await expectRoundTrip(graph, id)+ })+})diff --git a/packages/core/tests/editor/text/selection-style.test.ts b/packages/core/tests/editor/text/selection-style.test.tsnew file mode 100644index 000000000..3859bb317--- /dev/null+++ b/packages/core/tests/editor/text/selection-style.test.ts@@ -0,0 +1,86 @@+import { afterEach, describe, expect, test } from 'bun:test'++import { SkiaRenderer } from '@open-pencil/core/canvas'+import { createEditor } from '@open-pencil/core/editor'+import { initCanvasKit } from '@open-pencil/core/io'+import type { Fill } from '@open-pencil/scene-graph'++import { expectDefined } from '#core-tests/helpers/assert'++const cleanups: (() => void)[] = []++afterEach(() => {+ for (const cleanup of cleanups.splice(0)) cleanup()+})++const RED: Fill = {+ type: 'SOLID',+ color: { r: 1, g: 0, b: 0, a: 1 },+ opacity: 1,+ visible: true+}++/** An editor editing "Hello world" with "world" selected. */+async function editingWorld() {+ const ck = await initCanvasKit()+ const surface = expectDefined(ck.MakeSurface(200, 200), 'surface')+ const renderer = new SkiaRenderer(ck, surface)+ const editor = createEditor()+ editor.setCanvasKit(ck, renderer)+ await renderer.loadFonts()+ cleanups.push(() => {+ editor.dispose()+ renderer.destroy()+ })+ const page = editor.state.currentPageId+ const text = editor.graph.createNode('TEXT', page, { text: 'Hello world', width: 200, height: 20 })+ editor.startTextEditing(text.id)+ const state = expectDefined(editor.textEditor?.state, 'text editor state')+ state.selectionAnchor = 6+ state.cursor = 11+ const node = () => expectDefined(editor.graph.getNode(text.id), 'text')+ return { editor, id: text.id, node }+}++describe('panel edits while text is edited', () => {+ test('fill the selected characters, not the layer, and undo the fill', async () => {+ const { editor, id, node } = await editingWorld()+ const layerFills = node().fills++ editor.updateNodeWithUndo(id, { fills: [RED] }, 'Change fill')++ expect(node().fills).toEqual(layerFills)+ expect(node().styleRuns).toEqual([{ start: 6, length: 5, style: { fills: [RED] } }])+ expect(editor.getTextSelectionStyle(node())?.fills).toEqual([RED])++ editor.undoAction()+ expect(node().styleRuns).toEqual([])+ })++ test('record a dragged size as one step back to the runs it started from', async () => {+ const { editor, id, node } = await editingWorld()++ editor.updateNode(id, { fontSize: 30 })+ editor.updateNode(id, { fontSize: 40 })+ editor.commitNodeUpdate(id, { fontSize: 14 }, 'Change fontSize')++ expect(node().fontSize).toBe(14)+ expect(node().styleRuns).toEqual([{ start: 6, length: 5, style: { fontSize: 40 } }])+ editor.undoAction()+ expect(node().styleRuns).toEqual([])+ editor.redoAction()+ expect(node().styleRuns).toEqual([{ start: 6, length: 5, style: { fontSize: 40 } }])+ })++ test('style the layer when no characters are selected', async () => {+ const { editor, id, node } = await editingWorld()+ const state = expectDefined(editor.textEditor?.state, 'text editor state')+ state.selectionAnchor = null++ editor.updateNodeWithUndo(id, { fills: [RED] }, 'Change fill')++ expect(node().fills).toEqual([RED])+ expect(node().styleRuns).toEqual([])+ expect(editor.getTextSelectionStyle(node())).toBeNull()+ })+})diff --git a/packages/core/tests/figma-api/create-defaults.test.ts b/packages/core/tests/figma-api/create-defaults.test.tsindex b18f40cee..4219e572d 100644--- a/packages/core/tests/figma-api/create-defaults.test.ts+++ b/packages/core/tests/figma-api/create-defaults.test.ts@@ -3,6 +3,7 @@ import { describe, expect, test } from 'bun:test'import { createEditor } from '@open-pencil/core/editor'import { FigmaAPI } from '@open-pencil/core/figma-api'import { SceneGraph } from '@open-pencil/scene-graph'+import { expectFills } from '#core-tests/helpers/assert'// Recorded with the same script in Figma desktop 126: new layers from the plugin API and from the// drawing tools start alike.@@ -28,9 +29,9 @@ describe('new layer defaults', () => {const figma = api()const frame = figma.createFrame()const component = figma.createComponent()- expect(solid(frame.fills)).toEqual([WHITE])+ expect(solid(expectFills(frame.fills))).toEqual([WHITE])expect(frame.clipsContent).toBe(true)- expect(solid(component.fills)).toEqual([WHITE])+ expect(solid(expectFills(component.fills))).toEqual([WHITE])expect(component.clipsContent).toBe(false)})@@ -42,7 +43,7 @@ describe('new layer defaults', () => {figma.createPolygon(),figma.createStar()]) {- expect(solid(shape.fills)).toEqual([GREY])+ expect(solid(expectFills(shape.fills))).toEqual([GREY])expect(shape.strokes).toEqual([])}})@@ -71,12 +72,12 @@ describe('new layer defaults', () => {const figma = api()const light = figma.createSection()expect([light.width, light.height, light.cornerRadius]).toEqual([496, 496, 2])- expect(solid(light.fills)).toEqual([WHITE])+ expect(solid(expectFills(light.fills))).toEqual([WHITE])expect(solid(light.strokes)).toEqual([WHITE])expect([light.strokes[0]?.opacity, light.strokeAlign]).toEqual([0.1, 'INSIDE'])// Figma fills a section #444444 in its dark theme.figma.theme = 'dark'- expect(solid(figma.createSection().fills)).toEqual([[0.27, 0.27, 0.27]])+ expect(solid(expectFills(figma.createSection().fills))).toEqual([[0.27, 0.27, 0.27]])})test('each layer gets its own copy of the default paints', () => {diff --git a/packages/core/tests/figma-api/structure-parity.test.ts b/packages/core/tests/figma-api/structure-parity.test.tsindex 9adbbe20f..8a7033027 100644--- a/packages/core/tests/figma-api/structure-parity.test.ts+++ b/packages/core/tests/figma-api/structure-parity.test.ts@@ -2,6 +2,7 @@ import { describe, expect, test } from 'bun:test'import { FigmaAPI, type FigmaNodeProxy } from '@open-pencil/core/figma-api'import { SceneGraph } from '@open-pencil/scene-graph'+import { expectFills } from '#core-tests/helpers/assert'// Recorded with the same script in Figma desktop 126.@@ -70,7 +71,7 @@ describe('plugin API structure parity', () => {expect(component.type).toBe('COMPONENT')expect(component.name).toBe('r')expect([component.x, component.y, component.width, component.height]).toEqual([100, 0, 50, 50])- expect(component.fills[0]?.color).toMatchObject({ r: 1, g: 1, b: 1 })+ expect(expectFills(component.fills)[0]?.color).toMatchObject({ r: 1, g: 1, b: 1 })expect(order()).toEqual(['a', 'r', 'z'])expect(r.removed).toBe(false)expect(component.children[0]?.id).toBe(r.id)diff --git a/packages/core/tests/figma-api/text/styles.test.ts b/packages/core/tests/figma-api/text/styles.test.tsnew file mode 100644index 000000000..704cd91fe--- /dev/null+++ b/packages/core/tests/figma-api/text/styles.test.ts@@ -0,0 +1,356 @@+import { describe, expect, test } from 'bun:test'++import { expectFills } from '#core-tests/helpers/assert'++import { FigmaAPI, SceneGraph } from '@open-pencil/core'+import type { Color } from '@open-pencil/scene-graph'++// Results recorded from the same scripts run in live Figma (2026-10-11). OpenPencil reports+// lengths in pixels, as its node getters do, and paints in the shape `fills` returns.+function styledText(characters = 'Hello world\nSecond') {+ const api = new FigmaAPI(new SceneGraph())+ const text = api.createText()+ text.characters = characters+ return { api, text }+}++const REGULAR = { family: 'Inter', style: 'Regular' }+const BLUE: Color = { r: 0, g: 0, b: 1, a: 1 }+const RGB_BLUE = { r: 0, g: 0, b: 1 }+const BOLD = { family: 'Inter', style: 'Bold' }++describe('styled text segments', () => {+ test('split only where a requested field changes', () => {+ const { text } = styledText()+ text.setRangeFontSize(0, 5, 24)+ text.setRangeFontName(6, 11, BOLD)++ expect(text.getStyledTextSegments(['fontSize'])).toEqual([+ { characters: 'Hello', start: 0, end: 5, fontSize: 24 },+ { characters: ' world\nSecond', start: 5, end: 18, fontSize: 12 }+ ])+ expect(text.getStyledTextSegments(['fontSize', 'fontName'])).toEqual([+ { characters: 'Hello', start: 0, end: 5, fontSize: 24, fontName: REGULAR },+ { characters: ' ', start: 5, end: 6, fontSize: 12, fontName: REGULAR },+ { characters: 'world\n', start: 6, end: 12, fontSize: 12, fontName: BOLD },+ { characters: 'Second', start: 12, end: 18, fontSize: 12, fontName: REGULAR }+ ])+ expect(text.getStyledTextSegments(['fontSize'], 3, 8)).toEqual([+ { characters: 'lo', start: 3, end: 5, fontSize: 24 },+ { characters: ' wo', start: 5, end: 8, fontSize: 12 }+ ])+ })++ test('style a newline as the character before it', () => {+ const sizes = (start: number, end: number) => {+ const { text } = styledText('Hello world\nSecond\nThird')+ text.setRangeFontSize(start, end, 30)+ return text+ .getStyledTextSegments(['fontSize'])+ .map((segment) => [segment.start, segment.end, segment.fontSize])+ }+ expect(sizes(6, 11)).toEqual([+ [0, 6, 12],+ [6, 12, 30],+ [12, 24, 12]+ ])+ expect(sizes(6, 10)).toEqual([+ [0, 6, 12],+ [6, 10, 30],+ [10, 24, 12]+ ])+ expect(sizes(13, 18)).toEqual([+ [0, 13, 12],+ [13, 19, 30],+ [19, 24, 12]+ ])+ expect(sizes(11, 12)).toEqual([[0, 24, 12]])+ })++ test('read every field Figma lists, with its defaults for unstyled text', () => {+ const { text } = styledText('Abc')+ const [segment] = text.getStyledTextSegments([+ 'fontStyle',+ 'textDecorationStyle',+ 'textDecorationColor',+ 'textCase',+ 'lineHeight',+ 'hyperlink',+ 'textStyleId',+ 'fillStyleId',+ 'listOptions',+ 'indentation',+ 'openTypeFeatures',+ 'boundVariables',+ 'textStyleOverrides',+ 'textWrapStyle'+ ])+ expect(segment).toEqual({+ characters: 'Abc',+ start: 0,+ end: 3,+ fontStyle: 'REGULAR',+ textDecorationStyle: null,+ textDecorationColor: null,+ textCase: 'ORIGINAL',+ lineHeight: { unit: 'AUTO' },+ hyperlink: null,+ textStyleId: '',+ fillStyleId: '',+ listOptions: { type: 'NONE' },+ indentation: 0,+ openTypeFeatures: {},+ boundVariables: {},+ textStyleOverrides: [],+ textWrapStyle: 'AUTO'+ })+ })++ test('reject what Figma rejects, with its messages', () => {+ const { text } = styledText('Abc')+ expect(() => text.getStyledTextSegments(['fontSize'], 2, 2)).toThrow(+ "in getStyledTextSegments: Empty range selected. 'end' must be greater than 'start'"+ )+ expect(() => text.getStyledTextSegments(['fontSize'], 2)).toThrow(+ "in getStyledTextSegments: Invalid range. Must provide both 'start' and 'end'"+ )+ expect(() => text.getStyledTextSegments(['nope' as 'fontSize'])).toThrow(+ `in getStyledTextSegments: Property "getStyledTextSegments" failed validation: Invalid enum value. Expected 'fontSize' | 'fontName'`+ )+ expect(styledText('').text.getStyledTextSegments(['fontSize'])).toEqual([])+ })+})++describe('character style ranges', () => {+ test('read mixed on the node once ranges differ, and setting the node restyles every character', () => {+ const { api, text } = styledText()+ text.setRangeFontSize(0, 5, 24)+ text.setRangeFontName(6, 11, BOLD)+ expect<unknown>(text.fontSize).toBe(api.mixed)+ expect<unknown>(text.fontName).toBe(api.mixed)+ expect(text.getRangeFontSize(0, 8)).toBe(api.mixed)+ expect(text.getRangeFontWeight(6, 7)).toBe(700)+ expect(text.getRangeAllFontNames(0, 18)).toEqual([REGULAR, BOLD])++ text.fontSize = 13+ expect(text.getStyledTextSegments(['fontSize', 'fontName'])).toEqual([+ { characters: 'Hello ', start: 0, end: 6, fontSize: 13, fontName: REGULAR },+ { characters: 'world\n', start: 6, end: 12, fontSize: 13, fontName: BOLD },+ { characters: 'Second', start: 12, end: 18, fontSize: 13, fontName: REGULAR }+ ])+ })++ test('fill text ranges, and read the node mixed until it is filled again', () => {+ const { api, text } = styledText('Abc')+ const red = { type: 'SOLID' as const, color: { r: 1, g: 0, b: 0 } }+ text.setRangeFills(0, 1, [red])+ expect(expectFills(text.getRangeFills(0, 1) as never)[0]).toMatchObject({+ color: { r: 1, g: 0, b: 0 }+ })+ expect<unknown>(text.fills).toBe(api.mixed)+ text.fills = [{ type: 'SOLID', color: BLUE, opacity: 1, visible: true }]+ expect(+ text.getStyledTextSegments(['fills']).map((segment) => [segment.start, segment.end])+ ).toEqual([[0, 3]])+ expect(expectFills(text.fills)[0]).toMatchObject({ color: { r: 0, g: 0, b: 1 } })+ })++ test('take letter spacing and line height in pixels or percent of the font size', () => {+ const { api, text } = styledText('Abc')+ text.fontSize = 20+ text.setRangeLetterSpacing(0, 1, { value: 10, unit: 'PERCENT' })+ expect(text.getRangeLetterSpacing(0, 1)).toEqual({ unit: 'PIXELS', value: 2 })+ expect<unknown>(text.letterSpacing).toBe(api.mixed)+ text.setRangeLineHeight(0, 2, { value: 150, unit: 'PERCENT' })+ expect(text.getRangeLineHeight(0, 1)).toEqual({ unit: 'PIXELS', value: 30 })+ text.setRangeLineHeight(0, 2, { unit: 'AUTO' })+ expect(text.getRangeLineHeight(0, 1)).toEqual({ unit: 'AUTO' })+ })++ test('resolve a percent against the size of each character it styles', () => {+ const { text } = styledText('Small Large')+ text.fontSize = 10+ text.setRangeFontSize(6, 11, 20)+ const spacing = () =>+ text+ .getStyledTextSegments(['letterSpacing'])+ .map((segment) => [segment.start, segment.end, segment.letterSpacing])++ text.letterSpacing = { value: 10, unit: 'PERCENT' }+ expect(spacing()).toEqual([+ [0, 6, { unit: 'PIXELS', value: 1 }],+ [6, 11, { unit: 'PIXELS', value: 2 }]+ ])+ text.setRangeLetterSpacing(4, 8, { value: 50, unit: 'PERCENT' })+ expect(spacing()).toEqual([+ [0, 4, { unit: 'PIXELS', value: 1 }],+ [4, 6, { unit: 'PIXELS', value: 5 }],+ [6, 8, { unit: 'PIXELS', value: 10 }],+ [8, 11, { unit: 'PIXELS', value: 2 }]+ ])+ text.lineHeight = { value: 150, unit: 'PERCENT' }+ expect(text.getRangeLineHeight(0, 1)).toEqual({ unit: 'PIXELS', value: 15 })+ expect(text.getRangeLineHeight(6, 7)).toEqual({ unit: 'PIXELS', value: 30 })+ })++ test('style decorations of underlined ranges only, keeping them when the underline returns', () => {+ const { text } = styledText('Abc def')+ text.setRangeTextDecoration(0, 3, 'UNDERLINE')+ text.setRangeTextDecoration(4, 7, 'STRIKETHROUGH')+ expect([+ text.getRangeTextDecorationStyle(0, 3),+ text.getRangeTextDecorationOffset(0, 3),+ text.getRangeTextDecorationThickness(0, 3),+ text.getRangeTextDecorationColor(0, 3),+ text.getRangeTextDecorationSkipInk(0, 3)+ ]).toEqual(['SOLID', { unit: 'AUTO' }, { unit: 'AUTO' }, { value: 'AUTO' }, true])+ // A struck-through range has no underline to style.+ expect(text.getRangeTextDecorationStyle(4, 7)).toBeNull()+ expect(() => text.setRangeTextDecorationStyle(4, 7, 'WAVY')).toThrow(+ 'in setRangeTextDecorationStyle: Cannot set text decoration style on a non-underlined text range'+ )++ text.setRangeTextDecorationStyle(0, 3, 'WAVY')+ text.setRangeTextDecorationOffset(0, 3, { value: -2, unit: 'PIXELS' })+ text.setRangeTextDecorationThickness(0, 3, { value: 2, unit: 'PIXELS' })+ text.setRangeTextDecorationSkipInk(0, 3, false)+ text.setRangeTextDecorationColor(0, 3, {+ value: { type: 'SOLID', color: { r: 0, g: 1, b: 0 } }+ })+ expect(text.getRangeTextDecorationOffset(0, 3)).toEqual({ unit: 'PIXELS', value: -2 })+ expect(text.getRangeTextDecorationColor(0, 3)).toMatchObject({+ value: { color: { r: 0, g: 1, b: 0 } }+ })+ text.setRangeTextDecoration(0, 3, 'NONE')+ expect(text.getRangeTextDecorationSkipInk(0, 3)).toBeNull()+ text.setRangeTextDecoration(0, 3, 'UNDERLINE')+ expect([+ text.getRangeTextDecorationStyle(0, 3),+ text.getRangeTextDecorationThickness(0, 3),+ text.getRangeTextDecorationSkipInk(0, 3)+ ]).toEqual(['WAVY', { unit: 'PIXELS', value: 2 }, false])+ text.setRangeTextDecorationColor(0, 3, { value: 'AUTO' })+ expect(text.getRangeTextDecorationColor(0, 3)).toEqual({ value: 'AUTO' })+ })++ test('reject what Figma rejects, with its messages', () => {+ const { text } = styledText('Abc')+ const message = (method: string, problem: string) =>+ `in ${method}: Property "value" failed validation: ${problem}`+ expect(() => text.setRangeFontSize(0, 1, 0)).toThrow(+ message('setRangeFontSize', 'Number must be greater than or equal to 1')+ )+ expect(() => text.setRangeFontSize(0, 1, Number.NaN)).toThrow(+ message('setRangeFontSize', 'Expected number, received nan')+ )+ // The range is checked before the value.+ expect(() => text.setRangeFontSize(5, 9, 0)).toThrow(+ 'in setRangeFontSize: Range outside of available characters.'+ )+ expect(() =>+ text.setRangeLetterSpacing(0, 1, { value: 1, unit: 'EM' as 'PIXELS' })+ ).toThrow(+ message(+ 'setRangeLetterSpacing',+ "Invalid enum value. Expected 'PIXELS' | 'PERCENT', received 'EM' at .unit"+ )+ )+ expect(() => text.setRangeLineHeight(0, 1, { value: 1, unit: 'EM' as 'PIXELS' })).toThrow(+ message(+ 'setRangeLineHeight',+ "Invalid discriminator value. Expected 'PIXELS' | 'PERCENT' | 'AUTO' at .unit"+ )+ )+ expect(() =>+ text.setRangeFills(0, 1, [{ type: 'SOLID', color: { r: 2, g: 0, b: 0 } }])+ ).toThrow(message('setRangeFills', 'Number must be less than or equal to 1 at [0].color.r'))+ expect(() => text.setRangeTextDecoration(0, 1, 'OVERLINE' as 'NONE')).toThrow(+ message(+ 'setRangeTextDecoration',+ "Invalid enum value. Expected 'NONE' | 'UNDERLINE' | 'STRIKETHROUGH', received 'OVERLINE'"+ )+ )+ expect(() => text.setRangeFontName(0, 1, null as never)).toThrow(+ message('setRangeFontName', 'Expected object, received null')+ )+ expect(() => text.setRangeFontName(0, 1, { family: 1, style: 'Regular' } as never)).toThrow(+ message('setRangeFontName', 'Expected string, received number at .family')+ )+ text.setRangeTextDecoration(0, 3, 'UNDERLINE')+ expect(() => text.setRangeTextDecorationSkipInk(0, 1, 'yes' as never)).toThrow(+ message('setRangeTextDecorationSkipInk', 'Expected boolean, received string')+ )+ })++ test('reject paints Figma rejects, which would not survive saving', () => {+ const { text } = styledText('Abc')+ const paintTypes =+ "'SOLID' | 'SHADER' | 'GRADIENT_LINEAR' | 'GRADIENT_RADIAL' | 'GRADIENT_ANGULAR' | " ++ "'GRADIENT_DIAMOND' | 'IMAGE' | 'VIDEO'"+ const fills = (problem: string) =>+ `in setRangeFills: Property "value" failed validation: ${problem}`+ expect(() => text.setRangeFills(0, 1, [{ color: BLUE } as never])).toThrow(+ fills(`Invalid discriminator value. Expected ${paintTypes} at [0].type`)+ )+ expect(() => text.setRangeFills(0, 1, [{ type: 'SOLID' } as never])).toThrow(+ fills('Required value missing at [0].color')+ )+ expect(() => text.setRangeFills(0, 1, [null as never])).toThrow(+ fills('Expected object, received null at index 0')+ )+ const solid = (color: unknown, opacity?: unknown) =>+ text.setRangeFills(0, 1, [{ type: 'SOLID', color, opacity } as never])+ expect(() => solid(null)).toThrow(fills('Expected object, received null at [0].color'))+ expect(() => solid({ r: 0, g: 0 })).toThrow(fills('Required value missing at [0].color.b'))+ expect(() => solid({ r: -0.1, g: 0, b: 0 })).toThrow(+ fills('Number must be greater than or equal to 0 at [0].color.r')+ )+ expect(() => solid({ r: Number.NaN, g: 0, b: 0 })).toThrow(+ fills('Expected number, received nan at [0].color.r')+ )+ expect(() => solid({ r: '1', g: 0, b: 0 })).toThrow(+ fills('Expected number, received string at [0].color.r')+ )+ expect(() => solid({ r: 0, g: 0, b: 0, a: 2 })).toThrow(+ fills('Number must be less than or equal to 1 at [0].color.a')+ )+ expect(() => solid({ r: 0, g: 0, b: 0 }, 2)).toThrow(+ fills('Number must be less than or equal to 1 at [0].opacity')+ )+ expect(() => solid({ r: 0, g: 0, b: 0, a: 0.5 })).not.toThrow()++ text.setRangeTextDecoration(0, 3, 'UNDERLINE')+ const color = (problem: string) =>+ 'in setRangeTextDecorationColor: Property "textDecorationColor" failed validation: ' ++ problem+ const noneMatched = (issues: string) =>+ color(+ `Expected one of the following, but none matched:\n${issues}\n` ++ ' Invalid literal value, expected "AUTO" at .value'+ )+ expect(() => text.setRangeTextDecorationColor(0, 1, { value: BLUE as never })).toThrow(+ noneMatched(+ ' Multiple issues:\n' ++ ' Invalid literal value, expected "SOLID" at .value.type\n' ++ ' Required value missing at .value.color\n' ++ " Unrecognized key(s) in object: 'r', 'g', 'b', 'a' at .value"+ )+ )+ expect(() =>+ text.setRangeTextDecorationColor(0, 1, { value: { type: 'NOPE', color: RGB_BLUE } as never })+ ).toThrow(noneMatched(' Invalid literal value, expected "SOLID" at .value.type'))+ expect(() =>+ text.setRangeTextDecorationColor(0, 1, {+ value: { type: 'SOLID', color: RGB_BLUE, foo: 1 } as never+ })+ ).toThrow(color("Unrecognized key(s) in object: 'foo' at .value"))+ expect(() =>+ text.setRangeTextDecorationColor(0, 1, { value: { type: 'SOLID', color: null } as never })+ ).toThrow(noneMatched(' Expected object, received null at .value.color'))+ expect(() =>+ text.setRangeTextDecorationColor(0, 1, {+ value: { type: 'SOLID', color: { r: -1, g: 0, b: 0 } } as never+ })+ ).toThrow(color('Number must be greater than or equal to 0 at .value.color.r'))+ })+})diff --git a/packages/core/tests/helpers/assert.ts b/packages/core/tests/helpers/assert.tsindex d4d48ef65..4594344a4 100644--- a/packages/core/tests/helpers/assert.ts+++ b/packages/core/tests/helpers/assert.ts@@ -10,3 +10,9 @@ export function expectDefined<T>(value: T | null | undefined, label = 'value'):export function getNodeOrThrow(graph: SceneGraph, id: string): SceneNode {return expectDefined(graph.getNode(id), `node ${id}`)}++/** A script-visible node's fills, failing when they read `figma.mixed`, as differently filled text does. */+export function expectFills<T>(fills: readonly T[] | symbol, label = 'fills'): readonly T[] {+ if (typeof fills === 'symbol') throw new Error(`${label} were expected to be one value, not mixed`)+ return fills+}diff --git a/packages/core/tests/io/formats/fig/roundtrip/text-styles.test.ts b/packages/core/tests/io/formats/fig/roundtrip/text-styles.test.tsnew file mode 100644index 000000000..056a97de2--- /dev/null+++ b/packages/core/tests/io/formats/fig/roundtrip/text-styles.test.ts@@ -0,0 +1,40 @@+import { beforeAll, expect, test } from 'bun:test'++import { expectDefined } from '#core-tests/helpers/assert'++import { exportFigFile, initCodec, parseFigFile, SceneGraph } from '@open-pencil/core'+import { fontManager } from '@open-pencil/core/text'++beforeAll(async () => {+ await initCodec()+ const inter = expectDefined(+ await fontManager.fetchBundledFont('/Inter-Regular.ttf'),+ 'bundled Inter font'+ )+ fontManager.markLoaded('Inter', 'Regular', inter)+})++test('keeps auto line height on text that mixes font sizes', async () => {+ const graph = new SceneGraph()+ graph.createNode('TEXT', graph.getPages()[0].id, {+ text: 'Small large\nSecond line',+ fontFamily: 'Inter',+ fontSize: 24,+ lineHeight: null,+ width: 300,+ height: 73,+ textAutoResize: 'WIDTH_AND_HEIGHT',+ styleRuns: [+ { start: 6, length: 5, style: { fontSize: 36 } },+ { start: 12, length: 6, style: { textDecoration: 'UNDERLINE' } }+ ]+ })++ const reopened = await parseFigFile((await exportFigFile(graph)).slice().buffer)+ const text = expectDefined(+ [...reopened.getAllNodes()].find((node) => node.type === 'TEXT'),+ 'reopened text'+ )+ // Its lines differ in height; fixing both at the first one's cut off the second.+ expect(text.lineHeight).toBeNull()+})diff --git a/packages/design-jsx/README.md b/packages/design-jsx/README.mdindex c182db0e7..38e70aab6 100644--- a/packages/design-jsx/README.md+++ b/packages/design-jsx/README.md@@ -27,6 +27,16 @@ import { renderJSX } from '@open-pencil/core/design-jsx'await renderJSX(graph, '<Frame w={320} p={16} bg="#FFFFFF"><Text>Hello</Text></Frame>')```+Inside `<Text>`, `<Span>` styles some of its characters and `<Paragraph>` writes its paragraphs and list items:++```tsx+<Text size={16}>+ <Paragraph spacing={8}>Hello <Span weight="bold" color="#EE2222">world</Span></Paragraph>+ <Paragraph list="ordered">First</Paragraph>+ <Paragraph list="ordered" level={2}>Nested</Paragraph>+</Text>+```+Components that behave as controls are written with Reka UI's element names, in TSX (import `Switch`, `Slider`, `Tabs`, and the other namespaces, typed with their behaviour props) or in strings, and export writes them back the same way:```tsxdiff --git a/packages/design-jsx/src/component-properties.ts b/packages/design-jsx/src/component-properties.tsindex 813e5995e..fd8a5b786 100644--- a/packages/design-jsx/src/component-properties.ts+++ b/packages/design-jsx/src/component-properties.ts@@ -1,6 +1,11 @@+import { compact } from 'es-toolkit/array'import * as v from 'valibot'-import { applyComponentPropertyValue, componentPropertyDefinitions } from '@open-pencil/scene-graph'+import {+ applyComponentPropertyValue,+ componentPropertyDefinitions,+ createComponentPropertyId+} from '@open-pencil/scene-graph'import type {ComponentPropertyDefinition,ComponentPropertyReference,@@ -166,3 +171,64 @@ export function assignComponentProperties(assignValue(graph, instance, definition, key, value)}}++function parseVariantValues(name: string): Record<string, string> {+ const entries = compact(name.split(',').map((part) => part.trim()))+ const values: Record<string, string> = {}+ for (const entry of entries) {+ const [key = '', ...rest] = entry.split('=')+ const property = key.trim()+ const value = rest.join('=').trim()+ if (property && value) values[property] = value+ }+ return values+}++/** Variant properties a component set takes from its variants' names, such as `State=On`. */+export function inferComponentSetProperties(graph: SceneGraph, componentSetId: string): void {+ const componentSet = graph.getNode(componentSetId)+ if (componentSet?.type !== 'COMPONENT_SET') return+ const existingDefinitions = componentSet.componentPropertyDefinitions++ const variants = graph.getChildren(componentSetId).filter((node) => node.type === 'COMPONENT')+ const options = new Map<string, Set<string>>()+ const valuesById = new Map<string, Record<string, string>>()++ for (const variant of variants) {+ const values = parseVariantValues(variant.name)+ valuesById.set(variant.id, values)+ for (const [property, value] of Object.entries(values)) {+ let set = options.get(property)+ if (!set) {+ set = new Set()+ options.set(property, set)+ }+ set.add(value)+ }+ }++ const definitions: ComponentPropertyDefinition[] = [...options.entries()]+ .filter(+ ([name]) =>+ !existingDefinitions.some(+ (definition) => definition.type === 'VARIANT' && definition.name === name+ )+ )+ .map(([name, values]) => {+ const variantOptions = [...values]+ return {+ id: createComponentPropertyId(),+ name,+ type: 'VARIANT',+ defaultValue: variantOptions[0] ?? '',+ variantOptions+ }+ })++ for (const [id, values] of valuesById) {+ graph.updateNode(id, { componentPropertyValues: values })+ }+ graph.updateNode(componentSetId, {+ componentPropertyDefinitions: [...existingDefinitions, ...definitions]+ })+}diff --git a/packages/design-jsx/src/components.ts b/packages/design-jsx/src/components.tsindex c9d245297..3da2d6746 100644--- a/packages/design-jsx/src/components.ts+++ b/packages/design-jsx/src/components.ts@@ -3,6 +3,8 @@ import {type BaseProps,type ComponentProps,type InstanceProps,+ type ParagraphProps,+ type SpanProps,type TextProps,type TreeNode} from './tree'@@ -24,6 +26,14 @@ export function Text(props: TextProps, ...children: Child[]): TreeNode {return withChildren('text', props, children)}+export function Span(props: SpanProps, ...children: Child[]): TreeNode {+ return withChildren('text-span', props, children)+}++export function Paragraph(props: ParagraphProps, ...children: Child[]): TreeNode {+ return withChildren('text-paragraph', props, children)+}+export function Rectangle(props: BaseProps, ...children: Child[]): TreeNode {return withChildren('rectangle', props, children)}@@ -81,6 +91,8 @@ export const Page = Frameexport const INTRINSIC_ELEMENTS = ['frame','text',+ 'text-span',+ 'text-paragraph','rectangle','ellipse','line',diff --git a/packages/design-jsx/src/export/index.ts b/packages/design-jsx/src/export/index.tsindex 2ae56b0b7..fa0ca9cda 100644--- a/packages/design-jsx/src/export/index.ts+++ b/packages/design-jsx/src/export/index.ts@@ -5,28 +5,18 @@ import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'import { rekaExport, type RekaExport } from './behaviours'import { iconProps } from './icons'-import { collectProps, NODE_TYPE_TO_TAG, type JSXProp } from './props'-import { valueSyntax } from './value'--function propValue(value: JSXProp[1]): SyntaxNode | null {- if (value === true) return null- if (typeof value === 'string') return jsx.stringValue(value)- return jsx.container(valueSyntax(value))-}--/**- * A prop as a JSX attribute: `true` prints the bare name, strings as attribute strings, and- * other values as expressions, with paint and effect helpers as calls.- */-function propAttribute([name, value]: JSXProp): SyntaxNode {- return jsx.attribute(name, propValue(value))-}+import { collectProps, NODE_TYPE_TO_TAG } from './props'+import { textChildren } from './text'+import { propAttribute } from './value'/** Design JSX with the layer behind each element, in the order elements open. */export interface DesignJSXWithLayers {code: string- /** One id per JSX element, in pre-order, so editors can link elements to layers. */- layerIds: string[]+ /**+ * One entry per JSX element, in pre-order, so editors can link elements to layers: the+ * layer's id, or `null` for an element no layer is, such as a `<Span>` or `<Paragraph>`.+ */+ layerIds: Array<string | null>}const NO_REKA: RekaExport = { tags: new Map(), props: new Map(), flatten: new Set() }@@ -40,6 +30,17 @@ function mergeReka(outer: RekaExport, inner: RekaExport | null): RekaExport {}}+/** How many JSX elements the syntax holds, as an editor finds them in pre-order. */+function elementCount(nodes: readonly SyntaxNode[]): number {+ let count = 0+ for (const node of nodes) {+ if (node.type !== 'JSXElement') continue+ const children = (node as { children?: SyntaxNode[] }).children ?? []+ count += 1 + elementCount(children)+ }+ return count+}+/*** A layer and the layers below it as JSX elements. A component with a behaviour is written as* Reka UI elements; a container JSX leaves implicit is written as its children alone.@@ -48,7 +49,7 @@ function nodeToJSX(node: SceneNode,graph: SceneGraph,depth: number,- layerIds?: string[],+ layerIds?: Array<string | null>,outer: RekaExport = NO_REKA): SyntaxNode[] {const reka = mergeReka(outer, rekaExport(graph, node))@@ -73,7 +74,9 @@ function nodeToJSX(return [jsx.element(tag, ownProps.map(propAttribute), [], depth)]const attributes = [...collectProps(node, graph), ...(ownProps ?? [])].map(propAttribute)if (node.type === 'TEXT') {- return [jsx.element(tag, attributes, node.text ? [jsx.text(node.text)] : [], depth, true)]+ const { children: content, inline } = textChildren(node, depth)+ for (let count = elementCount(content); count > 0; count--) layerIds?.push(null)+ return [jsx.element(tag, attributes, content, depth, inline)]}return [jsx.element(tag, attributes, children(depth + 1), depth)]}@@ -158,7 +161,7 @@ export function selectionToJSXWithLayers(nodeIds: string[],graph: SceneGraph): DesignJSXWithLayers {- const layerIds: string[] = []+ const layerIds: Array<string | null> = []const code = compact(nodeIds.map((id) => {const node = graph.getNode(id)diff --git a/packages/design-jsx/src/export/props.ts b/packages/design-jsx/src/export/props.tsindex 9bc36b99e..e5ba0b742 100644--- a/packages/design-jsx/src/export/props.ts+++ b/packages/design-jsx/src/export/props.ts@@ -216,16 +216,19 @@ function collectTextSizingProps(node: SceneNode, graph: SceneGraph, props: JSXPrif (emitH && node.height > 0) props.push(['h', node.height])}+/** 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'+ if (weight === 500) return 'medium'+ return weight+}+function collectTextNodeProps(node: SceneNode, props: JSXProp[]): void {const direction = resolveNodeTextDirection(node)if (node.fontSize !== 14) props.push(['size', node.fontSize])if (node.fontFamily && node.fontFamily !== DEFAULT_FONT_FAMILY)props.push(['font', node.fontFamily])- if (node.fontWeight !== 400) {- if (node.fontWeight === 700) props.push(['weight', 'bold'])- else if (node.fontWeight === 500) props.push(['weight', 'medium'])- else props.push(['weight', node.fontWeight])- }+ if (node.fontWeight !== 400) props.push(['weight', fontWeightValue(node.fontWeight)])if (direction === 'RTL') props.push(['dir', 'rtl'])if (node.italic) props.push(['italic', true])if (node.textAlignHorizontal !== 'LEFT') {diff --git a/packages/design-jsx/src/export/text.ts b/packages/design-jsx/src/export/text.tsnew file mode 100644index 000000000..2d7d2c632--- /dev/null+++ b/packages/design-jsx/src/export/text.ts@@ -0,0 +1,122 @@+import { isEmptyObject, isEqual, omitBy, pick } from 'es-toolkit'++import { jsx, type SyntaxNode } from '@open-pencil/emit'+import {+ hasParagraphSpacing,+ MAX_LIST_INDENTATION,+ paragraphStyleAt,+ textParagraphRanges,+ type SceneNode,+ type TextParagraphStyle+} from '@open-pencil/scene-graph'++import { SPAN_STYLE_FIELDS, type SpanStyle } from '../text-content'+import { collectFillProps } from './paint'+import { fontWeightValue } from './props'+import { propAttribute, type JSXProp } from './value'++/** A text's content as JSX children, and whether they print on the element's own line. */+export interface TextChildren {+ children: SyntaxNode[]+ 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 => ({}))+ for (const run of node.styleRuns) {+ const style = pick(run.style, SPAN_STYLE_FIELDS)+ const end = Math.min(run.start + run.length, styles.length)+ 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]))+ )+}++function spanProps(style: SpanStyle, node: SceneNode): JSXProp[] {+ const props: JSXProp[] = []+ if (style.fontSize !== undefined) props.push(['size', style.fontSize])+ if (style.fontFamily !== undefined) props.push(['font', style.fontFamily])+ 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.letterSpacing !== undefined) props.push(['letterSpacing', style.letterSpacing])+ if (style.textDecoration !== undefined)+ props.push(['textDecoration', style.textDecoration.toLowerCase()])+ return props+}++/** `text[start, end)` as text and a `<Span>` for every stretch styled apart from the text. */+function inlineContent(+ node: SceneNode,+ styles: readonly SpanStyle[],+ start: number,+ end: number+): SyntaxNode[] {+ const content: SyntaxNode[] = []+ let from = start+ for (let index = start + 1; index <= end; index++) {+ if (index < end && isEqual(styles[index], styles[from])) continue+ const text = jsx.inlineText(node.text.slice(from, index))+ const style = styles[from]+ content.push(+ isEmptyObject(style)+ ? text+ : jsx.element('Span', spanProps(style, node).map(propAttribute), [text], 0, true)+ )+ from = index+ }+ return content+}++function paragraphProps(style: TextParagraphStyle): JSXProp[] {+ const props: JSXProp[] = []+ if (style.listType !== 'NONE') {+ props.push(['list', style.listType === 'ORDERED' ? 'ordered' : 'unordered'])+ 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])+ 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.+ */+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 styledParagraphs = paragraphs.some(+ (style) => style.listType !== 'NONE' || hasParagraphSpacing(style)+ )+ if (!styledParagraphs) {+ if (styles.every(isEmptyObject)) {+ return { children: node.text ? [jsx.text(node.text)] : [], inline: true }+ }+ return { children: inlineContent(node, styles, 0, node.text.length), inline: true }+ }+ const children = ranges.map(({ start, end }, index) =>+ jsx.element(+ 'Paragraph',+ paragraphProps(paragraphs[index]).map(propAttribute),+ inlineContent(node, styles, start, end),+ depth + 1,+ true+ )+ )+ return { children, inline: false }+}diff --git a/packages/design-jsx/src/export/value.ts b/packages/design-jsx/src/export/value.tsindex 535d8056e..ed9b18aba 100644--- a/packages/design-jsx/src/export/value.ts+++ b/packages/design-jsx/src/export/value.ts@@ -66,3 +66,17 @@ export function valueSyntax(value: JSXValue): SyntaxNode {}return jsx.literal(value)}++function propValue(value: JSXValue): SyntaxNode | null {+ if (value === true) return null+ if (typeof value === 'string') return jsx.stringValue(value)+ return jsx.container(valueSyntax(value))+}++/**+ * A prop as a JSX attribute: `true` prints the bare name, strings as attribute strings, and+ * other values as expressions, with paint and effect helpers as calls.+ */+export function propAttribute([name, value]: JSXProp): SyntaxNode {+ return jsx.attribute(name, propValue(value))+}diff --git a/packages/design-jsx/src/index.ts b/packages/design-jsx/src/index.tsindex ed5bd5ebd..0bc50732f 100644--- a/packages/design-jsx/src/index.ts+++ b/packages/design-jsx/src/index.ts@@ -1,6 +1,8 @@export {Frame,Text,+ Span,+ Paragraph,Rectangle,Ellipse,Line,@@ -42,6 +44,8 @@ export {type ComponentProps,type InstanceProps,type TextProps,+ type SpanProps,+ type ParagraphProps,type StyleProps,type PaintProp,isTreeNode,@@ -91,6 +95,8 @@ export {DESIGN_JSX_SUPPORTED_PROPERTIES,DESIGN_JSX_SUPPORTED_PROPERTY_NAMES,DESIGN_JSX_PROPERTY_ALIASES,+ DESIGN_JSX_PARAGRAPH_PROPERTY_NAMES,+ DESIGN_JSX_SPAN_PROPERTY_NAMES,DESIGN_JSX_STYLE_KEYS,type DesignJSXStyleKey,designJSXProp,diff --git a/packages/design-jsx/src/jsx-runtime.ts b/packages/design-jsx/src/jsx-runtime.tsindex d3236a12c..b516ac6f8 100644--- a/packages/design-jsx/src/jsx-runtime.ts+++ b/packages/design-jsx/src/jsx-runtime.ts@@ -1,4 +1,12 @@-import { FRAGMENT, node, type BaseProps, type TreeNode, type TextProps } from './tree'+import {+ FRAGMENT,+ node,+ type BaseProps,+ type ParagraphProps,+ type SpanProps,+ type TreeNode,+ type TextProps+} from './tree'export function jsx(type: string | ((props: BaseProps) => TreeNode), props: BaseProps): TreeNode {if (typeof type === 'function') {@@ -21,6 +29,8 @@ export namespace JSX {export interface IntrinsicElements {frame: BasePropstext: TextProps+ 'text-span': SpanProps+ 'text-paragraph': ParagraphPropsrectangle: BasePropsellipse: BasePropsline: BasePropsdiff --git a/packages/design-jsx/src/reference.ts b/packages/design-jsx/src/reference.tsindex 741b09510..1e203541d 100644--- a/packages/design-jsx/src/reference.ts+++ b/packages/design-jsx/src/reference.ts@@ -1,5 +1,3 @@-import dedent from 'dedent'-import authoring from './reference/authoring.md?raw'import { AUTHORING_EXAMPLES } from './reference/examples'import {@@ -13,15 +11,8 @@ export { AUTHORING_EXAMPLES, type AuthoringExample } from './reference/examples'/** Canonical scene-authoring guidance shared by runtime prompts and generated skill references. */export const JSX_REFERENCE = [authoring.trim(),- ...AUTHORING_EXAMPLES.map(- ({ title, jsx }) => dedent`-## ${title}--\`\`\`jsx-${jsx}-\`\`\`-`- ),+ // Examples are written verbatim; dedenting them again would flatten their nesting.+ ...AUTHORING_EXAMPLES.map(({ title, jsx }) => `## ${title}\n\n\`\`\`jsx\n${jsx}\n\`\`\``),'## Supported syntax inventory','Generated from the renderer metadata. This inventory lists accepted names, not arbitrary browser CSS support.',`**Elements:** ${DESIGN_JSX_ELEMENTS.map(({ name }) => `\`${name}\``).join(', ')}.`,diff --git a/packages/design-jsx/src/reference/authoring.md b/packages/design-jsx/src/reference/authoring.mdindex 8c5632968..9e5564850 100644--- a/packages/design-jsx/src/reference/authoring.md+++ b/packages/design-jsx/src/reference/authoring.md@@ -23,6 +23,7 @@ This reference describes scene creation, not React DOM output. Use the `render`- `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.- `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 677f6d96e..714457be5 100644--- a/packages/design-jsx/src/reference/examples.ts+++ b/packages/design-jsx/src/reference/examples.ts@@ -18,6 +18,17 @@ export const AUTHORING_EXAMPLES: readonly AuthoringExample[] = [title: 'Variable-bound spacing and typography',jsx: dedent`<Frame name="Bound note" w={280} h="hug" flex="col" gap={designVar('Space/small')} p={designVar('Space/medium')} bg="#FFFFFF"><Text name="Message" w="fill" size={designVar('Type/body')} lineHeight={designVar('Type/body-leading')} letterSpacing={designVar('Type/body-tracking')} color="#252A31">A note that grows with its content.</Text>+</Frame>`+ },+ {+ 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>+ <Paragraph list="unordered">Faster export</Paragraph>+ <Paragraph list="unordered" level={2}>PDF and SVG</Paragraph>+ <Paragraph list="ordered">Fewer clicks</Paragraph>+ </Text></Frame>`}]diff --git a/packages/design-jsx/src/render.ts b/packages/design-jsx/src/render.tsindex 601ba922b..27ff54b34 100644--- a/packages/design-jsx/src/render.ts+++ b/packages/design-jsx/src/render.ts@@ -1,4 +1,4 @@-import { uniq } from 'es-toolkit/array'+import { difference, uniq } from 'es-toolkit/array'import { transform } from 'sucrase'import type { SceneGraph } from '@open-pencil/scene-graph'@@ -7,17 +7,16 @@ import { REKA_ELEMENTS } from './behaviours'import { designJSXHelpers } from './helpers'import * as React from './mini-react'import { renderRoots, renderTree, componentPropNames, type RenderResult } from './renderer'-import { DESIGN_JSX_SUPPORTED_PROPERTIES } from './schema'+import {+ DESIGN_JSX_PARAGRAPH_PROPERTY_NAMES,+ DESIGN_JSX_SPAN_PROPERTY_NAMES,+ DESIGN_JSX_SUPPORTED_PROPERTY_NAMES+} from './schema'import type { DesignJSXServices } from './services'+import { PARAGRAPH, SPAN, TEXT_CONTENT_NAMES } from './text-content'import { isTreeNode, resolveToTree, type TreeNode } from './tree'import type { RenderOptions as RenderJSXOptions } from './types'-/**- * Build a component function from a JSX string using sucrase.- * Works in both Node/Bun and the browser (no native bindings).- */-const SUPPORTED_PROPS = DESIGN_JSX_SUPPORTED_PROPERTIES-/** `const Switch = { Root: 'Switch.Root', … }`: each Reka namespace as element types. */const REKA_ALIASES = Object.entries(REKA_ELEMENTS).map(@@ -38,19 +37,33 @@ function unsupportedPropWarnings(graph: SceneGraph, tree: TreeNode): string[] {return warnings}-const SVG_ROOT_PROPS = new Set([...SUPPORTED_PROPS, 'viewBox', 'body'])+// Paragraph props describe a paragraph of a text, never a layer.+const LAYER_PROPS = new Set<string>(+ difference(DESIGN_JSX_SUPPORTED_PROPERTY_NAMES, DESIGN_JSX_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])+const SPAN_PROPS = new Set<string>(['key', ...DESIGN_JSX_SPAN_PROPERTY_NAMES])++function supportedProps(type: string): ReadonlySet<string> {+ if (type === 'svg') return SVG_ROOT_PROPS+ if (type === SPAN) return SPAN_PROPS+ if (type === PARAGRAPH) return PARAGRAPH_PROPS+ return LAYER_PROPS+}function collectUnsupportedPropWarnings(graph: SceneGraph,tree: TreeNode,warnings: string[]): void {- const supportedProps = tree.type === 'svg' ? SVG_ROOT_PROPS : SUPPORTED_PROPS+ const supported = supportedProps(tree.type)// An instance sets its component's properties by name, such as `State="On"` or `Title="Hi"`.const properties = componentPropNames(graph, tree.props)for (const key of Object.keys(tree.props)) {- if (!supportedProps.has(key) && !properties.includes(key)) {- warnings.push(`Unsupported prop "${key}" on <${tree.type}> is ignored.`)+ if (!supported.has(key) && !properties.includes(key)) {+ const element = TEXT_CONTENT_NAMES[tree.type] ?? tree.type+ warnings.push(`Unsupported prop "${key}" on <${element}> is ignored.`)}}@@ -62,6 +75,10 @@ function collectUnsupportedPropWarnings(}}+/**+ * Build a component function from a JSX string using sucrase.+ * Works in both Node/Bun and the browser (no native bindings).+ */export function buildComponent(jsxString: string, warnings: string[] = []): React.ComponentType {const trimmed = stripHTMLComments(jsxString).trim()@@ -72,6 +89,7 @@ export function buildComponent(jsxString: string, warnings: string[] = []): Reacconst Line = 'line', Star = 'star', Polygon = 'polygon', Vector = 'vector'const Group = 'group', Section = 'section', View = 'frame', Rect = 'rectangle'const Component = 'component', ComponentSet = 'component-set', Instance = 'instance'+ const Span = 'text-span', Paragraph = 'text-paragraph'const Icon = 'icon'const svg = 'svg'${REKA_ALIASES}diff --git a/packages/design-jsx/src/renderer.ts b/packages/design-jsx/src/renderer.tsindex 5bdd13bf6..19249d91c 100644--- a/packages/design-jsx/src/renderer.ts+++ b/packages/design-jsx/src/renderer.ts@@ -1,10 +1,6 @@-import { compact } from 'es-toolkit/array'-import {- createComponentPropertyId,setInstanceOverride,type Color,- type ComponentPropertyDefinition,type NodeType,type SceneGraph,type SceneNode@@ -17,11 +13,13 @@ import {assignComponentProperties,componentMetadata,assignNamedProperties,- componentPropertyScope+ componentPropertyScope,+ inferComponentSetProperties} from './component-properties'import { applySizeOverrides, propsToOverrides } from './props-overrides'import { prepareScalarBindings } from './scalar-bindings'import type { DesignJSXServices } from './services'+import { isTextContent, TEXT_CONTENT_NAMES, textContentFields } from './text-content'import { FRAGMENT, isTreeNode } from './tree'import type { TreeNode } from './tree'import type { RenderOptions } from './types'@@ -289,66 +287,6 @@ function renderSVGNode<Artwork>(return placeArtwork(services, graph, artwork, props, size, parentId)}-function parseVariantValues(name: string): Record<string, string> {- const entries = compact(name.split(',').map((part) => part.trim()))- const values: Record<string, string> = {}- for (const entry of entries) {- const [key = '', ...rest] = entry.split('=')- const property = key.trim()- const value = rest.join('=').trim()- if (property && value) values[property] = value- }- return values-}--function inferComponentSetProperties(graph: SceneGraph, componentSetId: string): void {- const componentSet = graph.getNode(componentSetId)- if (componentSet?.type !== 'COMPONENT_SET') return- const existingDefinitions = componentSet.componentPropertyDefinitions-- const variants = graph.getChildren(componentSetId).filter((node) => node.type === 'COMPONENT')- const options = new Map<string, Set<string>>()- const valuesById = new Map<string, Record<string, string>>()-- for (const variant of variants) {- const values = parseVariantValues(variant.name)- valuesById.set(variant.id, values)- for (const [property, value] of Object.entries(values)) {- let set = options.get(property)- if (!set) {- set = new Set()- options.set(property, set)- }- set.add(value)- }- }-- const definitions: ComponentPropertyDefinition[] = [...options.entries()]- .filter(- ([name]) =>- !existingDefinitions.some(- (definition) => definition.type === 'VARIANT' && definition.name === name- )- )- .map(([name, values]) => {- const variantOptions = [...values]- return {- id: createComponentPropertyId(),- name,- type: 'VARIANT',- defaultValue: variantOptions[0] ?? '',- variantOptions- }- })-- for (const [id, values] of valuesById) {- graph.updateNode(id, { componentPropertyValues: values })- }- graph.updateNode(componentSetId, {- componentPropertyDefinitions: [...existingDefinitions, ...definitions]- })-}-function findComponentByName(graph: SceneGraph, name: string): SceneNode | undefined {for (const node of graph.getAllNodes()) {if (node.type === 'COMPONENT' && node.name === name) return node@@ -544,11 +482,10 @@ export function elementOverrides(}if (isText) {- const childText = tree.children.filter((c): c is string => typeof c === 'string').join('')- const propText =- props.text ?? props.characters ?? props.content ?? props.label ?? props.value ?? props.title- if (childText) overrides.text = childText- else if (typeof propText === 'string') overrides.text = propText+ // A span's variables give their values; characters keep no bindings of their own.+ const spanOverrides = (spanProps: Record<string, unknown>) =>+ propsToOverrides(preparePropsForRender(graph, spanProps, true, parentId).props, true, 'NONE')+ Object.assign(overrides, textContentFields(tree, props, overrides, spanOverrides))}return { overrides, bindings }}@@ -591,6 +528,8 @@ async function renderNodeContent<Artwork>(})if (reka) return reka+ if (isTextContent(tree))+ throw new Error(`<${TEXT_CONTENT_NAMES[tree.type]}> must be inside <Text>`)const nodeType = TYPE_MAP[tree.type]if (!nodeType) throw new Error(`Unknown element: <${tree.type}>`)@@ -599,7 +538,7 @@ async function renderNodeContent<Artwork>(applyBindings(graph, node.id, bindings)for (const child of tree.children) {- if (typeof child === 'string') continue+ if (typeof child === 'string' || (node.type === 'TEXT' && isTextContent(child))) continueif (isTreeNode(child)) {await renderNode(services, graph, child, node.id, onNode, scope)}diff --git a/packages/design-jsx/src/schema.ts b/packages/design-jsx/src/schema.tsindex b1f43e46f..5aee1666a 100644--- a/packages/design-jsx/src/schema.ts+++ b/packages/design-jsx/src/schema.ts@@ -35,6 +35,16 @@ export type DesignJSXHelperDefinition = DesignJSXNamedDefinitionexport const DESIGN_JSX_ELEMENTS: DesignJSXElementDefinition[] = [{ name: 'Frame', runtimeType: 'frame', description: 'A frame or auto-layout container.' },{ name: 'Text', runtimeType: 'text', description: 'A text layer.' },+ {+ name: 'Span',+ runtimeType: 'text-span',+ description: 'Characters inside a Text, styled apart from the rest.'+ },+ {+ name: 'Paragraph',+ runtimeType: 'text-paragraph',+ description: 'One paragraph of a Text, plain or a list item.'+ },{ name: 'Rectangle', runtimeType: 'rectangle', description: 'A rectangle layer.' },{ name: 'Ellipse', runtimeType: 'ellipse', description: 'An ellipse layer.' },{ name: 'Line', runtimeType: 'line', description: 'A line layer.' },@@ -52,6 +62,33 @@ export const DESIGN_JSX_ELEMENTS: DesignJSXElementDefinition[] = [...rekaElementDefinitions()]+/** Props only `<Paragraph>` takes; like every element, it also takes `key`. */+export const DESIGN_JSX_PARAGRAPH_PROPERTY_NAMES = [+ 'list',+ 'level',+ 'spacing',+ 'listSpacing',+ 'indent'+] as const++/** Props `<Span>` takes: `<Text>`'s character styles, under the same names. */+export const DESIGN_JSX_SPAN_PROPERTY_NAMES = [+ 'style',+ 'size',+ 'fontSize',+ 'font',+ 'fontFamily',+ 'weight',+ 'fontWeight',+ 'italic',+ 'color',+ 'fill',+ 'fills',+ 'lineHeight',+ 'letterSpacing',+ 'textDecoration'+] as const+export const DESIGN_JSX_SUPPORTED_PROPERTY_NAMES = ['name','key',@@ -149,6 +186,11 @@ export const DESIGN_JSX_SUPPORTED_PROPERTY_NAMES = ['letterSpacing','textDecoration','textCase',+ 'list',+ 'level',+ 'spacing',+ 'listSpacing',+ 'indent','maxLines','truncate','grid',diff --git a/packages/design-jsx/src/text-content.ts b/packages/design-jsx/src/text-content.tsnew file mode 100644index 000000000..43fc3a2bd--- /dev/null+++ b/packages/design-jsx/src/text-content.ts@@ -0,0 +1,210 @@+import { isEmptyObject, isEqual, omitBy, pick } from 'es-toolkit'+import * as v from 'valibot'++import {+ createDefaultNode,+ MAX_LIST_INDENTATION,+ paragraphCount,+ PLAIN_PARAGRAPH,+ trimParagraphStyles,+ type CharacterStyleOverride,+ type SceneNode,+ type StyleRun,+ type TextParagraphStyle+} from '@open-pencil/scene-graph'++import { isTreeNode, type TreeNode } from './tree'+import { parseScriptInput } from './validation'++/** `<Span>`: characters of a text styled apart from the rest of it. */+export const SPAN = 'text-span'+/** `<Paragraph>`: one paragraph of a text, with its list and spacing. */+export const PARAGRAPH = 'text-paragraph'++/** The names `<Span>` and `<Paragraph>` are written under, for messages about them. */+export const TEXT_CONTENT_NAMES: Readonly<Partial<Record<string, string>>> = {+ [SPAN]: 'Span',+ [PARAGRAPH]: 'Paragraph'+}++/** The character styles a `<Span>` sets, as the fields `<Text>`'s props set on a text. */+export const SPAN_STYLE_FIELDS = [+ 'fontFamily',+ 'fontSize',+ 'fontWeight',+ 'italic',+ 'fills',+ 'letterSpacing',+ 'lineHeight',+ 'textDecoration'+] as const satisfies readonly (keyof CharacterStyleOverride & keyof SceneNode)[]++export type SpanStyle = Pick<CharacterStyleOverride, (typeof SPAN_STYLE_FIELDS)[number]>++/** The fields an element's props set on a text node, as `propsToOverrides` reads them. */+export type SpanOverrides = (props: Record<string, unknown>) => Partial<SceneNode>++export type TextContentFields = Partial<Pick<SceneNode, 'text' | 'styleRuns' | 'textParagraphs'>>++const Length = v.pipe(v.number(), v.finite())++const ParagraphProps = v.pipe(+ v.object({+ list: v.optional(v.picklist(['ordered', 'unordered'])),+ level: v.optional(+ v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(MAX_LIST_INDENTATION))+ ),+ spacing: v.optional(Length),+ listSpacing: v.optional(Length),+ indent: v.optional(Length)+ }),+ v.check(+ (props) => props.level === undefined || props.list !== undefined,+ '`level` nests list items; set `list` too'+ )+)++/** Characters appended so far, each stretch with the style its spans give it. */+interface Segment {+ length: number+ style: SpanStyle+}++/** Whether a child is `<Span>` or `<Paragraph>`, which are part of their text, not layers. */+export function isTextContent(child: TreeNode | string): boolean {+ return isTreeNode(child) && (child.type === SPAN || child.type === PARAGRAPH)+}++function spanStyle(props: Record<string, unknown>, spanOverrides: SpanOverrides): SpanStyle {+ return omitBy(pick(spanOverrides(props), SPAN_STYLE_FIELDS), (value) => value === undefined)+}++function appendContent(+ segments: Segment[],+ children: TreeNode['children'],+ inherited: SpanStyle,+ owner: string,+ spanOverrides: SpanOverrides+): void {+ for (const child of children) {+ if (typeof child === 'string') {+ segments.push({ length: child.length, style: inherited })+ } else if (child.type === SPAN) {+ // Nested spans style their characters over the span around them.+ const style = { ...inherited, ...spanStyle(child.props, spanOverrides) }+ appendContent(segments, child.children, style, '<Span>', spanOverrides)+ } else if (child.type === PARAGRAPH) {+ throw new Error(`<Paragraph> must be a direct child of <Text>, not of ${owner}`)+ } else {+ throw new Error(`${owner} can hold only text and <Span>, not <${child.type}>`)+ }+ }+}++function textOf(children: TreeNode['children']): string {+ return children+ .map((child) => (typeof child === 'string' ? child : textOf(child.children)))+ .join('')+}++function paragraphStyle(props: Record<string, unknown>): TextParagraphStyle {+ const { list, level, spacing, listSpacing, indent } = parseScriptInput(+ 'Invalid <Paragraph> props',+ ParagraphProps,+ props+ )+ const style: TextParagraphStyle = list+ ? { listType: list === 'ordered' ? 'ORDERED' : 'UNORDERED', indentation: level ?? 1 }+ : { ...PLAIN_PARAGRAPH }+ if (spacing !== undefined) style.paragraphSpacing = spacing+ if (listSpacing !== undefined) style.listSpacing = listSpacing+ if (indent !== undefined) style.paragraphIndent = indent+ return style+}++/** The `<Paragraph>` children of a text, or null without any; other content beside them is an error. */+function paragraphElements(tree: TreeNode): TreeNode[] | null {+ const paragraphs = tree.children.filter(+ (child): child is TreeNode => isTreeNode(child) && child.type === PARAGRAPH+ )+ if (paragraphs.length === 0) return null+ const mixed = tree.children.some((child) =>+ typeof child === 'string' ? child.trim() !== '' : child.type !== PARAGRAPH+ )+ if (mixed) {+ throw new Error(+ '<Text> mixes <Paragraph> with other content: put all of its text in <Paragraph> elements, or use none'+ )+ }+ return paragraphs+}++/** Runs for the segments, holding only what differs from the text's own style. */+function styleRuns(segments: readonly Segment[], textStyle: SpanStyle): StyleRun[] {+ const runs: StyleRun[] = []+ let start = 0+ for (const segment of segments) {+ const style = omitBy(segment.style, (value, key) => isEqual(value, textStyle[key]))+ if (segment.length > 0 && !isEmptyObject(style)) {+ const previous = runs.at(-1)+ const adjoins = previous && previous.start + previous.length === start+ if (adjoins && isEqual(previous.style, style)) previous.length += segment.length+ else runs.push({ start, length: segment.length, style })+ }+ start += segment.length+ }+ return runs+}++/** The style of the last character appended, which a newline after it takes, as in Figma. */+function lastStyle(segments: readonly Segment[]): SpanStyle {+ return segments.findLast((segment) => segment.length > 0)?.style ?? {}+}++/**+ * The text a `<Text>` element's children and text props give. Strings alone are its text, as+ * before; `<Span>` children also give style runs and `<Paragraph>` children paragraph styles.+ * `overrides` are the text's own fields, which runs leave out.+ */+export function textContentFields(+ tree: TreeNode,+ props: Record<string, unknown>,+ overrides: Partial<SceneNode>,+ spanOverrides: SpanOverrides+): TextContentFields {+ if (!tree.children.some(isTextContent)) {+ const childText = tree.children.filter((c): c is string => typeof c === 'string').join('')+ const propText =+ props.text ?? props.characters ?? props.content ?? props.label ?? props.value ?? props.title+ if (childText) return { text: childText }+ return typeof propText === 'string' ? { text: propText } : {}+ }++ const textStyle = pick(+ createDefaultNode(() => '', 'TEXT', overrides),+ SPAN_STYLE_FIELDS+ )+ const segments: Segment[] = []+ const paragraphs = paragraphElements(tree)+ if (!paragraphs) {+ appendContent(segments, tree.children, {}, '<Text>', spanOverrides)+ return { text: textOf(tree.children), styleRuns: styleRuns(segments, textStyle) }+ }++ const styles: TextParagraphStyle[] = []+ const lines: string[] = []+ for (const paragraph of paragraphs) {+ if (lines.length > 0) segments.push({ length: 1, style: lastStyle(segments) })+ appendContent(segments, paragraph.children, {}, '<Paragraph>', spanOverrides)+ const content = textOf(paragraph.children)+ // A line break inside a paragraph's text starts paragraphs of the same style.+ const style = paragraphStyle(paragraph.props)+ for (let index = 0; index < paragraphCount(content); index++) styles.push(style)+ lines.push(content)+ }+ return {+ text: lines.join('\n'),+ styleRuns: styleRuns(segments, textStyle),+ textParagraphs: trimParagraphStyles(styles, styles.length)+ }+}diff --git a/packages/design-jsx/src/tree.ts b/packages/design-jsx/src/tree.tsindex bec0c8da3..b481f92ae 100644--- a/packages/design-jsx/src/tree.ts+++ b/packages/design-jsx/src/tree.ts@@ -187,6 +187,39 @@ type NodeProps = StyleProps & {export type BaseProps = NodeProps & { properties?: never }export type TextProps = BaseProps+/** A `<Span>`'s props: the character styles of `<Text>`, under the same names. */+export type SpanProps = Pick<+ StyleProps,+ | 'size'+ | 'fontSize'+ | 'font'+ | 'fontFamily'+ | 'weight'+ | 'fontWeight'+ | 'color'+ | 'fill'+ | 'fills'+ | 'lineHeight'+ | 'letterSpacing'+> & {+ key?: string | number+ style?: Record<string, unknown>+ italic?: boolean+ textDecoration?: 'none' | 'underline' | 'strikethrough'+ children?: unknown+}++/** A `<Paragraph>`'s props: a list item at `level` 1–5, or a plain paragraph, and its spacing. */+export type ParagraphProps = {+ key?: string | number+ list?: 'ordered' | 'unordered'+ level?: number+ spacing?: number+ listSpacing?: number+ indent?: number+ children?: unknown+}+export type ComponentProps = NodeProps & {properties?: SceneNode['componentPropertyDefinitions']}diff --git a/packages/design-jsx/tests/export/text.test.ts b/packages/design-jsx/tests/export/text.test.tsnew file mode 100644index 000000000..a224134ed--- /dev/null+++ b/packages/design-jsx/tests/export/text.test.ts@@ -0,0 +1,91 @@+import { describe, expect, test } from 'bun:test'++import { sceneNodeToJSX } from '#design-jsx/index'++import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'+import { colorToFill } from '@open-pencil/scene-graph/color'++function exportText(fields: Partial<SceneNode>): string {+ const graph = new SceneGraph()+ const node = graph.createNode('TEXT', graph.getPages()[0].id, {+ name: 'Note',+ textAutoResize: 'WIDTH_AND_HEIGHT',+ fills: [],+ ...fields+ })+ return sceneNodeToJSX(node.id, graph)+}++describe('rich text export', () => {+ test('writes styled characters as spans with only what differs', () => {+ const code = exportText({+ text: 'Hello world!',+ fontWeight: 700,+ styleRuns: [+ { start: 6, length: 5, style: { fontWeight: 700, fills: [colorToFill('#EE2222')] } }+ ]+ })+ expect(code).toBe(+ '<Text name="Note" weight="bold">Hello <Span color="#EE2222">world</Span>!</Text>'+ )+ })++ test('writes every character style under its Text prop name', () => {+ const code = exportText({+ text: 'ab',+ styleRuns: [+ {+ start: 0,+ length: 1,+ style: {+ fontSize: 20,+ fontFamily: 'Roboto',+ fontWeight: 500,+ italic: true,+ lineHeight: 30,+ letterSpacing: 1,+ textDecoration: 'STRIKETHROUGH'+ }+ },+ { start: 1, length: 1, style: { italic: false } }+ ]+ })+ expect(code).toBe(+ '<Text name="Note"><Span size={20} font="Roboto" weight="medium" italic lineHeight={30} letterSpacing={1} textDecoration="strikethrough">a</Span>b</Text>'+ )+ })++ test('writes paragraphs when one is a list item or spaced', () => {+ const code = exportText({+ text: 'Intro\nFirst\nNested',+ textParagraphs: [+ { listType: 'NONE', indentation: 0, paragraphSpacing: 12 },+ { listType: 'ORDERED', indentation: 1 },+ { listType: 'ORDERED', indentation: 2, listSpacing: 4, paragraphIndent: 8 }+ ],+ styleRuns: [{ start: 6, length: 5, style: { fontWeight: 700 } }]+ })+ expect(code).toBe(`<Text name="Note">+ <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('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>')+ })++ test('writes plain text as before', () => {+ const code = exportText({+ text: 'One\nTwo',+ textParagraphs: [{ listType: 'NONE', indentation: 0 }],+ styleRuns: [{ start: 0, length: 3, style: { fontWeight: 400 } }]+ })+ expect(code).toBe('<Text name="Note">{"One\\nTwo"}</Text>')+ })+})diff --git a/packages/design-jsx/tests/jsx-runtime.test.tsx b/packages/design-jsx/tests/jsx-runtime.test.tsxindex 59460effc..714ac9d6d 100644--- a/packages/design-jsx/tests/jsx-runtime.test.tsx+++ b/packages/design-jsx/tests/jsx-runtime.test.tsx@@ -1,7 +1,7 @@/** @jsxImportSource @open-pencil/design-jsx */import { describe, expect, test } from 'bun:test'-import { Frame, Text, solid, type TreeNode } from '#design-jsx/index'+import { Frame, Paragraph, Span, Text, solid, type TreeNode } from '#design-jsx/index'describe('JSX runtime', () => {test('builds the same tree as the element functions', () => {@@ -38,4 +38,25 @@ describe('JSX runtime', () => {)expect(tree.children).toEqual([Text({ children: 'One' }), Text({ children: 'Two' })])})++ test('builds rich text from spans and paragraphs', () => {+ const tree = (+ <Text size={24}>+ <Paragraph list="ordered" level={2}>+ Hello <Span weight={700}>world</Span>+ </Paragraph>+ </Text>+ )+ expect(tree).toEqual({+ type: 'text',+ props: { size: 24 },+ children: [+ {+ type: 'text-paragraph',+ props: { list: 'ordered', level: 2 },+ children: ['Hello ', { type: 'text-span', props: { weight: 700 }, children: ['world'] }]+ }+ ]+ })+ })})diff --git a/packages/design-jsx/tests/layer-order.test.ts b/packages/design-jsx/tests/layer-order.test.tsindex ceac5111c..772011a90 100644--- a/packages/design-jsx/tests/layer-order.test.ts+++ b/packages/design-jsx/tests/layer-order.test.ts@@ -26,11 +26,33 @@ describe('Design JSX layer order', () => {expect(result.layerIds).toEqual([card.id, title.id, hidden.id, row.id, dot.id, badge.id])expect(openingTagNames(result.code)).toEqual(result.layerIds.map((id) => {- const node = graph.getNode(id)+ const node = id === null ? undefined : graph.getNode(id)if (!node) throw new Error(`Missing layer ${id}`)return node.name}))expect(result.code).toBe(selectionToJSX([card.id, badge.id], graph))})++ test('lists rich text spans and paragraphs as elements without a layer', () => {+ const graph = new SceneGraph()+ const pageId = graph.getPages()[0].id+ const card = graph.createNode('FRAME', pageId, { name: 'Card', width: 200, height: 100 })+ const text = graph.createNode('TEXT', card.id, {+ name: 'Rich',+ text: 'Bold\nItem',+ styleRuns: [{ start: 0, length: 4, style: { fontWeight: 700 } }],+ textParagraphs: [+ { listType: 'NONE', indentation: 0 },+ { listType: 'UNORDERED', indentation: 1 }+ ]+ })+ const after = graph.createNode('RECTANGLE', card.id, { name: 'After', width: 8, height: 8 })++ const { code, layerIds } = selectionToJSXWithLayers([card.id], graph)++ // Two paragraphs and the span in the first: the layer after them keeps its own element.+ expect(layerIds).toEqual([card.id, text.id, null, null, null, after.id])+ expect(code.match(/<(?!\/)[A-Za-z]/g)).toHaveLength(layerIds.length)+ })})diff --git a/packages/design-jsx/tests/schema.test.ts b/packages/design-jsx/tests/schema.test.tsindex 5f2158218..42bc01af4 100644--- a/packages/design-jsx/tests/schema.test.ts+++ b/packages/design-jsx/tests/schema.test.ts@@ -1,6 +1,10 @@import { describe, expect, test } from 'bun:test'-import { DESIGN_JSX_SUPPORTED_PROPERTIES, transformDesignJSXExpression } from '#design-jsx/index'+import {+ DESIGN_JSX_ELEMENTS,+ DESIGN_JSX_SUPPORTED_PROPERTIES,+ transformDesignJSXExpression+} from '#design-jsx/index'describe('Design JSX schema', () => {test('includes renderer compatibility properties', () => {@@ -15,6 +19,18 @@ describe('Design JSX schema', () => {expect(DESIGN_JSX_SUPPORTED_PROPERTIES.has(property)).toBe(true)}})++ test('lists the rich text elements and their props', () => {+ expect(DESIGN_JSX_ELEMENTS).toContainEqual(+ expect.objectContaining({ name: 'Span', runtimeType: 'text-span' })+ )+ expect(DESIGN_JSX_ELEMENTS).toContainEqual(+ expect.objectContaining({ name: 'Paragraph', runtimeType: 'text-paragraph' })+ )+ for (const property of ['list', 'level', 'spacing', 'listSpacing', 'indent']) {+ expect(DESIGN_JSX_SUPPORTED_PROPERTIES.has(property)).toBe(true)+ }+ })})describe('Design JSX transform', () => {diff --git a/packages/design-jsx/tests/streaming.test.ts b/packages/design-jsx/tests/streaming.test.tsindex e04ddae09..100b576cd 100644--- a/packages/design-jsx/tests/streaming.test.ts+++ b/packages/design-jsx/tests/streaming.test.ts@@ -89,7 +89,8 @@ describe('streaming Design JSX', () => {'<Frame name="hello "world"" />','<><Text>One</Text><Text>Two</Text></>','<Frame><><Text>One</Text><Text>Two</Text></></Frame>',- '<svg viewBox="0 0 24 24"><path d="M0 0L2 2" /></svg>'+ '<svg viewBox="0 0 24 24"><path d="M0 0L2 2" /></svg>',+ '<Text><Paragraph list="ordered">Hello <Span weight={700}>bold</Span> world</Paragraph></Text>']it.each(fixtures)('matches complete JSX semantics: %s', (source) => {diff --git a/packages/design-jsx/tests/text-content.test.ts b/packages/design-jsx/tests/text-content.test.tsnew file mode 100644index 000000000..4f15664d2--- /dev/null+++ b/packages/design-jsx/tests/text-content.test.ts@@ -0,0 +1,168 @@+import { describe, expect, test } from 'bun:test'++import { createDesignJSXRenderer } from '#design-jsx/index'++import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'+import { colorToFill } from '@open-pencil/scene-graph/color'++const renderer = createDesignJSXRenderer<never>({+ icon: () => Promise.resolve(null),+ svg: () => null,+ createArtwork: () => {+ throw new Error('No artwork in these tests')+ },+ layout: () => {+ // Text content does not depend on layout.+ }+})++async function renderText(source: string): Promise<{ node: SceneNode; warnings: string[] }> {+ const graph = new SceneGraph()+ const [result] = await renderer.renderJSX(graph, source)+ const node = graph.getNode(result.id)+ if (!node) throw new Error('Rendered text is missing')+ return { node, warnings: result.warnings ?? [] }+}++describe('Span', () => {+ test('styles its characters with what differs from the text', async () => {+ const { node } = await renderText(+ '<Text size={24} weight="bold">Hello <Span weight="bold" size={24} color="#EE2222">world</Span>!</Text>'+ )+ expect(node.text).toBe('Hello world!')+ expect(node.fontWeight).toBe(700)+ expect(node.styleRuns).toEqual([+ { start: 6, length: 5, style: { fills: [colorToFill('#EE2222')] } }+ ])+ })++ test('takes the text props a character can have, under the same names', async () => {+ const { node, warnings } = await renderText(+ '<Text><Span font="Roboto" fontSize={20} fontWeight={600} italic lineHeight={30} letterSpacing={1} textDecoration="underline">a</Span></Text>'+ )+ expect(node.styleRuns[0]?.style).toEqual({+ fontFamily: 'Roboto',+ fontSize: 20,+ fontWeight: 600,+ italic: true,+ lineHeight: 30,+ letterSpacing: 1,+ textDecoration: 'UNDERLINE'+ })+ expect(warnings).toEqual([])+ })++ 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>'+ )+ expect(node.text).toBe('abc')+ expect(node.styleRuns).toEqual([+ { start: 0, length: 1, style: { fontWeight: 700 } },+ { start: 1, length: 1, style: { fontWeight: 300, italic: true } }+ ])+ })++ test('joins neighbouring spans of the same style into one run', async () => {+ const { node } = await renderText(+ '<Text><Span weight={700}>a</Span><Span weight={700}>b</Span></Text>'+ )+ expect(node.styleRuns).toEqual([{ start: 0, length: 2, style: { fontWeight: 700 } }])+ })++ test('warns about props that are not character styles', async () => {+ const { warnings } = await renderText('<Text><Span w={20}>a</Span></Text>')+ expect(warnings).toEqual(['Unsupported prop "w" on <Span> is ignored.'])+ })++ test('must be inside a text', async () => {+ await expect(renderText('<Frame><Span>a</Span></Frame>')).rejects.toThrow(+ '<Span> must be inside <Text>'+ )+ })++ test('holds only text and spans', async () => {+ await expect(renderText('<Text><Span><Frame /></Span></Text>')).rejects.toThrow(+ '<Span> can hold only text and <Span>, not <frame>'+ )+ })+})++describe('Paragraph', () => {+ test('makes paragraphs with list and spacing styles', async () => {+ const { node } = await renderText(`<Text size={24}>+ <Paragraph spacing={12}>Hello <Span weight={700}>world</Span></Paragraph>+ <Paragraph list="ordered">First</Paragraph>+ <Paragraph list="ordered" level={2} listSpacing={4} indent={8}>Nested</Paragraph>+ <Paragraph list="unordered">Dot</Paragraph>+</Text>`)+ expect(node.text).toBe('Hello world\nFirst\nNested\nDot')+ expect(node.textParagraphs).toEqual([+ { listType: 'NONE', indentation: 0, paragraphSpacing: 12 },+ { listType: 'ORDERED', indentation: 1 },+ { listType: 'ORDERED', indentation: 2, listSpacing: 4, paragraphIndent: 8 },+ { listType: 'UNORDERED', indentation: 1 }+ ])+ // The newline after a bold word is bold too, as Figma styles a newline like the character before.+ expect(node.styleRuns).toEqual([{ start: 6, length: 6, style: { fontWeight: 700 } }])+ })++ test('leaves plain paragraphs at the end out', async () => {+ const { node } = await renderText(+ '<Text><Paragraph list="unordered">a</Paragraph><Paragraph>b</Paragraph><Paragraph /></Text>'+ )+ expect(node.text).toBe('a\nb\n')+ expect(node.textParagraphs).toEqual([{ listType: 'UNORDERED', indentation: 1 }])+ })++ test('gives each line of its text its style', async () => {+ const { node } = await renderText(+ `<Text><Paragraph list="unordered">{'a\\nb'}</Paragraph><Paragraph list="ordered">c</Paragraph></Text>`+ )+ expect(node.text).toBe('a\nb\nc')+ expect(node.textParagraphs.map((paragraph) => paragraph.listType)).toEqual([+ 'UNORDERED',+ 'UNORDERED',+ 'ORDERED'+ ])+ })++ test('cannot share a text with other content', async () => {+ await expect(renderText('<Text>Intro<Paragraph>a</Paragraph></Text>')).rejects.toThrow(+ '<Text> mixes <Paragraph> with other content'+ )+ await expect(renderText('<Text><Span>a</Span><Paragraph>b</Paragraph></Text>')).rejects.toThrow(+ '<Text> mixes <Paragraph> with other content'+ )+ })++ test('is a direct child of a text', async () => {+ await expect(+ renderText('<Text><Paragraph><Paragraph>a</Paragraph></Paragraph></Text>')+ ).rejects.toThrow('<Paragraph> must be a direct child of <Text>, not of <Paragraph>')+ await expect(renderText('<Frame><Paragraph>a</Paragraph></Frame>')).rejects.toThrow(+ '<Paragraph> must be inside <Text>'+ )+ })++ test('rejects levels it cannot nest', async () => {+ await expect(+ renderText('<Text><Paragraph list="ordered" level={6}>a</Paragraph></Text>')+ ).rejects.toThrow('Invalid <Paragraph> props')+ await expect(renderText('<Text><Paragraph level={2}>a</Paragraph></Text>')).rejects.toThrow(+ '`level` nests list items; set `list` too'+ )+ })++ test('props are not layer props', async () => {+ const { warnings } = await renderText('<Text spacing={4}>a</Text>')+ expect(warnings).toEqual(['Unsupported prop "spacing" on <text> is ignored.'])+ })+})++test('a text without spans or paragraphs keeps its text as before', async () => {+ const { node } = await renderText('<Text>{"One\\nTwo"}</Text>')+ expect(node.text).toBe('One\nTwo')+ expect(node.styleRuns).toEqual([])+ expect(node.textParagraphs).toEqual([])+})diff --git a/packages/docs/programmable/cli/scripting.md b/packages/docs/programmable/cli/scripting.mdindex 5a6327b0b..531a512d7 100644--- a/packages/docs/programmable/cli/scripting.md+++ b/packages/docs/programmable/cli/scripting.md@@ -194,7 +194,8 @@ Common node properties are readable/writable through the proxy, including:- Geometry: `x`, `y`, `width`, `height`, `rotation`, `resize(width, height)`- Appearance: `fills`, `strokes`, `effects`, `opacity`, `visible`, `locked`, `blendMode`, `clipsContent`- Radius: `cornerRadius`, `topLeftRadius`, `topRightRadius`, `bottomRightRadius`, `bottomLeftRadius`-- Text: `characters`, `fontSize`, `fontName`, `fontWeight`, alignment, line height, letter spacing, style-run helpers+- Text: `characters`, `fontSize`, `fontName`, `fontWeight`, `fills`, `letterSpacing`, `lineHeight`, and `textDecoration`, which read `figma.mixed` while characters differ and restyle every character when set, and alignment+- Text ranges: `getStyledTextSegments(fields, start?, end?)`, and `getRange…` / `setRange…` for `FontSize`, `FontName`, `Fills`, `LetterSpacing`, `LineHeight`, `TextDecoration` with its `Style`, `Offset`, `Thickness`, `Color`, and `SkipInk`, plus `getRangeFontWeight`, `getRangeAllFontNames`, and `getRangeOpenTypeFeatures`. Lengths read in pixels; a percent given to a setter is of the font size- Text lists and paragraphs: `getRangeListOptions` / `setRangeListOptions` for bulleted (`UNORDERED`) and numbered (`ORDERED`) items, `getRangeIndentation` / `setRangeIndentation` for nesting (1–5 for list items), `listSpacing`, `paragraphSpacing`, and `paragraphIndent` for the whole text (`figma.mixed` when paragraphs differ) or per paragraph with `getRangeListSpacing` / `setRangeListSpacing`, `getRangeParagraphSpacing` / `setRangeParagraphSpacing`, and `getRangeParagraphIndent` / `setRangeParagraphIndent`, and `hangingList`- Auto-layout: `layoutMode`, `primaryAxisAlignItems`, `counterAxisAlignItems`, `itemSpacing`, padding, sizing, and layout positioning fields- Stroke helpers: `strokeWeight`, `strokeAlign`, `dashPattern`diff --git a/packages/docs/reference/design-authoring.md b/packages/docs/reference/design-authoring.mdindex 2d4945160..f19e58542 100644--- a/packages/docs/reference/design-authoring.md+++ b/packages/docs/reference/design-authoring.md@@ -25,6 +25,7 @@ This reference describes scene creation, not React DOM output. Use the `render`- `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.- `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.@@ -83,12 +84,25 @@ The examples below are executed by the authoring-reference tests. Create the nam</Frame>```+## Rich text with spans and lists++```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>+ <Paragraph list="unordered">Faster export</Paragraph>+ <Paragraph list="unordered" level={2}>PDF and SVG</Paragraph>+ <Paragraph list="ordered">Fewer clicks</Paragraph>+</Text>+</Frame>+```+## Supported syntax inventoryGenerated from the renderer metadata. This inventory lists accepted names, not arbitrary browser CSS support.-**Elements:** `Frame`, `Text`, `Rectangle`, `Ellipse`, `Line`, `Star`, `Polygon`, `Vector`, `Group`, `Section`, `Component`, `ComponentSet`, `Instance`, `View`, `Rect`, `Icon`, `Button.Root`, `Toggle.Root`, `Switch.Root`, `Switch.Thumb`, `Checkbox.Root`, `Checkbox.Indicator`, `RadioGroup.Root`, `RadioGroup.Item`, `RadioGroup.Indicator`, `ToggleGroup.Root`, `ToggleGroup.Item`, `Slider.Root`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Progress.Root`, `Progress.Track`, `Progress.Indicator`, `Tabs.Root`, `Tabs.List`, `Tabs.Trigger`, `Tabs.Content`, `Collapsible.Root`, `Collapsible.Trigger`, `Collapsible.Content`, `Accordion.Root`, `Accordion.Item`, `Accordion.Header`, `Accordion.Trigger`, `Accordion.Content`, `NumberField.Root`, `NumberField.Input`, `NumberField.Increment`, `NumberField.Decrement`, `TextField.Root`, `TextField.Input`, `Textarea.Root`, `Textarea.Input`.+**Elements:** `Frame`, `Text`, `Span`, `Paragraph`, `Rectangle`, `Ellipse`, `Line`, `Star`, `Polygon`, `Vector`, `Group`, `Section`, `Component`, `ComponentSet`, `Instance`, `View`, `Rect`, `Icon`, `Button.Root`, `Toggle.Root`, `Switch.Root`, `Switch.Thumb`, `Checkbox.Root`, `Checkbox.Indicator`, `RadioGroup.Root`, `RadioGroup.Item`, `RadioGroup.Indicator`, `ToggleGroup.Root`, `ToggleGroup.Item`, `Slider.Root`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Progress.Root`, `Progress.Track`, `Progress.Indicator`, `Tabs.Root`, `Tabs.List`, `Tabs.Trigger`, `Tabs.Content`, `Collapsible.Root`, `Collapsible.Trigger`, `Collapsible.Content`, `Accordion.Root`, `Accordion.Item`, `Accordion.Header`, `Accordion.Trigger`, `Accordion.Content`, `NumberField.Root`, `NumberField.Input`, `NumberField.Increment`, `NumberField.Decrement`, `TextField.Root`, `TextField.Input`, `Textarea.Root`, `Textarea.Input`.**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`, `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`, `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 filediff --git a/packages/dom-css/AGENTS.md b/packages/dom-css/AGENTS.mdindex 13e4b53b9..9a0aaebca 100644--- a/packages/dom-css/AGENTS.md+++ b/packages/dom-css/AGENTS.md@@ -16,3 +16,4 @@ Rules:- Imported documents are untrusted: check Base64 with `js-base64`'s `isValid` before decoding.- Import maps CSS flow onto the auto layout semantics in `@open-pencil/scene-graph` from `src/import/flow.ts`: an element's display comes from CSS or its tag's default, block flow stacks and stretches block-level children, flex items stretch across by default, and padding and borders sit outside an explicit size unless `box-sizing: border-box`. It records fill and hug and never sizes text; Core measures and lays out what it builds (`packages/dom-css/tests/import/flow.test.ts`).- `./scene-graph` is the browser-safe entry for building layers from a styled DOM. The main entry carries the headless CSS runtime, whose CSSOM dependency has no browser build with the exports it uses, so browser bundles must not import it.+- Rich text maps one way in both directions: style runs are spans that set only what differs from the text, text with lists, paragraph spacing, or a first-line indent is blocks of `<p>`, `<ul>`, and `<ol>` with Figma's markers and the space after each paragraph as a margin, and on import inline content or box-less text blocks in normal flow join into one text layer while a flex box's children stay apart (`src/export/text.ts`, `src/import/text.ts`, `packages/dom-css/tests/import/text.test.ts`).diff --git a/packages/dom-css/src/export/projection.ts b/packages/dom-css/src/export/projection.tsindex 11e6aeda2..530a06f47 100644--- a/packages/dom-css/src/export/projection.ts+++ b/packages/dom-css/src/export/projection.ts@@ -14,6 +14,7 @@ import { DesignTokens, type CSSModes } from '../tokens/references'import type { DesignDocument, DesignElement, DesignNode, DesignStyleDeclaration } from '../types'import { cssColor, dropShadowToCSS, effectsToCSS, fillToCSS, strokeColorToCSS } from './css'import { addGridContainer, addGridPlacement } from './grid'+import { textElementContent } from './text'const DOM_CSS_PLUGIN_ID = 'open-pencil-dom-css'const IMAGE_SOURCE_URL_KEY = 'image-source-url'@@ -456,14 +457,15 @@ function sceneNodeToDesignNode(const css: FieldCSS = (field, literal) => tokens?.reference(node, field, modes) ?? literalif (node.type === 'TEXT') {+ const content = textElementContent(node, styleFromTextNode(node, parent, css))return {type: 'element',- tagName: 'span',+ tagName: content.tagName,attrs,- inlineStyle: styleFromTextNode(node, parent, css),+ inlineStyle: content.style,sourceSceneNodeId: node.id,sourceSceneNode: node,- children: [{ type: 'text', text: node.text }]+ children: content.children}}diff --git a/packages/dom-css/src/export/tailwind-jsx.ts b/packages/dom-css/src/export/tailwind-jsx.tsindex 5af62e3e8..7b67660cc 100644--- a/packages/dom-css/src/export/tailwind-jsx.ts+++ b/packages/dom-css/src/export/tailwind-jsx.ts@@ -25,9 +25,12 @@ function jsxAttributeName(name: string): string {return name.replace(/-([a-z])/g, (_, letter: string) => letter.toUpperCase())}-/** Scene text layers become paragraphs; Tailwind's preflight removes their margins. */+/**+ * Scene text layers become paragraphs, whose margins Tailwind's preflight removes; text laid+ * out in blocks keeps the `<div>` that holds them.+ */function tagName(node: DesignElement): string {- return node.sourceSceneNode?.type === 'TEXT' ? 'p' : node.tagName+ return node.sourceSceneNode?.type === 'TEXT' && node.tagName === 'span' ? 'p' : node.tagName}function attributes(node: DesignElement, themeVariables: readonly string[]): SyntaxNode[] {diff --git a/packages/dom-css/src/export/text.ts b/packages/dom-css/src/export/text.tsnew file mode 100644index 000000000..4633cf67e--- /dev/null+++ b/packages/dom-css/src/export/text.ts@@ -0,0 +1,372 @@+import { isEqual } from 'es-toolkit/predicate'++import {+ hasTextList,+ listNumberFormat,+ paragraphSpacingAt,+ paragraphStyleAt,+ textListItems,+ textParagraphRanges,+ type CharacterStyleOverride,+ type SceneNode,+ type TextListItem,+ type TextParagraphRange+} from '@open-pencil/scene-graph'++import type { DesignElement, DesignNode, DesignStyleDeclaration } from '../types'+import { fillToCSS } from './css'++/** The character styles CSS writes, as a text layer and its runs hold them. */+type CharacterStyle = Pick<+ SceneNode,+ | 'fontFamily'+ | 'fontSize'+ | 'fontWeight'+ | 'italic'+ | 'letterSpacing'+ | 'lineHeight'+ | 'fills'+ | 'textDecoration'+ | 'textDecorationStyle'+ | 'textDecorationThickness'+ | 'textDecorationFills'+ | 'textDecorationSkipInk'+ | 'textUnderlineOffset'+>++type CharacterStyleKey = keyof CharacterStyle++const CHARACTER_STYLE_KEYS: readonly CharacterStyleKey[] = [+ 'fontFamily',+ 'fontSize',+ 'fontWeight',+ 'italic',+ 'letterSpacing',+ 'lineHeight',+ 'fills',+ 'textDecoration',+ 'textDecorationStyle',+ 'textDecorationThickness',+ 'textDecorationFills',+ 'textDecorationSkipInk',+ 'textUnderlineOffset'+]++/** A list's indent per level, in ems of its first character, as the canvas lays lists out. */+const LIST_INDENT_EMS = 1.5++const DECORATION_PROPERTIES = new Set([+ 'text-decoration-line',+ 'text-decoration-style',+ 'text-decoration-color',+ 'text-decoration-thickness',+ 'text-underline-offset',+ 'text-decoration-skip-ink'+])++const px = (value: number) => `${value}px`++/** Characters `[start, end)` and the run style over them. */+interface StyledRange {+ start: number+ end: number+ style: CharacterStyle+}++function characterStyle(node: SceneNode, override: CharacterStyleOverride = {}): CharacterStyle {+ const style = Object.fromEntries(CHARACTER_STYLE_KEYS.map((key) => [key, node[key]]))+ for (const key of CHARACTER_STYLE_KEYS) {+ const value = override[key]+ if (value !== undefined) style[key] = value+ }+ return style as CharacterStyle+}++/** The text in ranges of one style each: the runs, and the layer's own style between them. */+function styledRanges(node: SceneNode): StyledRange[] {+ const ranges: StyledRange[] = []+ const base = characterStyle(node)+ let at = 0+ for (const run of node.styleRuns.toSorted((a, b) => a.start - b.start)) {+ const start = Math.max(at, run.start)+ const end = Math.min(node.text.length, run.start + run.length)+ if (start > at) ranges.push({ start: at, end: start, style: base })+ if (end > start) ranges.push({ start, end, style: characterStyle(node, run.style) })+ at = Math.max(at, end)+ }+ if (at < node.text.length) ranges.push({ start: at, end: node.text.length, style: base })+ return ranges+}++/** Underline or strikethrough as CSS writes it: Figma's offset is CSS's, from the baseline. */+function decorationCSS(style: CharacterStyle): DesignStyleDeclaration {+ if (style.textDecoration === 'NONE') return {}+ const underline = style.textDecoration === 'UNDERLINE'+ const css: DesignStyleDeclaration = {+ 'text-decoration-line': underline ? 'underline' : 'line-through'+ }+ if (style.textDecorationStyle !== 'SOLID') {+ css['text-decoration-style'] = style.textDecorationStyle.toLowerCase()+ }+ const color = fillToCSS(style.textDecorationFills.find((fill) => fill.visible))+ if (color) css['text-decoration-color'] = color+ if (style.textDecorationThickness !== null) {+ css['text-decoration-thickness'] = px(style.textDecorationThickness)+ }+ if (underline && style.textUnderlineOffset !== null) {+ css['text-underline-offset'] = px(style.textUnderlineOffset)+ }+ if (underline && !style.textDecorationSkipInk) css['text-decoration-skip-ink'] = 'none'+ return css+}++function characterCSS(style: CharacterStyle, decorated: boolean): DesignStyleDeclaration {+ return {+ color: fillToCSS(style.fills.at(0)) ?? '',+ 'font-family': style.fontFamily,+ 'font-size': px(style.fontSize),+ 'font-weight': String(style.fontWeight),+ 'font-style': style.italic ? 'italic' : 'normal',+ 'letter-spacing': px(style.letterSpacing),+ 'line-height': style.lineHeight === null ? 'normal' : px(style.lineHeight),+ ...(decorated ? decorationCSS(style) : {})+ }+}++/** What `css` sets differently from `base`. */+function differing(+ css: DesignStyleDeclaration,+ base: DesignStyleDeclaration+): DesignStyleDeclaration {+ return Object.fromEntries(+ Object.entries(css).filter(([property, value]) => value !== '' && base[property] !== value)+ )+}++/**+ * Whether the text decorates every character alike. CSS draws an element's decoration through+ * its descendants, which cannot take it off, so mixed decorations go on the spans instead.+ */+function uniformDecoration(node: SceneNode, ranges: readonly StyledRange[]): boolean {+ const decorations = ranges+ .filter((range) => node.text.slice(range.start, range.end).replaceAll('\n', '') !== '')+ .map((range) => decorationCSS(range.style))+ return decorations.every((decoration) => isEqual(decoration, decorations[0]))+}++interface TextProjection {+ node: SceneNode+ ranges: StyledRange[]+ base: DesignStyleDeclaration+ decorated: boolean+}++function textNode(text: string): DesignNode {+ return { type: 'text', text }+}++function element(+ tagName: string,+ inlineStyle: DesignStyleDeclaration,+ children: DesignNode[]+): DesignElement {+ return { type: 'element', tagName, attrs: {}, inlineStyle, children }+}++/** `text[start, end)` as text and spans, each span setting only what differs from the layer. */+function inlineContent(projection: TextProjection, start: number, end: number): DesignNode[] {+ const { node, ranges, base, decorated } = projection+ const pieces: { css: DesignStyleDeclaration; text: string }[] = []+ for (const range of ranges) {+ const from = Math.max(start, range.start)+ const to = Math.min(end, range.end)+ if (to <= from) continue+ const css = differing(characterCSS(range.style, !decorated), base)+ const text = node.text.slice(from, to)+ const previous = pieces.at(-1)+ if (previous && isEqual(previous.css, css)) previous.text += text+ else pieces.push({ css, text })+ }+ return pieces.map(({ css, text }) =>+ Object.keys(css).length === 0 ? textNode(text) : element('span', css, [textNode(text)])+ )+}++/** A paragraph's content; an empty one holds a line break, which gives it a line's height. */+function paragraphContent(projection: TextProjection, range: TextParagraphRange): DesignNode[] {+ if (range.end === range.start) return [element('br', {}, [])]+ return inlineContent(projection, range.start, range.end)+}++/** Text that CSS lays out in one element: no lists, and no spacing or indent between lines. */+function needsBlocks(node: SceneNode): boolean {+ if (hasTextList(node)) return true+ const paragraphs = textParagraphRanges(node.text)+ return paragraphs.some(+ (_, index) =>+ paragraphSpacingAt(node, index, 'paragraphIndent') > 0 ||+ (index < paragraphs.length - 1 && paragraphSpacingAt(node, index, 'paragraphSpacing') > 0)+ )+}++/** The space after paragraph `index`: list spacing between two items, paragraph spacing else. */+function spaceAfter(node: SceneNode, index: number, count: number): number {+ if (index >= count - 1) return 0+ const betweenItems =+ paragraphStyleAt(node.textParagraphs, index).listType !== 'NONE' &&+ paragraphStyleAt(node.textParagraphs, index + 1).listType !== 'NONE'+ return paragraphSpacingAt(node, index, betweenItems ? 'listSpacing' : 'paragraphSpacing')+}++function listStyleType(item: TextListItem): string {+ if (item.listType === 'UNORDERED') return 'disc'+ const format = listNumberFormat(item.level)+ if (format === 'LOWER_ALPHA') return 'lower-alpha'+ if (format === 'LOWER_ROMAN') return 'lower-roman'+ return 'decimal'+}++/** A list in the text, open at one level, with the item that nested lists go into. */+interface OpenList {+ level: number+ listType: TextListItem['listType']+ element: DesignElement+ item: DesignElement | undefined+}++/** Where the next list item goes: closes lists deeper than it, or of another kind at its level. */+function closeListsFor(open: OpenList[], item: TextListItem): void {+ while ((open.at(-1)?.level ?? 0) > item.level) open.pop()+ const top = open.at(-1)+ if (top?.level === item.level && (top.listType !== item.listType || item.startsList)) open.pop()+}++/**+ * Opens a list one level below the innermost open one, inside its last item; a level an item+ * skips gets an item without a marker to hold it.+ */+function openList(+ open: OpenList[],+ blocks: DesignNode[],+ item: TextListItem,+ indent: number+): void {+ const parent = open.at(-1)+ const level = (parent?.level ?? 0) + 1+ const list = element(+ item.listType === 'ORDERED' ? 'ol' : 'ul',+ {+ ...blockMargins(0, 0),+ 'padding-inline-start': px(indent),+ 'list-style-type': level === item.level ? listStyleType(item) : 'none'+ },+ []+ )+ if (parent) {+ parent.item ??= appendTo(parent.element, element('li', { 'list-style-type': 'none' }, []))+ // The space after the item the list nests in stands above the list.+ const spacing = parent.item.inlineStyle?.['margin-bottom']+ if (spacing && parent.item.inlineStyle && list.inlineStyle) {+ delete parent.item.inlineStyle['margin-bottom']+ list.inlineStyle['margin-top'] = spacing+ }+ parent.item.children.push(list)+ } else blocks.push(list)+ open.push({ level, listType: item.listType, element: list, item: undefined })+}++function plainParagraph(+ projection: TextProjection,+ index: number,+ range: TextParagraphRange,+ after: number+): DesignElement {+ const style = blockMargins(0, after)+ const indent = paragraphSpacingAt(projection.node, index, 'paragraphIndent')+ if (indent > 0) style['text-indent'] = px(indent)+ return element('p', style, paragraphContent(projection, range))+}++/**+ * The text as blocks, as Figma lays it out: a paragraph per plain one, lists nested by level+ * with Figma's markers (bullets at every level, numbers counting 1, a, i as they nest), and the+ * space after each paragraph as a margin on what ends it.+ */+function blockContent(projection: TextProjection): DesignNode[] {+ const { node } = projection+ const paragraphs = textParagraphRanges(node.text)+ const items = new Map(+ textListItems(node.text, node.textParagraphs).map((item) => [item.paragraph, item])+ )+ const blocks: DesignNode[] = []+ const open: OpenList[] = []+ for (const [index, range] of paragraphs.entries()) {+ const after = spaceAfter(node, index, paragraphs.length)+ const item = items.get(index)+ if (!item) {+ open.length = 0+ blocks.push(plainParagraph(projection, index, range, after))+ continue+ }+ const unit = groupEm(projection, paragraphs, item) * LIST_INDENT_EMS+ closeListsFor(open, item)+ while ((open.at(-1)?.level ?? 0) < item.level) {+ // A hanging list's markers stand outside the text, so its first level has no indent.+ const first = open.length === 0+ openList(open, blocks, item, first && node.hangingList ? 0 : unit)+ }+ const list = open.at(-1)+ if (!list) continue+ const style: DesignStyleDeclaration = after > 0 ? { 'margin-bottom': px(after) } : {}+ list.item = appendTo(list.element, element('li', style, paragraphContent(projection, range)))+ }+ return blocks+}++/** Margins above and below a block, written out: paragraphs and lists have their own in CSS. */+function blockMargins(top: number, bottom: number): DesignStyleDeclaration {+ return { 'margin-top': px(top), 'margin-bottom': px(bottom) }+}++function appendTo(parent: DesignElement, child: DesignElement): DesignElement {+ parent.children.push(child)+ return child+}++/** The size of a list's first character, which its indents are measured in. */+function groupEm(+ projection: TextProjection,+ paragraphs: readonly TextParagraphRange[],+ item: TextListItem+): number {+ const at = paragraphs[item.groupStart]?.start ?? item.start+ const range = projection.ranges.find((candidate) => at >= candidate.start && at < candidate.end)+ return range?.style.fontSize ?? projection.node.fontSize+}++/**+ * A text layer's element: its tag, its style with the decoration the whole text shares, and+ * its content. Runs of characters styled apart become spans; text with lists, paragraph+ * spacing, or a first-line indent becomes blocks, which a `<div>` holds.+ */+export function textElementContent(+ node: SceneNode,+ layerStyle: DesignStyleDeclaration+): { tagName: string; style: DesignStyleDeclaration; children: DesignNode[] } {+ const ranges = styledRanges(node)+ const decorated = uniformDecoration(node, ranges)+ const style = Object.fromEntries(+ Object.entries(layerStyle).filter(([property]) => !DECORATION_PROPERTIES.has(property))+ )+ if (decorated) Object.assign(style, decorationCSS(characterStyle(node)))+ const projection: TextProjection = {+ node,+ ranges,+ base: characterCSS(characterStyle(node), decorated),+ decorated+ }+ if (!needsBlocks(node)) {+ return { tagName: 'span', style, children: inlineContent(projection, 0, node.text.length) }+ }+ return { tagName: 'div', style, children: blockContent(projection) }+}diff --git a/packages/dom-css/src/import/flow.ts b/packages/dom-css/src/import/flow.tsindex 8d1354f2e..8ea4ecb76 100644--- a/packages/dom-css/src/import/flow.ts+++ b/packages/dom-css/src/import/flow.ts@@ -28,15 +28,20 @@ export type FlowKind = 'block' | 'flex' | 'inline'/** The layout a child is placed in: its parent's flow, or none at the top of the page. */export type ParentFlow = FlowKind | 'none'-const INLINE_TAGS = new Set([+/** Tags browsers lay out in a line by default. */+export const INLINE_TAGS = new Set(['a','abbr','b','code',+ 'del','em','i',+ 'ins','kbd','label',+ 'mark',+ 's','small','span','strong',diff --git a/packages/dom-css/src/import/scene-graph.ts b/packages/dom-css/src/import/scene-graph.tsindex 61d693023..a4006d83d 100644--- a/packages/dom-css/src/import/scene-graph.ts+++ b/packages/dom-css/src/import/scene-graph.ts@@ -1,3 +1,4 @@+import { pick } from 'es-toolkit'import { isValid, toUint8Array } from 'js-base64'import {@@ -21,6 +22,15 @@ import {inheritedTextStyle,type ParentFlow} from './flow'+import {+ blockRichText,+ characterStyleFromCSS,+ holdsTextBlocks,+ inlineRichText,+ isInlineContent,+ applyParagraphs,+ type CSSCharacterStyle+} from './text'const DOM_CSS_PLUGIN_ID = 'open-pencil-dom-css'const IMAGE_SOURCE_URL_KEY = 'image-source-url'@@ -338,24 +348,26 @@ function applyElementStyle(if (alignSelf !== 'AUTO') node.layoutAlignSelf = alignSelf}+const CHARACTER_FIELDS = [+ 'fontFamily',+ 'fontSize',+ 'fontWeight',+ 'italic',+ 'letterSpacing',+ 'lineHeight',+ 'fills',+ 'textDecoration',+ 'textDecorationStyle',+ 'textDecorationThickness',+ 'textDecorationFills',+ 'textDecorationSkipInk',+ 'textUnderlineOffset'+] as const satisfies readonly (keyof CSSCharacterStyle)[]+function applyTextStyle(node: SceneNode, style: DesignStyleDeclaration): void {setNodeBox(node, style)applyPositioning(node, style)-- const fills = fillsFromStyle(style, 'color')- if (fills.length > 0) node.fills = fills-- const fontSize = parseCSSNumber(pickStyle(style, 'font-size'))- if (fontSize !== null) node.fontSize = fontSize-- const fontWeight = parseCSSNumber(pickStyle(style, 'font-weight'))- if (fontWeight !== null) node.fontWeight = fontWeight-- const lineHeight = parseCSSNumber(pickStyle(style, 'line-height'))- if (lineHeight !== null) node.lineHeight = lineHeight-- const letterSpacing = parseCSSNumber(pickStyle(style, 'letter-spacing'))- if (letterSpacing !== null) node.letterSpacing = letterSpacing+ Object.assign(node, characterStyleFromCSS(style, pick(node, CHARACTER_FIELDS)))const opacity = parseCSSNumber(pickStyle(style, 'opacity'))if (opacity !== null) node.opacity = opacity@@ -363,27 +375,59 @@ function applyTextStyle(node: SceneNode, style: DesignStyleDeclaration): void {const effects = parseCSSShadows(pickStyle(style, 'text-shadow'))if (effects.length > 0) node.effects = effects- const fontFamily = pickStyle(style, 'font-family')- if (fontFamily)- node.fontFamily = fontFamily.split(',')[0]?.replaceAll('"', '').trim() || node.fontFamily-- node.italic = pickStyle(style, 'font-style') === 'italic'-const textAlign = pickStyle(style, 'text-align')?.toUpperCase()if (textAlign === 'CENTER' || textAlign === 'RIGHT' || textAlign === 'JUSTIFIED') {node.textAlignHorizontal = textAlign}- const textDecoration = pickStyle(style, 'text-decoration-line')- if (textDecoration === 'underline') node.textDecoration = 'UNDERLINE'- if (textDecoration === 'line-through') node.textDecoration = 'STRIKETHROUGH'-const textCase = textCaseFromCSS(pickStyle(style, 'text-transform'))if (textCase !== 'ORIGINAL') node.textCase = textCaseif (pickStyle(style, 'white-space') === 'nowrap') node.maxLines = 1}+/**+ * Text and inline elements, or blocks of text, as one text layer: spans become runs, blocks+ * paragraphs, and lists list paragraphs, as Figma holds rich text.+ */+function createRichTextNode(+ graph: SceneGraph,+ parentId: string,+ element: DesignElement,+ style: DesignStyleDeclaration,+ display: string,+ parentFlow: ParentFlow+): SceneNode {+ const node = graph.createNode('TEXT', parentId, { name: 'Text' })+ applyTextStyle(node, style)+ const blocks = holdsTextBlocks(element, isPlainElement, isInlineElement)+ const base = pick(node, CHARACTER_FIELDS)+ const rich = blocks ? blockRichText(element, style, base) : inlineRichText(element, style, base)+ node.text = rich.text+ node.name = rich.text.slice(0, 32) || 'Text'+ node.styleRuns = rich.styleRuns+ if (blocks) applyParagraphs(node, rich)+ applyFlowSizing(graph, node, style, display, parentFlow)+ return node+}++/** Whether an element draws nothing of its own, so its text can join the text around it. */+function isPlainElement(element: DesignElement): boolean {+ return !hasBoxStyle(mergedStyle(element))+}++function isInlineElement(element: DesignElement): boolean {+ const style = mergedStyle(element)+ return elementDisplay(element, style) === 'inline' && !hasBoxStyle(style)+}++/** Whether the element's children are text in one layer: inline content, or text blocks. */+function holdsRichText(element: DesignElement): boolean {+ if (!element.children.some((child) => child.type === 'element')) return false+ if (holdsTextBlocks(element, isPlainElement, isInlineElement)) return true+ return isInlineContent(element, isInlineElement)+}+function createTextNode(graph: SceneGraph,parentId: string,@@ -461,6 +505,9 @@ function createElementNode() {return createTextNode(graph, parentId, textContent(element), style, display, parentFlow)}+ if (!hasBoxStyle(style) && holdsRichText(element)) {+ return createRichTextNode(graph, parentId, element, style, display, parentFlow)+ }const node = graph.createNode('FRAME', parentId, {name: element.attrs.id || element.attrs.class || element.tagName,@@ -475,6 +522,13 @@ function createElementNode(}applyFlowSizing(graph, node, style, display, parentFlow)+ // Blocks of text in a box's own flow are one text; a flex box's children are items.+ if (flow !== 'flex' && holdsRichText(element)) {+ const textStyle = inheritedTextStyle(element, style)+ const textDisplay = flow === 'inline' ? 'inline' : 'block'+ createRichTextNode(graph, node.id, element, textStyle, textDisplay, flow ?? 'none')+ return node+ }for (const child of element.children) {createDesignNode(graph, node.id, child, flow ?? 'none', inheritedTextStyle(element, style))}diff --git a/packages/dom-css/src/import/text.ts b/packages/dom-css/src/import/text.tsnew file mode 100644index 000000000..429f1b2f7--- /dev/null+++ b/packages/dom-css/src/import/text.ts@@ -0,0 +1,479 @@+import { countBy } from 'es-toolkit/array'+import { isEqual } from 'es-toolkit/predicate'++import type {+ CharacterStyleOverride,+ SceneNode,+ StyleRun,+ TextParagraphStyle+} from '@open-pencil/scene-graph'+import { parseCSSColor, parseCSSNumber } from '@open-pencil/scene-graph/css'++import type { DesignElement, DesignNode, DesignStyleDeclaration } from '../types'+import { colorToFillFromCSS, mergedStyle, pickStyle } from './css-values'++/** The character styles a text layer and its runs take from CSS. */+export type CSSCharacterStyle = Pick<+ SceneNode,+ | 'fontFamily'+ | 'fontSize'+ | 'fontWeight'+ | 'italic'+ | 'letterSpacing'+ | 'lineHeight'+ | 'fills'+ | 'textDecoration'+ | 'textDecorationStyle'+ | 'textDecorationThickness'+ | 'textDecorationFills'+ | 'textDecorationSkipInk'+ | 'textUnderlineOffset'+>++/**+ * What characters take from the elements around them: the properties CSS inherits, and the+ * decoration, which CSS draws through descendants.+ */+const CHARACTER_PROPERTIES = [+ 'color',+ 'font-family',+ 'font-size',+ 'font-style',+ 'font-weight',+ 'letter-spacing',+ 'line-height',+ 'white-space',+ 'text-decoration-line',+ 'text-decoration-style',+ 'text-decoration-color',+ 'text-decoration-thickness',+ 'text-underline-offset',+ 'text-decoration-skip-ink'+]++const TEXT_BLOCK_TAGS = new Set(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'])++/** What browsers' default stylesheet gives inline formatting elements that CSS does not set. */+const FORMATTING_DEFAULTS: Record<string, DesignStyleDeclaration> = {+ b: { 'font-weight': '700' },+ strong: { 'font-weight': '700' },+ i: { 'font-style': 'italic' },+ em: { 'font-style': 'italic' },+ u: { 'text-decoration-line': 'underline' },+ ins: { 'text-decoration-line': 'underline' },+ s: { 'text-decoration-line': 'line-through' },+ del: { 'text-decoration-line': 'line-through' }+}+const LIST_TAGS = new Set(['ul', 'ol'])++/** Lengths CSS gives as a number of pixels, or `null` for keywords such as `auto`. */+function pixels(value: string | undefined): number | null {+ const trimmed = value?.trim()+ if (!trimmed || !/^-?[\d.]+(px)?$/.test(trimmed)) return null+ return parseCSSNumber(trimmed)+}++function decorationLine(value: string | undefined): SceneNode['textDecoration'] {+ if (value?.includes('underline')) return 'UNDERLINE'+ if (value?.includes('line-through')) return 'STRIKETHROUGH'+ return 'NONE'+}++function decorationStyle(value: string | undefined): SceneNode['textDecorationStyle'] {+ const style = value?.trim().toLowerCase()+ if (style === 'dotted') return 'DOTTED'+ if (style === 'wavy') return 'WAVY'+ return 'SOLID'+}++/** The character style of CSS declarations, over `base` for what they leave out. */+export function characterStyleFromCSS(+ style: DesignStyleDeclaration,+ base: CSSCharacterStyle+): CSSCharacterStyle {+ const fills = colorToFillFromCSS(pickStyle(style, 'color'))+ const family = pickStyle(style, 'font-family')?.split(',')[0]?.replaceAll('"', '').trim()+ const decorationColor = pickStyle(style, 'text-decoration-color')+ const decorationFills = parseCSSColor(decorationColor) ? colorToFillFromCSS(decorationColor) : []+ const line = pickStyle(style, 'text-decoration-line')+ const fontStyle = pickStyle(style, 'font-style')+ const lineHeight = pickStyle(style, 'line-height')+ return {+ fontFamily: family || base.fontFamily,+ fontSize: parseCSSNumber(pickStyle(style, 'font-size')) ?? base.fontSize,+ fontWeight: parseCSSNumber(pickStyle(style, 'font-weight')) ?? base.fontWeight,+ italic: fontStyle === undefined ? base.italic : fontStyle === 'italic',+ letterSpacing: pixels(pickStyle(style, 'letter-spacing')) ?? base.letterSpacing,+ lineHeight: lineHeight === 'normal' ? null : (pixels(lineHeight) ?? base.lineHeight),+ fills: fills.length > 0 ? fills : base.fills,+ textDecoration: line === undefined ? base.textDecoration : decorationLine(line),+ textDecorationStyle:+ pickStyle(style, 'text-decoration-style') === undefined+ ? base.textDecorationStyle+ : decorationStyle(pickStyle(style, 'text-decoration-style')),+ textDecorationFills: decorationColor === undefined ? base.textDecorationFills : decorationFills,+ textDecorationThickness:+ pickStyle(style, 'text-decoration-thickness') === undefined+ ? base.textDecorationThickness+ : pixels(pickStyle(style, 'text-decoration-thickness')),+ textUnderlineOffset:+ pickStyle(style, 'text-underline-offset') === undefined+ ? base.textUnderlineOffset+ : pixels(pickStyle(style, 'text-underline-offset')),+ textDecorationSkipInk:+ pickStyle(style, 'text-decoration-skip-ink') === undefined+ ? base.textDecorationSkipInk+ : pickStyle(style, 'text-decoration-skip-ink') !== 'none'+ }+}++/** What the characters inside `element` take from it and the elements around it. */+function characterDeclarations(+ element: DesignElement,+ around: DesignStyleDeclaration+): DesignStyleDeclaration {+ const own = { ...FORMATTING_DEFAULTS[element.tagName.toLowerCase()], ...mergedStyle(element) }+ const inherited: DesignStyleDeclaration = {}+ for (const property of CHARACTER_PROPERTIES) {+ const value = pickStyle(own, property) ?? pickStyle(around, property)+ if (value !== undefined) inherited[property] = value+ }+ return inherited+}++/** Whether the element holds only characters: text, inline elements, and line breaks. */+export function isInlineContent(+ element: DesignElement,+ isInlineElement: (element: DesignElement) => boolean+): boolean {+ return element.children.every(+ (child) =>+ child.type === 'text' ||+ child.tagName.toLowerCase() === 'br' ||+ (isInlineElement(child) && isInlineContent(child, isInlineElement))+ )+}++function isWhitespace(node: DesignNode): boolean {+ return node.type === 'text' && node.text.trim() === ''+}++function isList(+ element: DesignElement,+ isListPlain: (element: DesignElement) => boolean,+ isPlain: (element: DesignElement) => boolean+): boolean {+ if (!LIST_TAGS.has(element.tagName.toLowerCase()) || !isListPlain(element)) return false+ return element.children.every(+ (child) =>+ isWhitespace(child) ||+ (child.type === 'element' && child.tagName.toLowerCase() === 'li' && isListItem(child))+ )++ function isListItem(item: DesignElement): boolean {+ return item.children.every(+ (child) =>+ child.type === 'text' ||+ child.tagName.toLowerCase() === 'br' ||+ isList(child, isPlain, isPlain) ||+ (!LIST_TAGS.has(child.tagName.toLowerCase()) && isPlain(child))+ )+ }+}++/**+ * Whether the element holds text in blocks, as Figma keeps it in one layer: it is a list, or+ * holds only paragraphs, headings, and lists of characters with no box of their own.+ */+export function holdsTextBlocks(+ element: DesignElement,+ isPlain: (element: DesignElement) => boolean,+ isInlineElement: (element: DesignElement) => boolean+): boolean {+ if (LIST_TAGS.has(element.tagName.toLowerCase())) return isList(element, () => true, isPlain)+ const blocks = element.children.filter((child) => !isWhitespace(child))+ return (+ blocks.length > 0 &&+ blocks.every(+ (child) =>+ child.type === 'element' &&+ (isList(child, isPlain, isPlain) ||+ (TEXT_BLOCK_TAGS.has(child.tagName.toLowerCase()) &&+ isPlain(child) &&+ isInlineContent(child, isInlineElement)))+ )+ )+}++/** Text with its runs and paragraphs, as one text layer holds it. */+export interface RichText {+ text: string+ styleRuns: StyleRun[]+ textParagraphs: TextParagraphStyle[]+ /** The space after each paragraph, from the margins between blocks. */+ spaceAfter: number[]+ /** Each paragraph's first-line indent. */+ indents: number[]+ /** Whether the outermost list puts its markers outside the text, with no indent of its own. */+ hangingList: boolean+}++interface Collector {+ base: CSSCharacterStyle+ text: string+ styles: CSSCharacterStyle[]+ paragraphs: TextParagraphStyle[]+ spaceAfter: number[]+ indents: number[]+ /** Space collected from margins since the last paragraph ended. */+ pending: number+ hangingList: boolean | undefined+}++function preservesWhitespace(style: DesignStyleDeclaration): boolean {+ const whiteSpace = pickStyle(style, 'white-space')+ return whiteSpace === 'pre' || whiteSpace === 'pre-wrap' || whiteSpace === 'pre-line'+}++function appendCharacters(collector: Collector, text: string, style: CSSCharacterStyle): void {+ collector.text += text+ collector.styles.push(...Array.from({ length: text.length }, () => style))+}++/**+ * Characters of `text` in `style`. A line break inside a block starts a paragraph of the+ * block's kind, as text in Figma breaks into paragraphs at every newline.+ */+function addCharacters(collector: Collector, text: string, style: DesignStyleDeclaration): void {+ const value = preservesWhitespace(style) ? text : text.replaceAll(/\s+/g, ' ')+ const characterStyle = characterStyleFromCSS(style, collector.base)+ for (const [index, line] of value.split('\n').entries()) {+ if (index > 0) {+ const paragraph = collector.paragraphs.at(-1)+ if (paragraph) {+ collector.spaceAfter.push(0)+ collector.paragraphs.push({ ...paragraph })+ collector.indents.push(0)+ }+ appendCharacters(collector, '\n', characterStyle)+ }+ appendCharacters(collector, line, characterStyle)+ }+}++function addInline(+ collector: Collector,+ nodes: readonly DesignNode[],+ style: DesignStyleDeclaration+) {+ for (const node of nodes) {+ if (node.type === 'text') addCharacters(collector, node.text, style)+ else if (isBreak(node)) addCharacters(collector, '\n', { ...style, 'white-space': 'pre' })+ else if (!LIST_TAGS.has(node.tagName.toLowerCase())) {+ addInline(collector, node.children, characterDeclarations(node, style))+ }+ }+}++function isBreak(node: DesignNode): boolean {+ return node.type === 'element' && node.tagName.toLowerCase() === 'br'+}++function margin(element: DesignElement, side: 'top' | 'bottom'): number {+ return Math.max(0, pixels(pickStyle(mergedStyle(element), `margin-${side}`)) ?? 0)+}++/** Starts a paragraph, ending the one before with the space collected since it. */+function startParagraph(collector: Collector, style: TextParagraphStyle, indent: number): void {+ if (collector.paragraphs.length > 0) {+ collector.spaceAfter.push(collector.pending)+ appendCharacters(collector, '\n', collector.styles.at(-1) ?? collector.base)+ }+ collector.pending = 0+ collector.paragraphs.push(style)+ collector.indents.push(indent)+}++/** A paragraph's characters, trimmed of the spaces that CSS drops at a block's edges. */+function addParagraph(+ collector: Collector,+ nodes: readonly DesignNode[],+ style: DesignStyleDeclaration,+ paragraph: TextParagraphStyle,+ indent: number+): void {+ startParagraph(collector, paragraph, indent)+ // A line break that ends a block adds no line: it gives an empty block its height.+ const content = isBreak(nodes.at(-1) ?? { type: 'text', text: '' }) ? nodes.slice(0, -1) : nodes+ addTrimmed(collector, content, style)+}++/** Inline content, trimmed of the spaces CSS drops at a block's edges unless it keeps them. */+function addTrimmed(+ collector: Collector,+ nodes: readonly DesignNode[],+ style: DesignStyleDeclaration+): void {+ const start = collector.text.length+ addInline(collector, nodes, style)+ if (preservesWhitespace(style)) return+ const added = collector.text.slice(start)+ const leading = added.length - added.trimStart().length+ const trimmed = added.trim()+ collector.text = collector.text.slice(0, start) + trimmed+ collector.styles = [+ ...collector.styles.slice(0, start),+ ...collector.styles.slice(start + leading, start + leading + trimmed.length)+ ]+}++function addList(+ collector: Collector,+ list: DesignElement,+ around: DesignStyleDeclaration,+ level: number+): void {+ const listStyle = characterDeclarations(list, around)+ collector.pending = Math.max(collector.pending, margin(list, 'top'))+ if (level === 1 && collector.hangingList === undefined) {+ collector.hangingList = pixels(pickStyle(mergedStyle(list), 'padding-inline-start')) === 0+ }+ const listType = list.tagName.toLowerCase() === 'ol' ? 'ORDERED' : 'UNORDERED'+ for (const item of list.children) {+ if (item.type !== 'element') continue+ const itemStyle = characterDeclarations(item, listStyle)+ const inline = item.children.filter(+ (child) => child.type === 'text' || !LIST_TAGS.has(child.tagName.toLowerCase())+ )+ collector.pending = Math.max(collector.pending, margin(item, 'top'))+ // An item holding only a nested list, as a skipped level is written, is no paragraph.+ if (inline.some((child) => !isWhitespace(child))) {+ addParagraph(collector, inline, itemStyle, { listType, indentation: level }, 0)+ }+ for (const child of item.children) {+ if (child.type === 'element' && LIST_TAGS.has(child.tagName.toLowerCase())) {+ addList(collector, child, itemStyle, level + 1)+ }+ }+ collector.pending = Math.max(collector.pending, margin(item, 'bottom'))+ }+ collector.pending = Math.max(collector.pending, margin(list, 'bottom'))+}++/** Runs of characters whose style differs from the text's own. */+function styleRunsFrom(styles: readonly CSSCharacterStyle[], base: CSSCharacterStyle): StyleRun[] {+ const runs: StyleRun[] = []+ for (const [index, style] of styles.entries()) {+ const override: CharacterStyleOverride = {}+ for (const key of Object.keys(style) as (keyof CSSCharacterStyle)[]) {+ if (!isEqual(style[key], base[key])) Object.assign(override, { [key]: style[key] })+ }+ const previous = runs.at(-1)+ if (+ previous &&+ previous.start + previous.length === index &&+ isEqual(previous.style, override)+ ) {+ previous.length+++ } else if (Object.keys(override).length > 0) {+ runs.push({ start: index, length: 1, style: override })+ }+ }+ return runs+}++function richTextFrom(collector: Collector): RichText {+ return {+ text: collector.text,+ styleRuns: styleRunsFrom(collector.styles, collector.base),+ textParagraphs: collector.paragraphs,+ spaceAfter: collector.spaceAfter,+ indents: collector.indents,+ hangingList: collector.hangingList ?? false+ }+}++function collector(base: CSSCharacterStyle): Collector {+ return {+ base,+ text: '',+ styles: [],+ paragraphs: [],+ spaceAfter: [],+ indents: [],+ pending: 0,+ hangingList: undefined+ }+}++/** An element of inline content as one paragraph of text, its spans as runs. */+export function inlineRichText(+ element: DesignElement,+ style: DesignStyleDeclaration,+ base: CSSCharacterStyle+): RichText {+ const text = collector(base)+ addTrimmed(text, element.children, characterDeclarations(element, style))+ return richTextFrom(text)+}++/** An element of text blocks as paragraphs of one text, its spans as runs. */+export function blockRichText(+ element: DesignElement,+ style: DesignStyleDeclaration,+ base: CSSCharacterStyle+): RichText {+ const text = collector(base)+ const around = characterDeclarations(element, style)+ const blocks = LIST_TAGS.has(element.tagName.toLowerCase()) ? [element] : element.children+ for (const block of blocks) {+ if (block.type !== 'element') continue+ if (LIST_TAGS.has(block.tagName.toLowerCase())) {+ addList(text, block, around, 1)+ continue+ }+ text.pending = Math.max(text.pending, margin(block, 'top'))+ const blockStyle = characterDeclarations(block, around)+ const indent = Math.max(0, pixels(pickStyle(mergedStyle(block), 'text-indent')) ?? 0)+ addParagraph(text, block.children, blockStyle, { listType: 'NONE', indentation: 0 }, indent)+ text.pending = Math.max(text.pending, margin(block, 'bottom'))+ }+ return richTextFrom(text)+}++/** The value most gaps of a kind share, which the text holds; the others are the paragraphs'. */+function sharedValue(values: readonly number[]): number {+ const counts = countBy(values, String)+ const shared = Object.entries(counts)+ .toSorted((a, b) => b[1] - a[1])+ .at(0)+ return shared ? Number(shared[0]) : 0+}++/** Paragraph styles with the spacing and indents of the text's blocks, by Figma's rules. */+export function applyParagraphs(node: SceneNode, rich: RichText): void {+ const { textParagraphs: paragraphs, spaceAfter, indents } = rich+ const betweenItems = (index: number) =>+ paragraphs[index]?.listType !== 'NONE' && paragraphs[index + 1]?.listType !== 'NONE'+ const gaps = spaceAfter.map((space, index) => ({ space, list: betweenItems(index) }))+ node.paragraphSpacing = sharedValue(gaps.filter((gap) => !gap.list).map((gap) => gap.space))+ node.listSpacing = sharedValue(gaps.filter((gap) => gap.list).map((gap) => gap.space))+ node.paragraphIndent = sharedValue(+ indents.filter((_, index) => paragraphs[index]?.listType === 'NONE')+ )+ node.hangingList = rich.hangingList+ const styles = paragraphs.map((paragraph, index) => {+ const style: TextParagraphStyle = { ...paragraph }+ const gap = gaps.at(index)+ const field = gap?.list ? 'listSpacing' : 'paragraphSpacing'+ if (gap && gap.space !== node[field]) style[field] = gap.space+ if (paragraph.listType === 'NONE' && indents[index] !== node.paragraphIndent) {+ style.paragraphIndent = indents[index]+ }+ return style+ })+ const plain = styles.every(+ (style) => style.listType === 'NONE' && Object.keys(style).length === 2+ )+ node.textParagraphs = plain ? [] : styles+}diff --git a/packages/dom-css/src/runtime/headless.ts b/packages/dom-css/src/runtime/headless.tsindex 8ab98bf58..0818ab6ea 100644--- a/packages/dom-css/src/runtime/headless.ts+++ b/packages/dom-css/src/runtime/headless.ts@@ -1,6 +1,7 @@import { parseFragment, type DefaultTreeAdapterTypes } from 'parse5'import { serializeHTML } from '../export/html'+import { INLINE_TAGS } from '../import/flow'import { parseStyleAttribute } from '../import/style-attribute'import type { CSSRuntime, DesignDocument, DesignElement, DesignNode } from '../types'import { computeHeadlessStyles } from './headless-css'@@ -19,9 +20,44 @@ function isTextNode(const NON_RENDERED_TAGS = new Set(['head', 'link', 'meta', 'script', 'style', 'template', 'title'])-function childToDesignNode(node: DefaultTreeAdapterTypes.ChildNode): DesignNode | null {+function isInlineElement(node: DefaultTreeAdapterTypes.ChildNode | undefined): boolean {+ return node !== undefined && 'tagName' in node && INLINE_TAGS.has(node.tagName.toLowerCase())+}++/**+ * Text, and the spaces in or beside inline elements, which CSS draws among their words; spaces+ * between blocks lay nothing out, so they are left out.+ */+function keepsText(+ node: DefaultTreeAdapterTypes.TextNode,+ siblings: readonly DefaultTreeAdapterTypes.ChildNode[],+ index: number,+ inInline: boolean+): boolean {+ if (node.value.trim().length > 0) return true+ return (+ node.value.length > 0 &&+ (inInline || isInlineElement(siblings[index - 1]) || isInlineElement(siblings[index + 1]))+ )+}++function childrenToDesignNodes(+ nodes: readonly DefaultTreeAdapterTypes.ChildNode[],+ inInline: boolean+): DesignNode[] {+ return nodes+ .map((node, index) => childToDesignNode(node, index, nodes, inInline))+ .filter((child): child is DesignNode => child !== null)+}++function childToDesignNode(+ node: DefaultTreeAdapterTypes.ChildNode,+ index: number,+ siblings: readonly DefaultTreeAdapterTypes.ChildNode[],+ inInline: boolean+): DesignNode | null {if (isTextNode(node)) {- return node.value.trim().length > 0 ? { type: 'text', text: node.value } : null+ return keepsText(node, siblings, index, inInline) ? { type: 'text', text: node.value } : null}if (!('tagName' in node)) return null@@ -32,9 +68,7 @@ function childToDesignNode(node: DefaultTreeAdapterTypes.ChildNode): DesignNodetype: 'element',tagName: node.tagName.toLowerCase(),attrs,- children: node.childNodes- .map(childToDesignNode)- .filter((child): child is DesignNode => child !== null)+ children: childrenToDesignNodes(node.childNodes, isInlineElement(node))}const inlineStyle = parseStyleAttribute(attrs.style)@@ -47,9 +81,7 @@ function parseHTML(html: string): DesignDocument {const fragment = parseFragment(html)return {type: 'document',- children: fragment.childNodes- .map(childToDesignNode)- .filter((node): node is DesignNode => node !== null)+ children: childrenToDesignNodes(fragment.childNodes, false)}}diff --git a/packages/dom-css/tests/export/text.test.ts b/packages/dom-css/tests/export/text.test.tsnew file mode 100644index 000000000..a9cb3ad5c--- /dev/null+++ b/packages/dom-css/tests/export/text.test.ts@@ -0,0 +1,131 @@+import { describe, expect, test } from 'bun:test'++import {+ sceneNodeToDesignDocument,+ sceneNodesToTailwindJSX,+ sceneNodesToTailwindJSXWithLayers,+ serializeHTML+} from '#dom-css/index'++import { SceneGraph, type Fill, type TextParagraphStyle } from '@open-pencil/scene-graph'++const RED: Fill = {+ type: 'SOLID',+ color: { r: 1, g: 0, b: 0, a: 1 },+ opacity: 1,+ visible: true+}+const PLAIN: TextParagraphStyle = { listType: 'NONE', indentation: 0 }++function text(props: Parameters<SceneGraph['createNode']>[2]) {+ const graph = new SceneGraph()+ const node = graph.createNode('TEXT', graph.getPages()[0].id, {+ fontFamily: 'Inter',+ fontSize: 16,+ width: 200,+ height: 40,+ ...props+ })+ const html = serializeHTML(sceneNodeToDesignDocument(graph, node.id, { includeSourceIds: false }))+ return { graph, node, html }+}++describe('text export', () => {+ test('writes runs as spans that set only what differs from the text', () => {+ const { html } = text({+ text: 'Hello world',+ styleRuns: [+ { start: 0, length: 5, style: { fontWeight: 700 } },+ { start: 6, length: 5, style: { fills: [RED], fontSize: 24 } }+ ]+ })+ expect(html).toContain(+ '<span style="font-weight: 700">Hello</span> <span style="color: #FF0000; font-size: 24px">world</span>'+ )+ })++ test('decorates the text when every character is decorated alike, with all its details', () => {+ const { html } = text({+ text: 'Linked',+ textDecoration: 'UNDERLINE',+ textDecorationStyle: 'WAVY',+ textDecorationFills: [RED],+ textDecorationThickness: 2,+ textUnderlineOffset: 4,+ textDecorationSkipInk: false+ })+ expect(html).toContain(+ 'text-decoration-line: underline; text-decoration-style: wavy; text-decoration-color: #FF0000; ' ++ 'text-decoration-thickness: 2px; text-underline-offset: 4px; text-decoration-skip-ink: none'+ )+ expect(html).not.toContain('<span style="text-decoration')+ })++ test('decorates spans when decorations differ, since CSS cannot take one off a descendant', () => {+ const { html } = text({+ text: 'on off',+ textDecoration: 'UNDERLINE',+ styleRuns: [{ start: 2, length: 4, style: { textDecoration: 'NONE' } }]+ })+ expect(html).toContain('<span style="text-decoration-line: underline">on</span> off')+ })++ test('writes lists as nested lists with Figma markers and the spacing after each paragraph', () => {+ const { html } = text({+ text: 'Intro\nOne\nNested\nTwo\nDot',+ paragraphSpacing: 12,+ listSpacing: 4,+ textParagraphs: [+ PLAIN,+ { listType: 'ORDERED', indentation: 1 },+ { listType: 'ORDERED', indentation: 2 },+ { listType: 'ORDERED', indentation: 1 },+ { listType: 'UNORDERED', indentation: 1 }+ ]+ })+ expect(html).toStartWith('<div ')+ expect(html).toContain('<p style="margin-top: 0px; margin-bottom: 12px">Intro</p>')+ expect(html).toContain(+ '<ol style="margin-top: 0px; margin-bottom: 0px; padding-inline-start: 24px; list-style-type: decimal"><li>One' ++ '<ol style="margin-top: 4px; margin-bottom: 0px; padding-inline-start: 24px; list-style-type: lower-alpha">' ++ '<li style="margin-bottom: 4px">Nested</li></ol></li><li style="margin-bottom: 4px">Two</li></ol>'+ )+ expect(html).toContain('list-style-type: disc"><li>Dot</li></ul>')+ })++ test('gives an empty paragraph a line break, and a first-line indent to plain paragraphs', () => {+ const { html } = text({ text: 'One\n\nTwo', paragraphIndent: 8 })+ expect(html).toContain('text-indent: 8px">One</p>')+ expect(html).toContain('text-indent: 8px"><br></p>')+ })++ test('keeps text without lists or spacing in one element', () => {+ const { html } = text({ text: 'One\nTwo' })+ expect(html).toStartWith('<span ')+ expect(html).toContain('>One\nTwo</span>')+ })++ test('writes Tailwind spans and blocks, and a div around blocks', () => {+ const { graph, node } = text({+ text: 'Bold\nItem',+ styleRuns: [{ start: 0, length: 4, style: { fontWeight: 700 } }],+ textParagraphs: [PLAIN, { listType: 'UNORDERED', indentation: 1 }]+ })+ const jsx = sceneNodesToTailwindJSX(graph, [node.id])+ expect(jsx).toStartWith('<div ')+ expect(jsx).toContain('<span className="font-bold">Bold</span>')+ expect(jsx).toContain('<ul className="mt-0 mb-0 ps-6 list-disc">')+ })++ test('lists spans and blocks as elements without a layer, for the Code tab to skip', () => {+ const { graph, node } = text({+ text: 'Bold\nItem',+ styleRuns: [{ start: 0, length: 4, style: { fontWeight: 700 } }],+ textParagraphs: [PLAIN, { listType: 'UNORDERED', indentation: 1 }]+ })+ const { code, layerIds } = sceneNodesToTailwindJSXWithLayers(graph, [node.id])+ // The text, its paragraph and span, then the list and its item.+ expect(layerIds).toEqual([node.id, null, null, null, null])+ expect(code.match(/<(?!\/)[A-Za-z]/g)).toHaveLength(layerIds.length)+ })+})diff --git a/packages/dom-css/tests/import/text.test.ts b/packages/dom-css/tests/import/text.test.tsnew file mode 100644index 000000000..c8ec8accd--- /dev/null+++ b/packages/dom-css/tests/import/text.test.ts@@ -0,0 +1,155 @@+import { describe, expect, test } from 'bun:test'++import {+ createHeadlessCSSRuntime,+ designDocumentToSceneGraph,+ htmlToDesignDocument,+ sceneNodeToDesignDocument,+ serializeHTML+} from '#dom-css/index'++import {+ paragraphSpacingAt,+ SceneGraph,+ textParagraphRanges,+ type SceneNode,+ type TextParagraphStyle+} from '@open-pencil/scene-graph'++async function texts(html: string): Promise<SceneNode[]> {+ const document = await htmlToDesignDocument(html, { runtime: createHeadlessCSSRuntime() })+ const graph = designDocumentToSceneGraph(document)+ return [...graph.getAllNodes()].filter((node) => node.type === 'TEXT')+}++async function roundTrip(props: Parameters<SceneGraph['createNode']>[2]) {+ const graph = new SceneGraph()+ const node = graph.createNode('TEXT', graph.getPages()[0].id, {+ fontFamily: 'Inter',+ fontSize: 16,+ width: 300,+ height: 120,+ ...props+ })+ const html = serializeHTML(sceneNodeToDesignDocument(graph, node.id, { includeSourceIds: false }))+ const [back, ...rest] = await texts(html)+ expect(rest).toHaveLength(0)+ return { node, back }+}++function spacing(node: SceneNode) {+ return textParagraphRanges(node.text).map((_, index) => [+ paragraphSpacingAt(node, index, 'paragraphSpacing'),+ paragraphSpacingAt(node, index, 'listSpacing'),+ paragraphSpacingAt(node, index, 'paragraphIndent')+ ])+}++const ordered = (indentation: number): TextParagraphStyle => ({ listType: 'ORDERED', indentation })++describe('rich text import', () => {+ test('joins inline formatting into one text with style runs', async () => {+ const [text, ...rest] = await texts(+ '<p style="font-size: 16px">Hello <strong>bold</strong> and <em style="color: #ff0000">red</em><br>next</p>'+ )+ expect(rest).toHaveLength(0)+ expect(text?.text).toBe('Hello bold and red\nnext')+ expect(text?.styleRuns).toEqual([+ { start: 6, length: 4, style: { fontWeight: 700 } },+ {+ start: 15,+ length: 3,+ style: {+ italic: true,+ fills: [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }]+ }+ }+ ])+ })++ test('joins paragraphs and lists into one text, nesting by level, spacing from margins', async () => {+ const [text, ...rest] = await texts(`+ <div>+ <p style="margin: 0 0 12px">Intro</p>+ <ol style="margin: 0"><li>One<ol><li>Nested</li></ol></li><li>Two</li></ol>+ <ul><li>Dot</li></ul>+ </div>`)+ expect(rest).toHaveLength(0)+ expect(text?.text).toBe('Intro\nOne\nNested\nTwo\nDot')+ expect(+ text?.textParagraphs.map((paragraph) => [paragraph.listType, paragraph.indentation])+ ).toEqual([+ ['NONE', 0],+ ['ORDERED', 1],+ ['ORDERED', 2],+ ['ORDERED', 1],+ ['UNORDERED', 1]+ ])+ expect(text?.paragraphSpacing).toBe(12)+ })++ test('keeps the items of a flex container apart', async () => {+ const found = await texts(+ '<div style="display: flex; flex-direction: column; gap: 8px"><h2>Title</h2><p>Body</p></div>'+ )+ expect(found.map((node) => node.text)).toEqual(['Title', 'Body'])+ })++ test('reads back the runs and decorations it writes', async () => {+ const { node, back } = await roundTrip({+ text: 'Bold, dotted, offset, struck',+ styleRuns: [+ { start: 0, length: 4, style: { fontWeight: 700, fontSize: 24 } },+ {+ start: 6,+ length: 6,+ style: { textDecoration: 'UNDERLINE', textDecorationStyle: 'DOTTED' }+ },+ {+ start: 14,+ length: 6,+ style: {+ textDecoration: 'UNDERLINE',+ textUnderlineOffset: 6,+ textDecorationSkipInk: false+ }+ },+ { start: 22, length: 6, style: { textDecoration: 'STRIKETHROUGH', italic: true } }+ ]+ })+ expect(back.text).toBe(node.text)+ expect(back.styleRuns).toEqual(node.styleRuns)+ })++ test('reads back lists, spacing, indents, and empty paragraphs it writes', async () => {+ const { node, back } = await roundTrip({+ text: 'Intro\nOne\nNested a\nNested b\nTwo\n\nOutro',+ paragraphSpacing: 12,+ listSpacing: 4,+ paragraphIndent: 10,+ textParagraphs: [+ { listType: 'NONE', indentation: 0 },+ ordered(1),+ ordered(2),+ ordered(2),+ ordered(1),+ { listType: 'NONE', indentation: 0 },+ { listType: 'NONE', indentation: 0 }+ ]+ })+ expect(back.text).toBe(node.text)+ expect(+ back.textParagraphs.map((paragraph) => [paragraph.listType, paragraph.indentation])+ ).toEqual(node.textParagraphs.map((paragraph) => [paragraph.listType, paragraph.indentation]))+ expect(spacing(back)).toEqual(spacing(node))+ })++ test('reads back hanging list markers', async () => {+ const { back } = await roundTrip({+ text: 'One\nTwo',+ hangingList: true,+ textParagraphs: [ordered(1), ordered(1)]+ })+ expect(back.hangingList).toBe(true)+ })+})diff --git a/packages/emit/src/jsx.ts b/packages/emit/src/jsx.tsindex ec632eca8..d9d347b16 100644--- a/packages/emit/src/jsx.ts+++ b/packages/emit/src/jsx.ts@@ -59,6 +59,15 @@ export function text(value: string): SyntaxNode {return plain ? whitespace(value) : container(literal(value))}+/**+ * Text that shares a line with elements, as beside a span. JSX trims whitespace only at line+ * edges, so text without a line break is kept as written, spaces at its ends included.+ */+export function inlineText(value: string): SyntaxNode {+ const plain = LITERAL_TEXT.test(value) && value.length > 0+ return plain ? whitespace(value) : container(literal(value))+}+/** Children on their own lines; JSX drops whitespace-only lines between elements. */function indented(children: SyntaxNode[], depth: number): SyntaxNode[] {const inner = `\n${' '.repeat(depth + 1)}`diff --git a/packages/emit/tests/jsx.test.ts b/packages/emit/tests/jsx.test.tsindex c9645e966..e0be74dd4 100644--- a/packages/emit/tests/jsx.test.ts+++ b/packages/emit/tests/jsx.test.ts@@ -38,6 +38,19 @@ describe('JSX text', () => {)})+describe('JSX inline text', () => {+ test('keeps spaces at its ends, which JSX keeps on one line', () => {+ const span = jsx.element('Span', [], [jsx.inlineText('b')], 0, true)+ expect(card([], [jsx.inlineText(' a '), span, jsx.inlineText(' ')])).toBe(+ '<Card> a <Span>b</Span> </Card>'+ )+ })++ test.each(['{braces}', 'a & b', 'one\ntwo', ''])('writes %p as a string expression', (value) => {+ expect(card([], [jsx.inlineText(value)])).toBe(`<Card>{${JSON.stringify(value)}}</Card>`)+ })+})+describe('JSX elements', () => {test('put children on indented lines', () => {const child = jsx.element('Item', [], [], 1)diff --git a/packages/fig/src/node-change/convert.ts b/packages/fig/src/node-change/convert.tsindex dd8000075..05109e434 100644--- a/packages/fig/src/node-change/convert.ts+++ b/packages/fig/src/node-change/convert.ts@@ -310,7 +310,13 @@ function convertPolygonProps(return props}+/**+ * 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.+ */function importedTextLineHeight(nc: NodeChange): number | null {+ if (!nc.lineHeight) return nullconst derivedLineHeight = nc.derivedTextData?.baselines?.[0]?.lineHeightif (derivedLineHeight !== undefined && Number.isFinite(derivedLineHeight))return derivedLineHeightdiff --git a/packages/fig/src/node-change/derived-text/build.ts b/packages/fig/src/node-change/derived-text/build.tsindex 41b8f9af5..1c0482e3f 100644--- a/packages/fig/src/node-change/derived-text/build.ts+++ b/packages/fig/src/node-change/derived-text/build.ts@@ -11,13 +11,16 @@ import {import type { DerivedTextGlyph, SceneNode } from '@open-pencil/scene-graph'import { bytesToHex } from '../bytes'+import type { PlacedTextGlyph, TextDecorationRecord } from '../export/runtime'import { weightToFigmaStyle } from '../font/style'import { bakeGlyphScale, encodePathCommandsBlob, type OutlineCommand } from '../path/commands'+import { characterStyleIDs } from '../text/data-export'import { buildDerivedTextData } from './data'type DerivedTextData = NonNullable<NodeChange['derivedTextData']>type DerivedTextBaseline = NonNullable<DerivedTextData['baselines']>[number]type DerivedTextGlyphRecord = NonNullable<DerivedTextData['glyphs']>[number]+type DerivedTextDecoration = NonNullable<DerivedTextData['decorations']>[number]/*** One shaped glyph in node space: `x`/`y` sit on its baseline, and `commands` are its outline in@@ -47,6 +50,7 @@ export interface DerivedTextBuildContext {blobs: Uint8Array[]glyphBlobMap: Map<string, number>shapeText(node: SceneNode): ShapedText | null+ textDecorations(node: SceneNode, glyphs: readonly PlacedTextGlyph[]): TextDecorationRecord[]}// Figma stores a whitespace glyph as a lone close command.@@ -241,6 +245,25 @@ function savedGlyphRecords(})}+/**+ * Decorations as Figma saves them, which it draws saved text's underlines and strikethroughs+ * from: their rects by the style of the characters they decorate.+ */+function derivedDecorations(+ node: SceneNode,+ glyphs: readonly PlacedTextGlyph[],+ context: DerivedTextBuildContext+): DerivedTextDecoration[] | undefined {+ const records = context.textDecorations(node, glyphs)+ if (records.length === 0) return undefined+ const styleIDs = characterStyleIDs(node)+ const byStyle = groupBy(records, (record) => String(styleIDs[record.firstCharacter] ?? 0))+ return Object.entries(byStyle).map(([styleID, rects]) => ({+ rects: rects.map(({ x, y, width, height }) => ({ x, y, w: width, h: height })),+ styleID: Number(styleID)+ }))+}+/** Glyphs are derived data: a shaper failure must not fail the save or copy that writes them. */function shapeOrNull(node: SceneNode, context: DerivedTextBuildContext): ShapedText | null {try {@@ -266,6 +289,7 @@ export function buildNodeDerivedTextData(return buildDerivedTextData({node,glyphs: savedGlyphRecords(node, saved, context),+ decorations: node.textPathData ? undefined : derivedDecorations(node, saved, context),fontMetaData: fonts,...savedGlyphLayout(node, saved)})@@ -274,6 +298,7 @@ export function buildNodeDerivedTextData(return buildDerivedTextData({node,glyphs: shaped ? shapedGlyphRecords(shaped, context) : [],+ decorations: shaped ? derivedDecorations(node, shaped.glyphs, context) : undefined,fontMetaData: fonts,baselines: shaped?.baselines ?? [],logicalIndexToCharacterOffsetMap: shaped?.logicalIndexToCharacterOffsetMap ?? []diff --git a/packages/fig/src/node-change/derived-text/data.ts b/packages/fig/src/node-change/derived-text/data.tsindex 7e9d0758f..93fbb189a 100644--- a/packages/fig/src/node-change/derived-text/data.ts+++ b/packages/fig/src/node-change/derived-text/data.ts@@ -6,6 +6,7 @@ type DerivedTextData = NonNullable<NodeChange['derivedTextData']>interface DerivedTextDataOptions {node: SceneNodeglyphs: DerivedTextData['glyphs']+ decorations?: DerivedTextData['decorations']fontMetaData: DerivedTextData['fontMetaData']baselines: DerivedTextData['baselines']logicalIndexToCharacterOffsetMap: number[]@@ -18,6 +19,7 @@ export function buildDerivedTextData(layoutSize: { x: options.node.width, y: options.node.height },baselines: options.baselines,glyphs: options.glyphs,+ ...(options.decorations ? { decorations: options.decorations } : {}),fontMetaData: options.fontMetaData,logicalIndexToCharacterOffsetMap: options.logicalIndexToCharacterOffsetMap,derivedLines: [{ directionality: 'LTR' }],diff --git a/packages/fig/src/node-change/export/runtime.ts b/packages/fig/src/node-change/export/runtime.tsindex 329ccf225..775f8d35f 100644--- a/packages/fig/src/node-change/export/runtime.ts+++ b/packages/fig/src/node-change/export/runtime.ts@@ -1,13 +1,35 @@-import type { SceneNode } from '@open-pencil/scene-graph'+import type { DerivedTextGlyph, SceneNode } from '@open-pencil/scene-graph'import type { ShapedText } from '../derived-text/build'+import type { OutlineCommand } from '../path/commands'++/**+ * A glyph where it stands, as saved and shaped glyphs both give it, with its outline: saved+ * glyphs keep it as command bytes, shaped ones as commands, or none when unknown.+ */+export type PlacedTextGlyph = Pick<+ DerivedTextGlyph,+ 'x' | 'y' | 'firstCharacter' | 'advance' | 'fontSize' | 'scaleX' | 'scaleY'+> & { commandsBlob?: Uint8Array; commands?: OutlineCommand[] | null }++/** One underline or strikethrough on one line, by the first character it decorates. */+export interface TextDecorationRecord {+ firstCharacter: number+ x: number+ y: number+ width: number+ height: number+}/** Engine services the `.fig` writer needs but cannot provide without a text shaper. */export interface FigNodeChangeExportRuntime {/** Lay the node's text out at its width as the renderer draws it, or `null` when it cannot. */shapeText(node: SceneNode): ShapedText | null+ /** The node's underlines and strikethroughs over these glyphs, as Figma saves them. */+ textDecorations(node: SceneNode, glyphs: readonly PlacedTextGlyph[]): TextDecorationRecord[]}export const EMPTY_EXPORT_RUNTIME: FigNodeChangeExportRuntime = {- shapeText: () => null+ shapeText: () => null,+ textDecorations: () => []}diff --git a/packages/fig/src/node-change/serialize.ts b/packages/fig/src/node-change/serialize.tsindex a146128e0..759b68b90 100644--- a/packages/fig/src/node-change/serialize.ts+++ b/packages/fig/src/node-change/serialize.ts@@ -136,7 +136,8 @@ function serializeTextProps(digestMap: fontDigestMap,blobs,glyphBlobMap: glyphBlobMap ?? new Map(),- shapeText: (textNode) => runtime.shapeText(textNode)+ shapeText: (textNode) => runtime.shapeText(textNode),+ textDecorations: (textNode, glyphs) => runtime.textDecorations(textNode, glyphs)})}if (node.leadingTrim !== 'NONE') nc.leadingTrim = node.leadingTrimdiff --git a/packages/fig/src/node-change/text/data-export.ts b/packages/fig/src/node-change/text/data-export.tsindex c4282eddd..554868027 100644--- a/packages/fig/src/node-change/text/data-export.ts+++ b/packages/fig/src/node-change/text/data-export.ts@@ -91,6 +91,11 @@ function collectTextStyleOverrides(node: SceneNode): {return { charIds, styleMap }}+/** The style each character is written with, as an index into its override table. */+export function characterStyleIDs(node: SceneNode): number[] {+ return collectTextStyleOverrides(node).charIds+}+export function exportTextData(node: SceneNode,fillToKiwiPaint: (fill: SceneNode['fills'][number]) => Paintdiff --git a/packages/fig/tests/node-change/derived-text.test.ts b/packages/fig/tests/node-change/derived-text.test.tsindex d5593250f..7de6e055b 100644--- a/packages/fig/tests/node-change/derived-text.test.ts+++ b/packages/fig/tests/node-change/derived-text.test.ts@@ -5,7 +5,8 @@ import {buildNodeDerivedTextData,convertFigmaDerivedTextGlyphs,type DerivedTextBuildContext,- type ShapedText+ type ShapedText,+ type TextDecorationRecord} from '#fig/node-change/index'import type { NodeChange } from '@open-pencil/kiwi/fig/codec'@@ -30,12 +31,16 @@ function textNode(props: Partial<SceneNode> = {}): SceneNode {})}-function context(shaped: ShapedText | null): DerivedTextBuildContext & { blobs: Uint8Array[] } {+function context(+ shaped: ShapedText | null,+ decorations: TextDecorationRecord[] = []+): DerivedTextBuildContext & { blobs: Uint8Array[] } {return {digestMap: new Map(),blobs: [],glyphBlobMap: new Map(),- shapeText: () => shaped+ shapeText: () => shaped,+ textDecorations: () => decorations}}@@ -96,6 +101,25 @@ describe('derived text writer', () => {expect(writer.blobs).toHaveLength(0)})+ test('writes decorations by the style of the characters they decorate', () => {+ // Figma draws saved text's underlines and strikethroughs from these rects only.+ const node = textNode({+ textDecoration: 'UNDERLINE',+ styleRuns: [{ start: 3, length: 1, style: { textDecoration: 'STRIKETHROUGH' } }]+ })+ const rect = { x: 0, y: 14, width: 16, height: 1 }+ const writer = context(twoLines(SQUARE), [+ { firstCharacter: 0, ...rect },+ { firstCharacter: 3, ...rect, y: 22 }+ ])+ const data = expectDefined(buildNodeDerivedTextData(node, writer), 'derived text')++ expect(data.decorations).toEqual([+ { rects: [{ x: 0, y: 14, w: 16, h: 1 }], styleID: 0 },+ { rects: [{ x: 0, y: 22, w: 16, h: 1 }], styleID: 1 }+ ])+ })+test('writes no glyphs for text that could not be shaped', () => {const data = expectDefined(buildNodeDerivedTextData(textNode(), context(null)), 'derived')diff --git a/packages/fig/tests/node-change/export.test.ts b/packages/fig/tests/node-change/export.test.tsindex 6e1cb9531..a3bba6484 100644--- a/packages/fig/tests/node-change/export.test.ts+++ b/packages/fig/tests/node-change/export.test.ts@@ -112,6 +112,7 @@ describe('@open-pencil/fig SceneGraph export policy', () => {})const blobs: Uint8Array[] = []const runtime: FigNodeChangeExportRuntime = {+ textDecorations: () => [],shapeText: () => ({glyphs: [{diff --git a/packages/kiwi/src/fig/codec.ts b/packages/kiwi/src/fig/codec.tsindex 8ed411efd..82ab12108 100644--- a/packages/kiwi/src/fig/codec.ts+++ b/packages/kiwi/src/fig/codec.ts@@ -324,6 +324,12 @@ export interface NodeChange {/** Radians along the text path; kiwi omits the field for axis-aligned text. */rotation?: number}>+ /** Underlines and strikethroughs, which Figma draws saved text's decorations from. */+ decorations?: Array<{+ rects: Array<{ x: number; y: number; w: number; h: number }>+ /** The override table entry of the characters decorated, or 0 for the text's own style. */+ styleID: number+ }>fontMetaData?: Array<{key: { family: string; style: string; postscript?: string }fontLineHeight: numberdiff --git a/packages/vue/src/controls/typography/actions.ts b/packages/vue/src/controls/typography/actions.tsindex 3bd0f366d..416373de9 100644--- a/packages/vue/src/controls/typography/actions.ts+++ b/packages/vue/src/controls/typography/actions.ts@@ -18,6 +18,7 @@ import {} from '#vue/canvas/text-edit/paragraphs'import { MIXED, type MixedValue } from '#vue/controls/node-props/use'import type { UseTypographyOptions } from '#vue/controls/typography/use'+import { selectedNodesAsShown } from '#vue/editor/selection-state/nodes'import { useSceneComputed } from '#vue/internal/scene-computed/use'import { useNodeFontStatus } from '#vue/shared/font-status/use'@@ -54,7 +55,7 @@ function sharedFormatting(nodes: readonly SceneNode[]) {*/export function createTypographyState(editor: Editor) {const nodes = useSceneComputed<SceneNode[]>(() =>- editor.getSelectedNodes().filter((n) => n.type === 'TEXT')+ selectedNodesAsShown(editor).filter((n) => n.type === 'TEXT'))const node = computed<SceneNode | null>(() => nodes.value.at(0) ?? null)const { missingFonts, hasMissingFonts } = useNodeFontStatus(() => node.value)diff --git a/packages/vue/src/editor/selection-state/nodes.ts b/packages/vue/src/editor/selection-state/nodes.tsindex 0887d25b0..2a1617f66 100644--- a/packages/vue/src/editor/selection-state/nodes.ts+++ b/packages/vue/src/editor/selection-state/nodes.ts@@ -14,6 +14,18 @@ export interface SelectedNodeState {dispose: () => void}+/**+ * The selected layers as the panel shows them: text being edited has the style of its selected+ * characters, which the panel then edits.+ */+export function selectedNodesAsShown(editor: Editor): SceneNode[] {+ if (editor.state.editingTextId) void editor.state.textSelectionVersion+ return editor.getSelectedNodes().map((node) => {+ const style = editor.getTextSelectionStyle(node)+ return style ? { ...node, ...style } : node+ })+}+/** Selected-node copies with property-level preview tracking; never proxies the graph. */export function createSelectedNodeState(editor: Editor,@@ -31,7 +43,7 @@ export function createSelectedNodeState(void revision.valuevoid editor.state.sceneVersionvoid editor.state.currentPageId- return editor.getSelectedNodes().map((node) => shallowReactive(structuredClone(node)))+ return selectedNodesAsShown(editor).map((node) => shallowReactive(structuredClone(node)))})const byId = computed(() => new Map(nodes.value.map((node) => [node.id, node])))const node = computed(() => (nodes.value.length === 1 ? nodes.value[0] : null))diff --git a/skills/open-pencil/SKILL.md b/skills/open-pencil/SKILL.mdindex 65dc3752a..ec996bd33 100644--- a/skills/open-pencil/SKILL.md+++ b/skills/open-pencil/SKILL.md@@ -161,8 +161,18 @@ openpencil eval design.fig -o modified.fig -c '...'# Read code from stdinecho 'figma.currentPage.children.map(n => n.name)' | openpencil eval design.fig --stdin++# Style part of a text, and read how it is styled+openpencil eval design.fig -w -c '+ const title = figma.currentPage.findOne(n => n.type === "TEXT" && n.name === "Title");+ title.setRangeFontName(0, 5, { family: "Inter", style: "Bold" });+ title.setRangeFills(0, 5, [{ type: "SOLID", color: { r: 0.9, g: 0.1, b: 0.1 } }]);+ title.getStyledTextSegments(["fontName", "fills"]).map(s => [s.characters, s.fontName.style])+'```+Text styles follow Figma's per-character model: `getStyledTextSegments(fields)` reads runs, `getRange…`/`setRange…` read and set font, size, fills, letter spacing, line height, and decorations for `[start, end)`, and a text's `fontSize`, `fontName`, `fills`, and similar read `figma.mixed` while characters differ. Check for it before using the value.+Next to `figma`, scripts get `openpencil`: what OpenPencil adds to the Figma API, in its style. A main component can behave as a Reka UI control, by its own property and slot names:```bashdiff --git a/skills/open-pencil/references/design-authoring.md b/skills/open-pencil/references/design-authoring.mdindex 2d4945160..f19e58542 100644--- a/skills/open-pencil/references/design-authoring.md+++ b/skills/open-pencil/references/design-authoring.md@@ -25,6 +25,7 @@ This reference describes scene creation, not React DOM output. Use the `render`- `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.- `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.@@ -83,12 +84,25 @@ The examples below are executed by the authoring-reference tests. Create the nam</Frame>```+## Rich text with spans and lists++```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>+ <Paragraph list="unordered">Faster export</Paragraph>+ <Paragraph list="unordered" level={2}>PDF and SVG</Paragraph>+ <Paragraph list="ordered">Fewer clicks</Paragraph>+</Text>+</Frame>+```+## Supported syntax inventoryGenerated from the renderer metadata. This inventory lists accepted names, not arbitrary browser CSS support.-**Elements:** `Frame`, `Text`, `Rectangle`, `Ellipse`, `Line`, `Star`, `Polygon`, `Vector`, `Group`, `Section`, `Component`, `ComponentSet`, `Instance`, `View`, `Rect`, `Icon`, `Button.Root`, `Toggle.Root`, `Switch.Root`, `Switch.Thumb`, `Checkbox.Root`, `Checkbox.Indicator`, `RadioGroup.Root`, `RadioGroup.Item`, `RadioGroup.Indicator`, `ToggleGroup.Root`, `ToggleGroup.Item`, `Slider.Root`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Progress.Root`, `Progress.Track`, `Progress.Indicator`, `Tabs.Root`, `Tabs.List`, `Tabs.Trigger`, `Tabs.Content`, `Collapsible.Root`, `Collapsible.Trigger`, `Collapsible.Content`, `Accordion.Root`, `Accordion.Item`, `Accordion.Header`, `Accordion.Trigger`, `Accordion.Content`, `NumberField.Root`, `NumberField.Input`, `NumberField.Increment`, `NumberField.Decrement`, `TextField.Root`, `TextField.Input`, `Textarea.Root`, `Textarea.Input`.+**Elements:** `Frame`, `Text`, `Span`, `Paragraph`, `Rectangle`, `Ellipse`, `Line`, `Star`, `Polygon`, `Vector`, `Group`, `Section`, `Component`, `ComponentSet`, `Instance`, `View`, `Rect`, `Icon`, `Button.Root`, `Toggle.Root`, `Switch.Root`, `Switch.Thumb`, `Checkbox.Root`, `Checkbox.Indicator`, `RadioGroup.Root`, `RadioGroup.Item`, `RadioGroup.Indicator`, `ToggleGroup.Root`, `ToggleGroup.Item`, `Slider.Root`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Progress.Root`, `Progress.Track`, `Progress.Indicator`, `Tabs.Root`, `Tabs.List`, `Tabs.Trigger`, `Tabs.Content`, `Collapsible.Root`, `Collapsible.Trigger`, `Collapsible.Content`, `Accordion.Root`, `Accordion.Item`, `Accordion.Header`, `Accordion.Trigger`, `Accordion.Content`, `NumberField.Root`, `NumberField.Input`, `NumberField.Increment`, `NumberField.Decrement`, `TextField.Root`, `TextField.Input`, `Textarea.Root`, `Textarea.Input`.**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`, `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`, `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 filediff --git a/src/app/code/layers/use.ts b/src/app/code/layers/use.tsindex 03045b673..0638e22de 100644--- a/src/app/code/layers/use.ts+++ b/src/app/code/layers/use.ts@@ -51,7 +51,9 @@ export function useCodeLayers(source: Readonly<Ref<CodeSource>>) {}/** Design JSX for a layer added on the canvas, with the layer of each of its elements. */- function snippet(nodeId: string): { code: string; layerIds: string[] } | null {+ function snippet(+ nodeId: string+ ): { code: string; layerIds: ReadonlyArray<string | null> } | null {const { code, layerIds } = selectionToJSXWithLayers([nodeId], store.graph)return code ? { code, layerIds } : null}diff --git a/src/components/code-editor/layers/context.ts b/src/components/code-editor/layers/context.tsindex 828ceb524..2b9d73695 100644--- a/src/components/code-editor/layers/context.ts+++ b/src/components/code-editor/layers/context.ts@@ -3,14 +3,16 @@ import type { ChangeSpec, EditorState } from '@codemirror/state'import type { StaleAttribute } from './stale'/** Snippets of new layers: exported Design JSX and the layer of each element, in order. */-export type LayerSnippet = (nodeId: string) => { code: string; layerIds: string[] } | null+export type LayerSnippet = (+ nodeId: string+) => { code: string; layerIds: ReadonlyArray<string | null> } | null/** Text replacing a range, with the elements in it to link, by offset into the text. */export interface Rewrite {from: numberto: numbertext: string- links: Array<{ offset: number; length: number; layerIds: Array<string | null> }>+ links: Array<{ offset: number; length: number; layerIds: ReadonlyArray<string | null> }>/** Blocks kept from the old text: their range there and their offset into the new text. */moves: Array<{ from: number; to: number; offset: number }>}@@ -20,7 +22,12 @@ export interface PatchContext {changes: ChangeSpec[]stale: StaleAttribute[]rewrites: Rewrite[]- insertions: Array<{ at: number; text: string; offset: number; layerIds: string[] }>+ insertions: Array<{+ at: number+ text: string+ offset: number+ layerIds: ReadonlyArray<string | null>+ }>removed: Array<{ from: number; to: number }>snippet: LayerSnippet}diff --git a/tests/e2e/canvas/text/visual.spec.ts-snapshots/text-decoration-styles-and-opentype-features-openpencil-darwin.png b/tests/e2e/canvas/text/visual.spec.ts-snapshots/text-decoration-styles-and-opentype-features-openpencil-darwin.pngindex e61ae0bb2..5c4b8fae4 100644Binary files a/tests/e2e/canvas/text/visual.spec.ts-snapshots/text-decoration-styles-and-opentype-features-openpencil-darwin.png and b/tests/e2e/canvas/text/visual.spec.ts-snapshots/text-decoration-styles-and-opentype-features-openpencil-darwin.png differdiff --git a/tests/engine/figma/api/clone.test.ts b/tests/engine/figma/api/clone.test.tsindex bda9f0617..8a42be7c5 100644--- a/tests/engine/figma/api/clone.test.ts+++ b/tests/engine/figma/api/clone.test.ts@@ -1,5 +1,7 @@import { describe, expect, test } from 'bun:test'+import { expectFills } from '#tests/helpers/assert'+import { createAPI, solidFill } from './helpers'describe('clone', () => {@@ -15,7 +17,7 @@ describe('clone', () => {const cloned = frame.clone()expect(cloned.id).not.toBe(frame.id)expect(cloned.name).toBe('Original')- expect(cloned.fills[0].color.r).toBe(1)+ expect(expectFills(cloned.fills)[0].color.r).toBe(1)expect(cloned.children.length).toBe(1)expect(cloned.children[0].name).toBe('Child')expect(cloned.children[0].id).not.toBe(child.id)diff --git a/tests/engine/figma/api/property/access.test.ts b/tests/engine/figma/api/property/access.test.tsindex 5966ed0d8..dcaa4021c 100644--- a/tests/engine/figma/api/property/access.test.ts+++ b/tests/engine/figma/api/property/access.test.ts@@ -1,5 +1,7 @@import { describe, expect, test } from 'bun:test'+import { expectFills } from '#tests/helpers/assert'+import { createAPI, solidFill } from '../helpers'describe('property access', () => {@@ -41,7 +43,7 @@ describe('property access', () => {// Plugin scripts may leave out `opacity` and `visible`; Figma fills them in.Reflect.set(rect, 'fills', [{ type: 'SOLID', color: { r: 1, g: 0, b: 0 } }])Reflect.set(rect, 'strokes', [{ type: 'SOLID', color: { r: 0, g: 0, b: 1 }, opacity: 0.5 }])- expect(rect.fills[0]).toMatchObject({ opacity: 1, visible: true })+ expect(expectFills(rect.fills)[0]).toMatchObject({ opacity: 1, visible: true })expect(rect.strokes[0]).toMatchObject({ opacity: 0.5, visible: true })})diff --git a/tests/engine/mcp/tools.test.ts b/tests/engine/mcp/tools.test.tsindex 91e5a9a2b..55e541471 100644--- a/tests/engine/mcp/tools.test.ts+++ b/tests/engine/mcp/tools.test.ts@@ -2,7 +2,7 @@ import { describe, expect, test } from 'bun:test'import { ALL_TOOLS, FigmaAPI, SceneGraph, computeAllLayouts, parseFigFile } from '@open-pencil/core'-import { expectDefined } from '#tests/helpers/assert'+import { expectDefined, expectFills } from '#tests/helpers/assert'interface PageTreeResult {page: string@@ -143,9 +143,9 @@ describe('MCP tool execution', () => {findTool('set_fill').execute(api, { id: frame.id, color: '#ff0000' })const node = expectDefined(api.getNodeById(frame.id), 'filled rectangle')expect(node.fills).toHaveLength(1)- expect(node.fills[0].color.r).toBeCloseTo(1)- expect(node.fills[0].color.g).toBeCloseTo(0)- expect(node.fills[0].color.b).toBeCloseTo(0)+ expect(expectFills(node.fills)[0].color.r).toBeCloseTo(1)+ expect(expectFills(node.fills)[0].color.g).toBeCloseTo(0)+ expect(expectFills(node.fills)[0].color.b).toBeCloseTo(0)})test('set_layout configures auto-layout', () => {diff --git a/tests/engine/render/canvas/derived-text.test.ts b/tests/engine/render/canvas/derived-text.test.tsindex d21636725..d736ce0ce 100644--- a/tests/engine/render/canvas/derived-text.test.ts+++ b/tests/engine/render/canvas/derived-text.test.ts@@ -5,7 +5,6 @@ import { SceneGraph } from '@open-pencil/scene-graph'import { initCanvasKit } from '#cli/headless'import { SkiaRenderer } from '#core/canvas/renderer'import {- derivedUnderlineRect,hasRotatedDerivedGlyphs,shouldUseHardDerivedGlyphCoverage,snapDerivedGlyphBaseline@@ -20,6 +19,18 @@ beforeAll(async () => {ck = await initCanvasKit()})+/** Saved glyphs as Figma saves them, one per character with its advance, 8px apart from x 2. */+function savedGlyphs(text: string) {+ return Array.from(text, (_, index) => ({+ commandsBlob: squareCommandsBlob(),+ x: 2 + index * 8,+ y: 12,+ fontSize: 10,+ firstCharacter: index,+ advance: 8+ }))+}+function useDerivedGlyphFallback(renderer: SkiaRenderer): void {renderer.nodeFontReadiness = () => 'exhausted'}@@ -146,15 +157,6 @@ describe('derived text rendering', () => {expect(shouldUseHardDerivedGlyphCoverage({ fontSize: 14, fontWeight: 500 })).toBeFalse()})- test('places derived underlines at Figma-like subpixel coverage bounds', () => {- expect(derivedUnderlineRect({ width: 70 }, 17)).toEqual({- x1: 0,- y1: 19.75,- x2: 69.25,- y2: 20.75- })- })-test('draws Figma-derived glyphs even when the font is unavailable', async () => {const graph = new SceneGraph()const page = graph.getPages()[0]@@ -229,14 +231,7 @@ describe('derived text rendering', () => {visible: true}],- derivedTextGlyphs: [- {- commandsBlob: squareCommandsBlob(),- x: 2,- y: 12,- fontSize: 10- }- ]+ derivedTextGlyphs: savedGlyphs('x')})const surface = expectDefined(ck.MakeSurface(1, 1), 'surface')@@ -263,8 +258,8 @@ describe('derived text rendering', () => {'pixels')- const underlinedRows = [15, 16].map((y) => pixels[(y * image.width() + 8) * 4 + 3])- expect(Math.max(...underlinedRows)).toBeGreaterThan(0)+ // 10px text on a baseline at 12 is underlined from 13.99 to 14.67, as Figma places it.+ expect(pixels[(14 * image.width() + 6) * 4 + 3]).toBeGreaterThan(0)image.delete()} finally {surface.delete()@@ -295,14 +290,7 @@ describe('derived text rendering', () => {visible: true}],- derivedTextGlyphs: [- {- commandsBlob: squareCommandsBlob(),- x: 2,- y: 12,- fontSize: 10- }- ]+ derivedTextGlyphs: savedGlyphs('on off')})const surface = expectDefined(ck.MakeSurface(1, 1), 'surface')@@ -329,14 +317,8 @@ describe('derived text rendering', () => {'pixels')- const leftUnderlineAlpha = Math.max(- pixels[(15 * image.width() + 12) * 4 + 3] ?? 0,- pixels[(16 * image.width() + 12) * 4 + 3] ?? 0- )- const disabledUnderlineAlpha = Math.max(- pixels[(15 * image.width() + 45) * 4 + 3] ?? 0,- pixels[(16 * image.width() + 45) * 4 + 3] ?? 0- )+ const leftUnderlineAlpha = pixels[(14 * image.width() + 12) * 4 + 3] ?? 0+ const disabledUnderlineAlpha = pixels[(14 * image.width() + 45) * 4 + 3] ?? 0expect(leftUnderlineAlpha).toBeGreaterThan(0)expect(disabledUnderlineAlpha).toBe(0)image.delete()@@ -390,14 +372,7 @@ describe('derived text rendering', () => {visible: true}],- derivedTextGlyphs: [- {- commandsBlob: squareCommandsBlob(),- x: 2,- y: 12,- fontSize: 10- }- ]+ derivedTextGlyphs: savedGlyphs('red blue')})const surface = expectDefined(ck.MakeSurface(1, 1), 'surface')diff --git a/tests/engine/render/canvas/text-font-variations.test.ts b/tests/engine/render/canvas/text-font-variations.test.tsindex 097d864f2..bb9b94956 100644--- a/tests/engine/render/canvas/text-font-variations.test.ts+++ b/tests/engine/render/canvas/text-font-variations.test.ts@@ -1,28 +1,8 @@import { describe, expect, test } from 'bun:test'-import {- textDecorationStyleValue,- textFontFeatures,- textFontVariations,- textHeightBehaviorValue-} from '#core/canvas/text'+import { textFontFeatures, textFontVariations, textHeightBehaviorValue } from '#core/canvas/text'describe('canvas text font variations', () => {- test('maps imported text decoration styles to CanvasKit', () => {- const ck = {- DecorationStyle: {- Solid: 'solid',- Dotted: 'dotted',- Wavy: 'wavy'- }- }-- expect(textDecorationStyleValue(ck, 'SOLID')).toBe('solid')- expect(textDecorationStyleValue(ck, 'DOTTED')).toBe('dotted')- expect(textDecorationStyleValue(ck, 'WAVY')).toBe('wavy')- expect(textDecorationStyleValue(ck, undefined)).toBe('solid')- })-test('maps imported leading trim to CanvasKit text height behavior', () => {const ck = {TextHeightBehavior: {diff --git a/tests/engine/render/canvas/text-preparation-cache.test.ts b/tests/engine/render/canvas/text-preparation-cache.test.tsindex 5c4f42efe..b83289c71 100644--- a/tests/engine/render/canvas/text-preparation-cache.test.ts+++ b/tests/engine/render/canvas/text-preparation-cache.test.ts@@ -233,6 +233,8 @@ describe('text preparation cache', () => {textDecorationFills: [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }],+ textDecorationSkipInk: false,+ textUnderlineOffset: 4,textTruncation: 'ENDING',maxLines: 2,textParagraphs: [{ listType: 'UNORDERED', indentation: 1 }],diff --git a/tests/engine/tools/ai-adapter.test.ts b/tests/engine/tools/ai-adapter.test.tsindex d646f28de..012526541 100644--- a/tests/engine/tools/ai-adapter.test.ts+++ b/tests/engine/tools/ai-adapter.test.ts@@ -4,7 +4,7 @@ import { tool } from 'ai'import { ALL_TOOLS, FigmaAPI, SceneGraph, toolsToAI } from '@open-pencil/core'-import { expectDefined } from '#tests/helpers/assert'+import { expectDefined, expectFills } from '#tests/helpers/assert'type AdapterTool = { execute(args: Record<string, unknown>): Promise<unknown>; description: string }type SDKTool = {@@ -105,7 +105,7 @@ describe('AI adapter', () => {const setFill = adapterTool(tools, 'set_fill')await setFill.execute({ id: rect.id, color: '#00ff00' })- const fills = expectDefined(figma.getNodeById(rect.id), 'filled rectangle').fills+ const fills = expectFills(expectDefined(figma.getNodeById(rect.id), 'filled rectangle').fills)expect(fills.length).toBe(1)expect(fills[0].color.g).toBeCloseTo(1)})diff --git a/tests/engine/tools/modify.test.ts b/tests/engine/tools/modify.test.tsindex 1415f3168..40ad48c88 100644--- a/tests/engine/tools/modify.test.ts+++ b/tests/engine/tools/modify.test.ts@@ -2,7 +2,7 @@ import { describe, expect, test } from 'bun:test'import { computeAllLayouts } from '@open-pencil/core'-import { expectDefined, getNodeOrThrow } from '#tests/helpers/assert'+import { expectDefined, expectFills, getNodeOrThrow } from '#tests/helpers/assert'import { getTool, setupToolTest, type ToolResult } from '#tests/helpers/tools'describe('set_fill', () => {@@ -14,7 +14,7 @@ describe('set_fill', () => {const tool = getTool('set_fill')tool.execute(figma, { id: frame.id, color: '#ff0000' })- const fills = expectDefined(figma.getNodeById(frame.id), 'frame node').fills+ const fills = expectFills(expectDefined(figma.getNodeById(frame.id), 'frame node').fills)expect(fills.length).toBe(1)expect(fills[0].color.r).toBeCloseTo(1)expect(fills[0].color.g).toBeCloseTo(0)@@ -220,6 +220,31 @@ describe('set_constraints', () => {})describe('set_font_range', () => {+ test('returns an empty or overlong range as an error and changes nothing', () => {+ const { figma, graph } = setupToolTest()+ const created = getTool('create_shape').execute(figma, {+ type: 'TEXT',+ x: 0,+ y: 0,+ width: 200,+ height: 20+ }) as ToolResult+ const id = expectDefined(created.id, 'created node id')+ getTool('set_text').execute(figma, { id, text: 'Hello' })+ const setFontRange = getTool('set_font_range')++ expect(setFontRange.execute(figma, { id, start: 2, end: 2, size: 18 })).toEqual({+ error: "in setRangeFontSize: Empty range selected. 'end' must be greater than 'start'"+ })+ expect(setFontRange.execute(figma, { id, start: 0, end: 9, size: 18 })).toMatchObject({+ error: expect.stringContaining('Range outside of available characters')+ })+ expect(setFontRange.execute(figma, { id, start: 2, end: 2 })).toEqual({+ error: 'set_font_range needs at least one of family, size, style, or color'+ })+ expect(getNodeOrThrow(graph, id).styleRuns).toEqual([])+ })+test('applies font style to text range and survives serialization', () => {const { figma, graph } = setupToolTest()const createText = getTool('create_shape')diff --git a/tests/engine/tools/modify/image-fill.test.ts b/tests/engine/tools/modify/image-fill.test.tsindex f03789281..57b136a4e 100644--- a/tests/engine/tools/modify/image-fill.test.ts+++ b/tests/engine/tools/modify/image-fill.test.ts@@ -2,7 +2,7 @@ import { describe, expect, test } from 'bun:test'import { ALL_TOOLS, FigmaAPI, SceneGraph } from '@open-pencil/core'-import { expectDefined } from '#tests/helpers/assert'+import { expectDefined, expectFills } from '#tests/helpers/assert'const PNG_MAGIC = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])@@ -42,7 +42,7 @@ describe('set_image_fill tool', () => {expect(result.imageHash).toBeTruthy()expect(result.scaleMode).toBe('FILL')- const fills = expectDefined(figma.getNodeById(node.id), 'image-filled node').fills+ const fills = expectFills(expectDefined(figma.getNodeById(node.id), 'image-filled node').fills)expect(fills).toHaveLength(1)expect(fills[0].type).toBe('IMAGE')expect(fills[0].imageHash).toBe(result.imageHash)@@ -96,7 +96,9 @@ describe('set_image_fill tool', () => {}) as { scaleMode: string }expect(result.scaleMode).toBe(mode)- const fills = expectDefined(figma.getNodeById(node.id), 'image-filled node').fills+ const fills = expectFills(+ expectDefined(figma.getNodeById(node.id), 'image-filled node').fills+ )expect(fills[0].imageScaleMode).toBe(mode)}})diff --git a/tests/fixtures/figma-oracles/text-decorations.json b/tests/fixtures/figma-oracles/text-decorations.jsonnew file mode 100644index 000000000..61e9c80d4--- /dev/null+++ b/tests/fixtures/figma-oracles/text-decorations.json@@ -0,0 +1,940 @@+{+ "source": {+ "tool": "Figma clipboard, copied over CDP",+ "captured": "2026-10-11",+ "font": "Inter Regular as Figma ships it"+ },+ "note": "Figma saves each underline and strikethrough as rects in derivedTextData.decorations and draws saved text from them.",+ "cases": [+ {+ "name": "deco-decorations",+ "text": "Solid dotted wavy coloured thick offset strike",+ "fontSize": 24,+ "textDecoration": "NONE",+ "textDecorationStyle": "SOLID",+ "styleRuns": [+ {+ "start": 0,+ "length": 6,+ "style": {+ "textDecoration": "UNDERLINE"+ }+ },+ {+ "start": 6,+ "length": 6,+ "style": {+ "textDecoration": "UNDERLINE",+ "textDecorationStyle": "DOTTED"+ }+ },+ {+ "start": 12,+ "length": 1,+ "style": {+ "textDecoration": "UNDERLINE"+ }+ },+ {+ "start": 13,+ "length": 4,+ "style": {+ "textDecoration": "UNDERLINE",+ "textDecorationStyle": "WAVY"+ }+ },+ {+ "start": 17,+ "length": 1,+ "style": {+ "textDecoration": "UNDERLINE"+ }+ },+ {+ "start": 18,+ "length": 8,+ "style": {+ "textDecoration": "UNDERLINE",+ "textDecorationFills": [+ {+ "type": "SOLID",+ "color": {+ "r": 0.10000000149011612,+ "g": 0.4000000059604645,+ "b": 0.949999988079071,+ "a": 1+ },+ "opacity": 1,+ "visible": true,+ "blendMode": "NORMAL"+ }+ ]+ }+ },+ {+ "start": 26,+ "length": 1,+ "style": {+ "textDecoration": "UNDERLINE"+ }+ },+ {+ "start": 27,+ "length": 5,+ "style": {+ "textDecoration": "UNDERLINE",+ "textDecorationThickness": 4+ }+ },+ {+ "start": 32,+ "length": 1,+ "style": {+ "textDecoration": "UNDERLINE"+ }+ },+ {+ "start": 33,+ "length": 6,+ "style": {+ "textDecoration": "UNDERLINE",+ "textUnderlineOffset": 8+ }+ },+ {+ "start": 40,+ "length": 6,+ "style": {+ "textDecoration": "STRIKETHROUGH"+ }+ }+ ],+ "glyphs": [+ {+ "x": 0,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 0,+ "rotation": 0,+ "advance": 15.306818962097168,+ "outline": 0+ },+ {+ "x": 15.3046875,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 1,+ "rotation": 0,+ "advance": 14.318182468414307,+ "outline": 1+ },+ {+ "x": 29.625,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 2,+ "rotation": 0,+ "advance": 5.693182110786438,+ "outline": 2+ },+ {+ "x": 35.3203125,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 3,+ "rotation": 0,+ "advance": 5.693182110786438,+ "outline": 3+ },+ {+ "x": 41.015625,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 4,+ "rotation": 0,+ "advance": 14.897727012634277,+ "outline": 4+ },+ {+ "x": 55.921875,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 5,+ "rotation": 0,+ "advance": 6.75,+ "outline": 5+ },+ {+ "x": 62.671875,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 6,+ "rotation": 0,+ "advance": 14.897727012634277,+ "outline": 4+ },+ {+ "x": 77.578125,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 7,+ "rotation": 0,+ "advance": 14.318182468414307,+ "outline": 1+ },+ {+ "x": 91.8984375,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 8,+ "rotation": 0,+ "advance": 8.727272987365723,+ "outline": 6+ },+ {+ "x": 100.6171875,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 9,+ "rotation": 0,+ "advance": 8.727272987365723,+ "outline": 6+ },+ {+ "x": 109.1953125,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 10,+ "rotation": 0,+ "advance": 13.977272987365723,+ "outline": 7+ },+ {+ "x": 123.1640625,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 11,+ "rotation": 0,+ "advance": 14.897727012634277,+ "outline": 4+ },+ {+ "x": 138.0703125,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 12,+ "rotation": 0,+ "advance": 6.75,+ "outline": 5+ },+ {+ "x": 144.8203125,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 13,+ "rotation": 0,+ "advance": 19.5,+ "outline": 8+ },+ {+ "x": 164.3203125,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 14,+ "rotation": 0,+ "advance": 13.53409194946289,+ "outline": 9+ },+ {+ "x": 177.375,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 15,+ "rotation": 0,+ "advance": 13.363636493682861,+ "outline": 10+ },+ {+ "x": 190.734375,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 16,+ "rotation": 0,+ "advance": 13.363636493682861,+ "outline": 11+ },+ {+ "x": 204.09375,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 17,+ "rotation": 0,+ "advance": 6.75,+ "outline": 5+ },+ {+ "x": 210.84375,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 18,+ "rotation": 0,+ "advance": 13.397727012634277,+ "outline": 12+ },+ {+ "x": 224.25,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 19,+ "rotation": 0,+ "advance": 14.318182468414307,+ "outline": 1+ },+ {+ "x": 238.5703125,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 20,+ "rotation": 0,+ "advance": 5.693182110786438,+ "outline": 2+ },+ {+ "x": 244.265625,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 21,+ "rotation": 0,+ "advance": 14.318182468414307,+ "outline": 1+ },+ {+ "x": 258.5859375,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 22,+ "rotation": 0,+ "advance": 13.943182468414307,+ "outline": 13+ },+ {+ "x": 272.53125,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 23,+ "rotation": 0,+ "advance": 8.93181824684143,+ "outline": 14+ },+ {+ "x": 281.0625,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 24,+ "rotation": 0,+ "advance": 13.977272987365723,+ "outline": 7+ },+ {+ "x": 295.03125,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 25,+ "rotation": 0,+ "advance": 14.897727012634277,+ "outline": 4+ },+ {+ "x": 309.9375,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 26,+ "rotation": 0,+ "advance": 6.75,+ "outline": 5+ },+ {+ "x": 316.6875,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 27,+ "rotation": 0,+ "advance": 8.727272987365723,+ "outline": 6+ },+ {+ "x": 325.6875,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 28,+ "rotation": 0,+ "advance": 14.181818962097168,+ "outline": 15+ },+ {+ "x": 339.8671875,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 29,+ "rotation": 0,+ "advance": 5.693182110786438,+ "outline": 3+ },+ {+ "x": 345.5625,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 30,+ "rotation": 0,+ "advance": 13.397727012634277,+ "outline": 12+ },+ {+ "x": 358.96875,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 31,+ "rotation": 0,+ "advance": 13.056818962097168,+ "outline": 16+ },+ {+ "x": 372.0234375,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 32,+ "rotation": 0,+ "advance": 6.75,+ "outline": 5+ },+ {+ "x": 378.7734375,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 33,+ "rotation": 0,+ "advance": 14.318182468414307,+ "outline": 1+ },+ {+ "x": 393.09375,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 34,+ "rotation": 0,+ "advance": 8.659091234207153,+ "outline": 17+ },+ {+ "x": 401.7421875,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 35,+ "rotation": 0,+ "advance": 8.659091234207153,+ "outline": 17+ },+ {+ "x": 409.8515625,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 36,+ "rotation": 0,+ "advance": 12.54545545578003,+ "outline": 18+ },+ {+ "x": 422.390625,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 37,+ "rotation": 0,+ "advance": 13.977272987365723,+ "outline": 7+ },+ {+ "x": 436.359375,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 38,+ "rotation": 0,+ "advance": 8.727272987365723,+ "outline": 6+ },+ {+ "x": 445.078125,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 39,+ "rotation": 0,+ "advance": 6.75,+ "outline": 5+ },+ {+ "x": 451.828125,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 40,+ "rotation": 0,+ "advance": 12.54545545578003,+ "outline": 18+ },+ {+ "x": 464.3671875,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 41,+ "rotation": 0,+ "advance": 8.727272987365723,+ "outline": 6+ },+ {+ "x": 473.0859375,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 42,+ "rotation": 0,+ "advance": 8.93181824684143,+ "outline": 14+ },+ {+ "x": 482.015625,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 43,+ "rotation": 0,+ "advance": 5.693182110786438,+ "outline": 3+ },+ {+ "x": 487.7109375,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 44,+ "rotation": 0,+ "advance": 13.056818962097168,+ "outline": 16+ },+ {+ "x": 500.2265625,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 45,+ "rotation": 0,+ "advance": 13.977272987365723,+ "outline": 7+ }+ ],+ "figmaRects": [+ {+ "x": 0,+ "y": 27.772727966308594,+ "w": 62.671875,+ "h": 1.636362075805664+ },+ {+ "x": 138.0703125,+ "y": 27.772727966308594,+ "w": 6.75,+ "h": 1.636362075805664+ },+ {+ "x": 204.09375,+ "y": 27.772727966308594,+ "w": 6.75,+ "h": 1.636362075805664+ },+ {+ "x": 309.9375,+ "y": 27.772727966308594,+ "w": 6.75,+ "h": 1.636362075805664+ },+ {+ "x": 372.0234375,+ "y": 27.772727966308594,+ "w": 6.75,+ "h": 1.636362075805664+ },+ {+ "x": 62.671875,+ "y": 27.772727966308594,+ "w": 75.3984375,+ "h": 1.636362075805664+ },+ {+ "x": 144.8203125,+ "y": 27.772727966308594,+ "w": 46.9322509765625,+ "h": 1.636362075805664+ },+ {+ "x": 195.9505615234375,+ "y": 27.772727966308594,+ "w": 8.1431884765625,+ "h": 1.636362075805664+ },+ {+ "x": 210.84375,+ "y": 27.772727966308594,+ "w": 99.09375,+ "h": 1.636362075805664+ },+ {+ "x": 316.6875,+ "y": 27.772727966308594,+ "w": 55.3359375,+ "h": 4+ },+ {+ "x": 378.7734375,+ "y": 31,+ "w": 66.3046875,+ "h": 1.6363639831542969+ },+ {+ "x": 451.828125,+ "y": 15.142045021057129,+ "w": 62.375732421875,+ "h": 1.6363649368286133+ }+ ]+ },+ {+ "name": "skip-Inter-24",+ "text": "gypj",+ "fontSize": 24,+ "textDecoration": "UNDERLINE",+ "textDecorationStyle": "SOLID",+ "styleRuns": [],+ "glyphs": [+ {+ "x": 0,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 0,+ "rotation": 0,+ "advance": 14.625,+ "outline": 19+ },+ {+ "x": 14.625,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 1,+ "rotation": 0,+ "advance": 13.363636493682861,+ "outline": 11+ },+ {+ "x": 27.984375,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 2,+ "rotation": 0,+ "advance": 14.625,+ "outline": 20+ },+ {+ "x": 42.609375,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 3,+ "rotation": 0,+ "advance": 5.693182110786438,+ "outline": 21+ }+ ],+ "figmaRects": [+ {+ "x": 0,+ "y": 27.772727966308594,+ "w": 2.8948864936828613,+ "h": 1.636362075805664+ },+ {+ "x": 11.347301483154297,+ "y": 27.772727966308594,+ "w": 3.6413345336914062,+ "h": 1.636362075805664+ },+ {+ "x": 20.495738983154297,+ "y": 27.772727966308594,+ "w": 7.696022033691406,+ "h": 1.636362075805664+ },+ {+ "x": 33.4723014831543,+ "y": 27.772727966308594,+ "w": 7.500709533691406,+ "h": 1.636362075805664+ },+ {+ "x": 45.5582389831543,+ "y": 27.772727966308594,+ "w": 2.7443199157714844,+ "h": 1.636362075805664+ }+ ]+ },+ {+ "name": "skip-Inter-96",+ "text": "gypj",+ "fontSize": 96,+ "textDecoration": "UNDERLINE",+ "textDecorationStyle": "SOLID",+ "styleRuns": [],+ "glyphs": [+ {+ "x": 0,+ "y": 92.90908813476562,+ "fontSize": 96,+ "firstCharacter": 0,+ "rotation": 0,+ "advance": 58.5,+ "outline": 19+ },+ {+ "x": 58.5,+ "y": 92.90908813476562,+ "fontSize": 96,+ "firstCharacter": 1,+ "rotation": 0,+ "advance": 53.454545974731445,+ "outline": 11+ },+ {+ "x": 111.9375,+ "y": 92.90908813476562,+ "fontSize": 96,+ "firstCharacter": 2,+ "rotation": 0,+ "advance": 58.5,+ "outline": 20+ },+ {+ "x": 170.4375,+ "y": 92.90908813476562,+ "fontSize": 96,+ "firstCharacter": 3,+ "rotation": 0,+ "advance": 22.772728443145752,+ "outline": 21+ }+ ],+ "figmaRects": [+ {+ "x": 0,+ "y": 112.09091186523438,+ "w": 11.609375,+ "h": 6.545448303222656+ },+ {+ "x": 45.359375,+ "y": 112.09091186523438,+ "w": 14.6015625,+ "h": 6.545448303222656+ },+ {+ "x": 81.953125,+ "y": 112.09091186523438,+ "w": 30.8515625,+ "h": 6.545448303222656+ },+ {+ "x": 133.84375,+ "y": 112.09091186523438,+ "w": 30.09375,+ "h": 6.545448303222656+ },+ {+ "x": 182.1796875,+ "y": 112.09091186523438,+ "w": 11.030548095703125,+ "h": 6.545448303222656+ }+ ]+ },+ {+ "name": "skip-WAVY-24",+ "text": "gypj",+ "fontSize": 24,+ "textDecoration": "UNDERLINE",+ "textDecorationStyle": "WAVY",+ "styleRuns": [],+ "glyphs": [+ {+ "x": 0,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 0,+ "rotation": 0,+ "advance": 14.625,+ "outline": 19+ },+ {+ "x": 14.625,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 1,+ "rotation": 0,+ "advance": 13.363636493682861,+ "outline": 11+ },+ {+ "x": 27.984375,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 2,+ "rotation": 0,+ "advance": 14.625,+ "outline": 20+ },+ {+ "x": 42.609375,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 3,+ "rotation": 0,+ "advance": 5.693182110786438,+ "outline": 21+ }+ ],+ "figmaRects": [+ {+ "x": 0,+ "y": 27.772727966308594,+ "w": 3.549431800842285,+ "h": 1.636362075805664+ },+ {+ "x": 10.692755699157715,+ "y": 27.772727966308594,+ "w": 4.95042610168457,+ "h": 1.636362075805664+ },+ {+ "x": 19.84119415283203,+ "y": 27.772727966308594,+ "w": 9.005111694335938,+ "h": 1.636362075805664+ },+ {+ "x": 32.81775665283203,+ "y": 27.772727966308594,+ "w": 8.809799194335938,+ "h": 1.636362075805664+ },+ {+ "x": 44.90369415283203,+ "y": 27.772727966308594,+ "w": 3.39886474609375,+ "h": 1.636362075805664+ }+ ]+ },+ {+ "name": "skip-DOTTED-24",+ "text": "gypj",+ "fontSize": 24,+ "textDecoration": "UNDERLINE",+ "textDecorationStyle": "DOTTED",+ "styleRuns": [],+ "glyphs": [+ {+ "x": 0,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 0,+ "rotation": 0,+ "advance": 14.625,+ "outline": 19+ },+ {+ "x": 14.625,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 1,+ "rotation": 0,+ "advance": 13.363636493682861,+ "outline": 11+ },+ {+ "x": 27.984375,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 2,+ "rotation": 0,+ "advance": 14.625,+ "outline": 20+ },+ {+ "x": 42.609375,+ "y": 23.227272033691406,+ "fontSize": 24,+ "firstCharacter": 3,+ "rotation": 0,+ "advance": 5.693182110786438,+ "outline": 21+ }+ ],+ "figmaRects": [+ {+ "x": 0,+ "y": 27.772727966308594,+ "w": 3.549431800842285,+ "h": 1.636362075805664+ },+ {+ "x": 10.692755699157715,+ "y": 27.772727966308594,+ "w": 4.95042610168457,+ "h": 1.636362075805664+ },+ {+ "x": 19.84119415283203,+ "y": 27.772727966308594,+ "w": 9.005111694335938,+ "h": 1.636362075805664+ },+ {+ "x": 32.81775665283203,+ "y": 27.772727966308594,+ "w": 8.809799194335938,+ "h": 1.636362075805664+ },+ {+ "x": 44.90369415283203,+ "y": 27.772727966308594,+ "w": 3.39886474609375,+ "h": 1.636362075805664+ }+ ]+ }+ ],+ "outlines": [+ "AAEvuvg+6aILPwNedPU+XXQZP4wu3j5GFyE/A7voxj4vuig/RhelPi+6KD8DGF2MPi+6KD/ponM+L7okPwO76E4+L7ogP4wuOj4vuhk/A3XRJT4vuhI/ddElPnXRCT8DddElPhhdAj8AADQ+AAD6PgOji0I+XnTvPkYXWT4YXeg+A+mibz5edOE+jC6EPrvo3D4Do4uQPqOL2D666Jo+ddHVPgIvusA+6aLLPgPSRc8+ddHHPkYX4T5GF8E+A0YX8z4YXbo+L7oBPy+6rj4DAAAKP9JFoz4YXQ8/0kWRPgMvuhQ/o4t+Pi+6FD+MLko+Ay+6FD910Q0+ddEMP4wuuj0DAAAFP110MT110es+jC56PAN10c0+XnRRvLrooj5edFG8A3XRdT5edFG80kU7PumiSzwDRhcBPowuGj3SRb89XXSpPQOMLno9uugCPi+6aD0AAEA+AtJFFz4AAEA+A7roGj510RU+6aIzPhhd9D0DL7pMPnXRvT276HI+uuiiPQMvuow+L7qIPbrooj4vuog9Ay+6vD4vuog90kXRPowuqj0DddHlPhhdzD110fE+GF0EPgN10f0+uugiPnXR/T7poks+A3XR/T4vunA+XnTzPgAAhD4DRhfpPumijz6MLtg+uuiWPgPSRcc+jC6ePumisz7poqM+AnXRhT4vurA+AxhdND7SRb0+XXQBPqOL1D4DRhedPXXR6z5GF509L7oIPwNGF509GF0YPy+64D0AACQ/A6OLEj4vui8/AABMPowuNj8DuuiCPi+6PD+ji6Y+L7o8PwOji8o+L7o8P6OL5j7SRTY/A9JFAT+76C8/XXQJP3XRJD8DL7oRPy+6GT+MLhI/6aILPwIvuvg+6aILPwA=",+ "AAEvupg+jC46vAN10WU+jC46vC+6LD676MI8AwAA6D1edHE9AACoPYwu+j0DXnRRPXXRPT5edFE9jC6KPgNedFE9ddG1PgAAqD0YXdY+AwAA6D276PY+L7osPl10BD8DddFlPl10DT8vupg+XXQNPwOji74+XXQNP7vo2j5ddAQ/A1509z676PY+6aIDPxhd1j4D6aILP3XRtT7pogs/jC6KPgPpogs/ddE9PumiAz+MLvo9A1509z5edHE9u+jaPrvowjwDo4u+PowuOrwvupg+jC46vAABL7qYPrrogj0DXXS1Prrogj0AAMg+ddG9PQOji9o+L7r4PV504z4YXSw+Axhd7D4YXVw+GF3sPowuij4DGF3sPowupj5edOM+GF2+PgOji9o+o4vWPgAAyD5edOU+A110tT4YXfQ+L7qYPhhd9D4DAAB4Phhd9D676FI+XnTlPgN10S0+o4vWPgAAHD4YXb4+A4wuCj6MLqY+jC4KPowuij4DjC4KPhhdXD4AABw+GF0sPgN10S0+L7r4PbvoUj510b09AwAAeD666II9L7qYPrrogj0A",+ "AAEYXSQ+jC46PwIYXSQ+AAAAAAJGF509AAAAAAJGF509jC46PwIYXSQ+jC46PwA=",+ "AAFGF509AAAAAAJGF5096aILPwIYXSQ+6aILPwIYXSQ+AAAAAAJGF509AAAAAAABGF30PbroIj8DjC7CPbroIj910Z09jC4nPwMYXXQ9XXQrPxhddD1ddDE/AxhddD1ddDc/ddGdPS+6Oz8DjC7CPQAAQD8YXfQ9AABAPwPSRRM+AABAP0YXJT4vujs/A9JFNz5ddDc/0kU3Pl10MT8D0kU3Pl10Kz9GFyU+jC4nPwPSRRM+uugiPxhd9D266CI/AA==",+ "AAEvupA+jC46vAPpols+jC46vIwuJj5GF708A1504T1GF209RhelPQAA+D0DXnRRPUYXPT5edFE9uuiKPgNedFE9u+i2PkYXpT3SRdc+A1504T3povc+o4smPumiBD8DGF1cPl10DT9ddJE+XXQNPwMvuqw+XXQNP6OLvD666Ag/A6OLzD5ddAQ/u+jUPl50/T4DXnTdPowu8j6MLuI+u+jqPgJ10eU+u+jqPgJ10eU+jC46PwIYXQg/jC46PwIYXQg/AAAAAALSRec+AAAAAALSRec+6aKrPQKMLuI+6aKrPQNedN0+RheNPS+61D5GFz09AwAAzD676MI8ddG7PnXRxTsD6aKrPowuOrwvupA+jC46vAABo4uWPrrogj0DGF2wPrrogj2MLsI+L7q4PQMAANQ+0kXvPdJF3T7poic+A6OL5j4AAFg+o4vmPumiiz4Do4vmPrvoqj5edN0+GF3CPgMYXdQ+AADaPqOLwj5GF+c+Ay+6sD4YXfQ+o4uWPhhd9D4Do4t2Phhd9D6MLlI+GF3mPgOMLi4+o4vYPgAAHD4vusA+A4wuCj5GF6k+jC4KPumiiz4DjC4KPumiWz4YXRw+u+gqPgO76C4+Rhf1PbvoUj7pors9A9JFdz666II9o4uWPrrogj0A",+ "AA==",+ "AAEvuqA+6aILPwIvuqA+u+jyPgIAAAA9u+jyPgIAAAA96aILPwIvuqA+6aILPwABL7roPUYXLT8CjC5KPkYXLT8CjC5KPgAAID4DjC5KPtJF9z0vulQ+u+jSPQPpol8+0kWvPRhdcD666KI9Ay+6gD7SRZc9jC6KPtJFlz0D0kWRPtJFlz110ZU+jC6aPQMYXZo+ddGdPUYXnT4AAKA9AnXRpT6MLjo7A110oT6MLrq56aKZPi+6aLsDddGRPi+66Lt10YU+L7rouwPSRWc+L7rouxhdRD510QU8A3XRIT4AAMA8uugKPgAAYD0DL7roPQAAsD0vuug9L7oIPgIvuug9RhctPwA=",+ "AAEYXZw+jC46vAMAAGg+jC46vF10LT4AAMA8A6OL5j0AAHA90kWnPS+6+D0DXnRRPUYXPT5edFE9XXSJPgNedFE9GF20PtJFpz1GF9U+A6OL5j0AAPY+6aIrPowuBD8DGF1kPl10DT8AAJg+XXQNPwN10a0+XXQNP0YXwz510Qk/Axhd2D6MLgY/ddHpPgAA/D4D0kX7PnXR6z510QI/RhfRPgMAAAg/GF22PgAACD/SRY8+AgAACD+MLno+Arvo4j2MLno+Arvo4j2MLqI+Ahhd5D6MLqI+Axhd5D510bk+u+jaPhhdzD4D6aLRPrvo3j4YXcA+6aLpPgPSRa8+GF30PgAAmD4YXfQ+Ay+6fD4YXfQ+0kVXPumi5z4DjC4yPkYX2z6MLh4+u+jGPgOMLgo+L7qyPowuCj7pops+AowuCj666II+A4wuCj6ji0Y+AAAgPqOLGj4DjC42PnXR3T1edF0+AACwPQMYXYI+uuiCPRhdnD666II9A9JFrT666II9u+i6PnXRlT0DL7rIPl10qT0vutI+AADQPQMvutw+0kX3PYwu4j4vuhg+AnXRBT9ddAE+A6OLAj+ji6496aL1PkYXXT0DjC7mPkYXvTxddM8+jC66OwMvurg+jC46vBhdnD6MLjq8AA==",+ "AAFGF00+AAAAAALpogs96aILPwKMLvo96aILPwJ10XU+uugCPgLpons+uugCPgJddLk+6aILPwLSRec+6aILPwJGFxE/GF0EPgKjixI/GF0EPgIvujA/6aILPwLSRUc/6aILPwIvuhw/AAAAAALpogc/AAAAAAKMLtI+o4vWPgJ10c0+o4vWPgIvupA+AAAAAAJGF00+AAAAAAA=",+ "AAG76HI+XnRRvAN10T0+XnRRvKOLEj5GF907A6OLzj2MLto86aKbPbrogj0DXnRRPQAA0D1edFE9o4sePgNedFE9o4tOPqOLjj0YXWw+AxhdtD3SRYU+6aLzPXXRjT4DXXQZPhhdlj7poj8+o4uaPgOMLmY+uuiePqOLhj5ddKE+AwAAoD4vuqQ+ddGvPhhdpj4DddG/PowuqD5GF8c+GF2sPgOji84+o4uwPqOLzj676Lo+AqOLzj4YXbw+A6OLzj7SRdc+ddG/Powu5j4D0kWxPkYX9T7popM+Rhf1PgN10Wk+Rhf1PrvoRj7pouc+AwAAJD6MLto+ddEVPrvoyj4CL7qIPV502T4DGF20Pbvo8j5GF/09o4sAPwPSRSM+L7oHP6OLTj6jiwo/A4wuej5ddA0/jC6SPl10DT8D6aKfPl10DT9GF7E+ddELPwMvusI+0kUKP0YX0z4YXQU/A+mi4z5ddAA/o4vuPkYX7T4DXnT5PtJF2T5edPk+AAC4PgJedPk+AAAAAAKji84+AAAAAAKji84+0kWXPQIYXcw+0kWXPQMAAMg+ddFlPXXRvT666BI9A+misz4AAIA8L7qiPowuujoDddGRPl50Uby76HI+XnRRvAABAACAPgAAgD0DXXSZPgAAgD276Ko+AACoPQOji7w+AADQPV10xT7pogc+A6OLzj7SRSc+o4vOPowuSj4Co4vOPhhdjD4DddHLPkYXiT6ji8I+GF2GPgNddLk+ddGDPl10rT510YE+A+mioT4AAIA+GF2WPkYXfT4D0kWLPqOLej4YXYQ+L7p4PgPSRWc+GF10PowuSj6ji2o+A110LT5GF2E+6aIbPnXRTT4DjC4KPrvoOj6MLgo+jC4aPgOMLgo+u+jaPdJFKz5GF609Ay+6TD4AAIA9AACAPgAAgD0A",+ "AAF10QU/6aILPwIYXaQ+AAAAAAJedHE+AAAAAALpogs96aILPwIAAAA+6aILPwJGF40+u+jiPQIAAJA+u+jiPQJGF90+6aILPwJ10QU/6aILPwA=",+ "AAF10QU+XnRRvgMAAOA9XnRRvnXRvT110U2+A+mimz2ji0q+o4uOPdJFR74CjC66PdJF970DL7r4PemiA74YXRQ+XXQBvgMYXSw+o4v+vbvoPj4AANi9A3XRUT6MLrK9XnRhPowuOr0CXnRxPowuOrsC6aILPemiCz8CAAAAPumiCz8CRheNPrvo4j0CAACQPrvo4j0CRhfdPumiCz8CddEFP+miCz8CRheVPrroor0DRheNPl50+b3SRYE+RhcZvgO76Go+ddE1vumiSz7pokO+Ay+6LD5edFG+ddEFPl50Ub4A",+ "AAEvupg+jC46vAO76GI+jC46vIwuKj7poss8A7vo4j2MLno9ddGlPdJF/z0DXnRRPS+6QD5edFE9jC6KPgNedFE9L7q0PtJFpz3SRdU+A6OL5j0AAPY+6aIrPowuBD8DGF1kPl10DT8AAJg+XXQNPwNddLU+XXQNP0YXzT4AAAg/Ay+65D6jiwI/ddHzPl508T4DXXQBP3XR3T7SRQM/6aLDPgLpots+6aLDPgMvutY+L7rWPnXRxT5edOU+A0YXtT4YXfQ+L7qYPhhd9D4D0kV/Phhd9D5edFk+0kXnPgMAADQ+GF3aPrroHj4vusI+A4wuCj7SRas+jC4KPumiiz4DjC4KPqOLVj6jix4+o4smPgPSRTM+RhftPS+6WD4AALg9A6OLfj666II9L7qYPrrogj0DXXSpPrrogj1GF7c+jC6aPQMvusQ+XXSxPYwuzj5GF909A+mi1z4YXQQ+6aLbPrroIj4C0kUDP7roIj4DXXQBP7vo4j2ji/Q+6aKTPQMYXeY+jC4KPbvozj4YXTQ8A+mitz6MLjq8L7qYPowuOrwA",+ "AAHSRdc+GF1kPgLSRdc+6aILPwJGFwE/6aILPwJGFwE/AAAAAALSRdc+AAAAAALSRdc+Rhe9PQIYXdQ+Rhe9PQOji8o+AABQPXXRtT5ddLE8A0YXoT4vuui7XXSBPi+66LsDo4tOPi+66Lt10SU+jC56PAOMLvo96aIbPemiyz276Ko9A0YXnT0YXQQ+RhedPemiSz4CRhedPemiCz8CGF0kPumiCz8CGF0kPl50UT4DGF0kPhhdFD6ji0Y+AADgPQNGF2k+0kWXPdJFjz7SRZc9A9JFnz7SRZc9ddGvPgAAuD0Do4vAPi+62D110cs+jC4OPgPSRdc+AAAwPtJF1z4YXWQ+AA==",+ "AAFGF509AAAAAAJGF5096aILPwJddCE+6aILPwJddCE+RhftPgLSRSc+RhftPgOjizY+uugAP6OLXj4YXQc/A9JFgz510Q0/GF2cPnXRDT8DRhehPnXRDT+MLqg+L7oNPwPSRa8+6aINP7vosj5ddA0/Arvosj7SRe8+Ay+6sD510e8+u+ioPrvo8D4D0kWhPowu8j4vupg+jC7yPgMYXYQ+jC7yPi+6aD7pouk+A0YXST7SReE+o4s2Phhd0j4DGF0kPumiwz4YXSQ+L7qwPgIYXSQ+AAAAAAJGF509AAAAAAA=",+ "AAEYXSQ+AACoPgIYXSQ+AAAAAAJGF509AAAAAAJGF509jC46PwIYXSQ+jC46PwIYXSQ+6aLrPgLpois+6aLrPgPSRT8+6aIAP6OLZj4AAAc/A0YXhz5ddA0/AACoPl10DT8Do4vEPl10DT8AANo+L7oHPwNedO8+RhcCP9JF+z4vuuw+A+miAz9edNU+6aIDP110sT4C6aIDPwAAAAACGF3cPgAAAAACGF3cPqOLrj4DGF3cPnXRzz5GF8s+AADiPgMAALo+GF30Pumimz4YXfQ+A6OLhj4YXfQ+6aJrPl506z4Do4tKPqOL4j7SRTc+XnTRPgMYXSQ+GF3APhhdJD4AAKg+AA==",+ "AAGjix4+6aJLPgJGFx0+uuiaPgKjiy4+uuiaPgJedNE+6aILPwLSRQM/6aILPwIYXYQ+6aKTPgIvuoA+6aKTPgKjix4+6aJLPgABRhedPQAAAAACRhedPYwuOj8CGF0kPowuOj8CGF0kPgAAAAACRhedPQAAAAAAAS+62D4AAAAAAtJFVz6MLoo+Aowuij4AAKg+AumiBz8AAAAAAi+62D4AAAAAAA==",+ "AAHpoqM+6aILPwLpoqM+u+jyPgJedNE8u+jyPgJedNE86aILPwLpoqM+6aILPwABL7roPQAAAAACL7roPbroHj8DL7roPbvoKj+66Ao+u+gyPwNddCE+u+g6P110RT676D4/A150aT676EI/L7qIPrvoQj8Do4uYPrvoQj+ji6I+6aJBPwOji6w+GF1AP110sT7SRT8/AkYXpT4vuiw/A3XRoT7SRS0/AACcPkYXLj8DGF2WPrvoLj9GF40+u+guPwPpom8+u+guPy+6XD6jiyk/A4wuSj6MLiQ/jC5KPnXRGT8CjC5KPgAAAAACL7roPQAAAAAA",+ "AAFGF+0+L7rYPgKji8Y+ddHNPgO76MI+XnTXPnXRuz6ji+A+A7votD510ek+u+ioPnXR7z4DuuicPnXR9T6MLoo+ddH1PgNGF2E+ddH1PrvoPj4AAOo+A0YXHT4YXd4+RhcdPhhdzD4DRhcdPhhdvD4YXTQ+RhezPgPpoks+ddGpPkYXfT7poqM+AgAAqD5ddJk+A110zT4YXZA+ddHfPtJFez4DjC7yPowuVj6MLvI+6aIbPgOMLvI+0kXXPRhd5D7poos9Ay+61j4AAAA9jC6+PrroIjwD6aKlPowuOrxGF4U+jC46vAMvujQ+jC46vF50+T3poss8A110iT2MLno90kVXPXXRBT4C0kUHPowuGj4DuugSPowu2j3SRTM+RhetPQMAAFQ+AACAPRhdhD4AAIA9Axhdoj4AAIA9AAC0Prvosj0DddHFPqOL5j110cU+0kUXPgN10cU+GF00Pumiuz4AAEg+A110sT4AAFw+GF2cPnXRZT4C6aJbPumiez4DuugOPrrohj510dU9AACaPgOji4490kWtPqOLjj2MLso+A6OLjj110eE+6aLDPQAA9D4DXnT5PUYXAz+76Co+0kUIPwNedFk+XXQNP4wuij5ddA0/A+misz5ddA0/0kXLPhhdBD8DRhfjPqOL9j5GF+0+L7rYPgA=",+ "AAEAAJg+RhddvgN10XE+RhddvkYXRT5GF02+AxhdGD5ddD2+Rhf1PemiI74DjC66PYwuCr7SRZc9jC7avQIAABA+GF10vQPpohs+L7qYvV10LT4AAMC9A9JFPz4AAOi9jC5ePqOLAr4DXnR9Pl10Eb4AAJg+XXQRvgN10bk+XXQRvnXRzz5edOG9A3XR5T4AAKC9ddHlPrroIrwCddHlPqOLzj0CjC7iPqOLzj0DXnTdPgAAsD0vutQ+uuiCPQOMLsw+RhctPQAAvD6ji848AwAArD7pogs8L7qQPumiCzwDddFdPumiCzwAACg+uugiPQNGF+U9XXSRPaOLpj110QU+A150UT276EI+XnRRPUYXjT4DXnRRPQAAuD5GF6U9ddHXPgNedOE9ddH3PqOLJj7pogQ/AxhdXD5ddA0/XXSRPl10DT8DL7qsPl10DT8vurw+uugIPwO76Mw+XXQEP1501T5edP0+A4wu3j6MLvI+u+jiPrvo6j4C0kXnPrvo6j4C0kXnPumiCz8CGF0IP+miCz8CGF0IPwAAgLwDGF0IPwAAsL2MLgA/RhcFvgOMLvA+o4syvi+61D7poke+A110uT5GF12+AACYPkYXXb4AAaOLlj7poqs9AxhdsD7poqs9jC7CPrvo2j0DAADUPkYXBT7SRd0+XXQxPgOji+Y+ddFdPqOL5j510Y0+A6OL5j4AAKw+XnTdPkYXwz4DGF3UPowu2j6ji8I+0kXnPgMvurA+GF30PqOLlj4YXfQ+A6OLdj4YXfQ+jC5SPqOL5j4DjC4uPi+62D4AABw+XXTBPgOMLgo+jC6qPowuCj510Y0+A4wuCj5edGE+GF0cPi+6ND4Du+guPhhdCD676FI+ddHdPQPSRXc+6aKrPaOLlj7poqs9AA==",+ "AAFGF509XnRRvgJGF5096aILPwJddCE+6aILPwJddCE+u+jqPgLpois+u+jqPgNGFzU+jC7yPnXRRT5edP0+A7voVj5ddAQ/o4t2PrroCD8D0kWLPl10DT+ji6Y+XXQNPwN10ck+XXQNPy+65D7pogQ/A+mi/z7povc+GF0HP9JF1z4DuugOP7votj666A4/uuiKPgO66A4/Rhc9PhhdBz8AAPg9A+mi/z5GF209u+jkPkYXvTwDjC7KPowuOrzSRac+jC46vAMYXYw+jC46vBhdeD510cU7AwAAWD676MI8o4tGPkYXPT0DRhc1PkYXjT3pois+6aKrPQIYXSQ+6aKrPQIYXSQ+XnRRvgJGF509XnRRvgABuugiPumiiz4DuugiPgAAWD5ddDU+6aInPgMAAEg+0kXvPemiaz4vurg9A+mihz666II9XXShPrrogj0DGF28Prrogj0YXc4+6aK7PQOji+A+Rhf1Pemi6T676Co+A7vo8j7pols+u+jyPumiiz4Du+jyPkYXqT510ek+L7rAPgO76OA+o4vYPi+6zj4YXeY+Ay+6vD4YXfQ+XXShPhhd9D4D0kWHPhhd9D676Go+RhfnPgPSRUc+AADaPkYXNT4YXcI+A7roIj676Ko+uugiPumiiz4A",+ "AAFGF5096aILPwIYXSQ+6aILPwIYXSQ+uugivQMYXSQ+L7q4vaOLEj6MLgK+A0YXAT4AACi+u+i6PS+6PL4DL7poPV50Ub7poos7XnRRvgMAAAAAXnRRvumii7tedFG+A+miC7xedFG+XnRRvF50Ub4CXnRRvF10Ab4D6aILvF10Ab666KK7XXQBvgOMLrq6XXQBvowuOjtddAG+Ay+6KD1ddAG+XnRxPRhd1L0DRhedPaOLpr1GF509uugivQJGF5096aILPwABXnTxPbroIj8D0kW/PbroIj+66Jo9jC4nPwOji249XXQrP6OLbj1ddDE/A6OLbj1ddDc/uuiaPS+6Oz8D0kW/PQAAQD9edPE9AABAPwN10RE+AABAP+miIz4vujs/A3XRNT5ddDc/ddE1Pl10MT8DddE1Pl10Kz/poiM+jC4nPwN10RE+uugiP1508T266CI/AA=="+ ]+}diff --git a/tests/helpers/assert.ts b/tests/helpers/assert.tsindex db365bf3d..49eb204cc 100644--- a/tests/helpers/assert.ts+++ b/tests/helpers/assert.ts@@ -14,3 +14,10 @@ export function getNodeOrThrow(graph: SceneGraph, id: string): SceneNode {export function childIdAt(node: SceneNode, index: number): string {return expectDefined(node.childIds[index], `child ${index} of ${node.id}`)}++/** A script-visible node's fills, failing when they read `figma.mixed`, as differently filled text does. */+export function expectFills<T>(fills: readonly T[] | symbol, label = 'fills'): readonly T[] {+ if (typeof fills === 'symbol')+ throw new Error(`${label} were expected to be one value, not mixed`)+ return fills+}