Skip to content

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

feat(text): space mixed-size lines as Figma does; case, links, styles, variables per range (#1094)

Danila Poyarkov3cc33aa42653
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b73365f8a..001d58f3e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,12 +5,23 @@
### Breaking changes
- `CORNER_ROTATE_ZONE` is removed from `@open-pencil/core/constants`; the selection's resize and rotation zones are `TRANSFORM_ZONE` and `transformZoneAt` in `@open-pencil/core/geometry`, which also owns the `HandlePosition` and `CornerPosition` types.
+- In scripts, a text node's `textCase`, `textStyleId`, and `fillStyleId` read `figma.mixed` while its characters differ, as in Figma, instead of the text's own value, and setting one restyles every character.
+
+### Added
+
+- Text keeps a case, a link, text and fill styles, and variable bindings for any range of its characters, as in Figma: the canvas draws each range in its own case, `.fig` files and the Figma clipboard keep them, apart from font weight bindings, HTML, Tailwind, and JSX exports write links as `<a href>` and cases as `text-transform` and HTML import reads them back, Design JSX `<Span>` takes `textCase` and `href`, and the Typography section's text case changes the selected characters while text is edited. Scripts read and set them with `getRangeTextCase`, `setRangeTextCase`, `getRangeHyperlink`, `setRangeHyperlink`, `getRangeTextStyleId`, `setRangeTextStyleIdAsync`, `getRangeFillStyleId`, `setRangeFillStyleIdAsync`, `getRangeBoundVariable`, `setRangeBoundVariable`, and the text's `hyperlink`.
### Changed
- A selected layer resizes and rotates where Figma's does: every edge resizes along its whole length within 7.5 px outside it and up to a tenth of the side inside it, corners within 7.5 px, and the area outside a corner within 16 px rotates; a frame's name takes a press before rotation but not before resizing. Layers under 24 px keep these zones outside them, and a layer under 10 px on both sides has none, taking presses within 16 px across its centre instead. A selection draws Figma's four corner handles, without the edge midpoints, and none on such a small layer.
- Pasted layers keep how they were turned and flipped on the canvas, as in Figma, so a layer copied out of a rotated frame stays at its angle in an upright one, and paste to replace keeps the copied layer's angle too. Layers copied out of a frame or section keep their offset from its box on the canvas, and move into the frame only when they start past its far edge, or, for top-level layers, miss it: then layers that fit are centred on that axis, and larger ones go to the frame's top-left, or are centred if top-level. Layers overlapping an edge stay where they are, and layers copied from different places are placed each from its own.
+### Fixed
+
+- Lines of text that mix font sizes or line heights are spaced as in Figma: each line is as tall as the tallest line height on it, with its largest font centred in it, instead of stacking the tallest parts of every style on it, which put lines after a large word or a taller line height up to 10 px off.
+- A line height in pixels shorter than the font, such as 24 px on 24 px text, opens from `.fig` files as set instead of as the font's own height.
+- Text with an empty line, or ending in one, saved to `.fig` or copied to Figma shows there, where Figma showed it blank.
+
## 0.16.0-beta.1 — 2026-10-11
This is a pre-release: npm packages are published under the `next` tag, and installed apps on the stable release do not update to it. Linux package managers see `0.16.0-beta.1` as newer than `0.16.0`, so `.deb` and `.rpm` users should remove the beta before installing the final 0.16.0.
diff --git a/packages/core/src/canvas/scene.ts b/packages/core/src/canvas/scene.ts
index b0e3d0d12..68d68b152 100644
--- a/packages/core/src/canvas/scene.ts
+++ b/packages/core/src/canvas/scene.ts
@@ -13,7 +13,7 @@ import Matrix from '@open-pencil/scene-graph/matrix'
import type { Color } from '@open-pencil/scene-graph/primitives'
import { createSceneGeometry, nodeOrientationMatrix, projectedNode } from '#core/geometry'
-import { transformTextCase } from '#core/text/case'
+import { shownText } from '#core/text/case'
import { fontManager } from '#core/text/fonts'
import { vectorNetworkToCenterlinePath } from '#core/vector'
@@ -1010,13 +1010,7 @@ export function renderText(r: SkiaRenderer, canvas: Canvas, node: SceneNode, fil
} else if (r.textFont) {
const fontSize = node.fontSize || r.DEFAULT_FONT_SIZE
const paragraphY = textVerticalOffset(node, fontSize)
- canvas.drawText(
- transformTextCase(text, node.textCase),
- 0,
- paragraphY + fontSize,
- r.fillPaint,
- r.textFont
- )
+ canvas.drawText(shownText(node), 0, paragraphY + fontSize, r.fillPaint, r.textFont)
}
canvas.restore()
diff --git a/packages/core/src/canvas/text/decorations.ts b/packages/core/src/canvas/text/decorations.ts
index f6022a65b..f5b8dddd3 100644
--- a/packages/core/src/canvas/text/decorations.ts
+++ b/packages/core/src/canvas/text/decorations.ts
@@ -12,7 +12,7 @@ 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 { shownText } 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'
@@ -359,7 +359,7 @@ export function drawTextLayout(
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 glyphs = laidOutGlyphs(node, layout, shownText(node), y)
const rects = glyphs ? textDecorationRects(node, laidOutDecoratedGlyphs(glyphs)) : []
prepared.decorations = { y, rects }
}
diff --git a/packages/core/src/canvas/text/index.ts b/packages/core/src/canvas/text/index.ts
index ab85baf52..284419436 100644
--- a/packages/core/src/canvas/text/index.ts
+++ b/packages/core/src/canvas/text/index.ts
@@ -1,7 +1,7 @@
import type { SceneNode } from '@open-pencil/scene-graph'
import { DEFAULT_FONT_FAMILY } from '#core/constants'
-import { transformTextCase } from '#core/text/case'
+import { shownCharacters, shownText } from '#core/text/case'
import { fontManager, weightToStyle } from '#core/text/fonts'
import {
fontCoverageDemand,
@@ -59,15 +59,7 @@ function languageForCharacter(node: SceneNode, sourceIndex: number): string | nu
}
function transformedSourceOffsets(node: SceneNode): number[] {
- const offsets: number[] = []
- let sourceIndex = 0
- for (const sourceCharacter of node.text) {
- for (const _character of transformTextCase(sourceCharacter, node.textCase)) {
- offsets.push(sourceIndex)
- }
- sourceIndex += sourceCharacter.length
- }
- return offsets
+ return shownCharacters(node).map((shown) => shown.sourceIndex)
}
export type NodeFontReadiness = 'ready' | 'substituted' | 'pending' | 'exhausted'
@@ -126,7 +118,7 @@ function observedGlyphReadiness(r: TextRenderer, node: SceneNode): NodeFontReadi
if (!prepared.missingGlyphs) {
prepared.paragraph.layout(resolveParagraphLayoutWidth(node))
prepared.missingGlyphs = missingGlyphOccurrences(
- transformTextCase(node.text, node.textCase),
+ shownText(node),
prepared.paragraph.getShapedLines(),
transformedSourceOffsets(node)
)
diff --git a/packages/core/src/canvas/text/layout/build.ts b/packages/core/src/canvas/text/layout/build.ts
index 5f6316ef7..1713a3368 100644
--- a/packages/core/src/canvas/text/layout/build.ts
+++ b/packages/core/src/canvas/text/layout/build.ts
@@ -16,6 +16,7 @@ import {
import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text-direction'
import { TextLayout, type TextLayoutBlock, type TextLayoutMarker } from '#core/canvas/text/layout'
+import type { LineHeightRun, TextLayoutBlockLines } from '#core/canvas/text/layout/lines'
import type { ParagraphBuildOptions } from '#core/canvas/text/paint'
import {
buildSkParagraph,
@@ -27,7 +28,7 @@ import type { ParagraphNode } from '#core/canvas/text/paragraph/inputs'
import type { TextRenderer } from '#core/canvas/text/renderer'
import { utf8Length } from '#core/canvas/text/utf8'
import { DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE } from '#core/constants'
-import { transformTextCase } from '#core/text/case'
+import { shownText } from '#core/text/case'
import { weightToStyle } from '#core/text/fonts'
import { glyphAdvanceSync } from '#core/text/opentype'
@@ -58,6 +59,72 @@ function sliceStyleRuns(runs: readonly StyleRun[], start: number, end: number):
return sliced
}
+/** Line heights by paragraph index, `lead` places before the text: each run's, the text's elsewhere. */
+function lineHeightRuns(node: ParagraphNode, lead: number): LineHeightRun[] {
+ const own = node.lineHeight || null
+ const runs: LineHeightRun[] = []
+ const add = (start: number, end: number, lineHeight: number | null) => {
+ const last = runs.at(-1)
+ // Runs at one line height measure as one, whatever else they style.
+ if (last && last.end === start && last.lineHeight === lineHeight) last.end = end
+ else runs.push({ start, end, lineHeight })
+ }
+ let position = 0
+ for (const run of node.styleRuns) {
+ if (position < run.start) add(position + lead, run.start + lead, own)
+ const lineHeight = run.style.lineHeight !== undefined ? run.style.lineHeight || null : own
+ add(run.start + lead, run.start + run.length + lead, lineHeight)
+ position = run.start + run.length
+ }
+ if (position < node.text.length) add(position + lead, node.text.length + lead, own)
+ return runs
+}
+
+/**
+ * What placing a paragraph's lines as Figma does needs: its line heights, and its lines laid
+ * out one by one from `node`'s text, the first after its indent and the last truncated as the
+ * paragraph is.
+ */
+function paragraphLines(
+ r: TextRenderer,
+ node: ParagraphNode,
+ color: Float32Array | undefined,
+ options: ParagraphBuildOptions,
+ firstLineIndent = 0
+): TextLayoutBlockLines | undefined {
+ // Lines are cut by character index, which the text's case must keep.
+ if (shownText(node).length !== node.text.length) return undefined
+ const lead = firstLineIndent > 0 ? 1 : 0
+ const ellipsis = buildTruncateOpts(node, node.fontSize || DEFAULT_FONT_SIZE).ellipsis
+ // A justified line is stretched only with text after it: lines are laid out with the rest
+ // of the paragraph and cut, as truncated last lines are.
+ const justified = node.textAlignHorizontal === 'JUSTIFIED'
+ const lineTruncation = (lines: number, truncated: boolean) => {
+ if (truncated) return { maxLines: lines, ellipsis }
+ return justified ? { maxLines: lines } : {}
+ }
+ return {
+ heights: lineHeightRuns(node, lead),
+ // A trimmed edge is laid out by where it stands in the paragraph.
+ build:
+ node.leadingTrim === 'CAP_HEIGHT'
+ ? undefined
+ : (start, end, lines, truncated) => {
+ const from = Math.max(0, start - lead)
+ const to = justified ? node.text.length : end - lead
+ const line: ParagraphNode = {
+ ...node,
+ text: node.text.slice(from, to),
+ styleRuns: sliceStyleRuns(node.styleRuns, from, to)
+ }
+ return buildSkParagraph(r, line, color, options, {
+ firstLineIndent: start === 0 ? firstLineIndent : 0,
+ truncation: lineTruncation(lines, truncated)
+ })
+ }
+ }
+}
+
/** Whether the text lays out paragraph by paragraph rather than as one native paragraph. */
function needsParagraphLayout(node: ParagraphNode): boolean {
return (
@@ -136,9 +203,9 @@ function buildBlocks(
color: Float32Array | undefined,
options: ParagraphBuildOptions
): TextLayout {
- const shownText = transformTextCase(node.text, node.textCase)
+ const shown = shownText(node)
const sources = textParagraphRanges(node.text)
- const shown = textParagraphRanges(shownText)
+ const shownRanges = textParagraphRanges(shown)
const items = new Map(
textListItems(node.text, node.textParagraphs).map((item) => [item.paragraph, item])
)
@@ -149,9 +216,9 @@ function buildBlocks(
// Each paragraph starts one byte, its newline, after the one before it ends.
const utf8Starts: number[] = []
let utf8Offset = 0
- for (const range of shown) {
+ for (const range of shownRanges) {
utf8Starts.push(utf8Offset)
- utf8Offset += utf8Length(shownText.slice(range.start, range.end)) + 1
+ utf8Offset += utf8Length(shown.slice(range.start, range.end)) + 1
}
const blocks: TextLayoutBlock[] = []
@@ -170,7 +237,7 @@ function buildBlocks(
return new TextLayout(r.ck, blocks, maxLines)
function buildBlock(index: number, start: number, end: number): TextLayoutBlock {
- const shownRange: TextParagraphRange = shown[index]
+ const shownRange: TextParagraphRange = shownRanges[index]
const item = items.get(index)
const paragraphStyle = paragraphStyleAt(node.textParagraphs, index)
const empty = end === start
@@ -223,6 +290,7 @@ function buildBlocks(
? 0
: paragraphSpacingAt(node, index - 1, betweenItems ? 'listSpacing' : 'paragraphSpacing'),
marker,
+ lines: paragraphLines(r, blockNode, color, options, firstLineIndent),
x: 0,
y: 0,
visible: true
@@ -283,7 +351,8 @@ export function buildParagraph(
: TextLayout.ofParagraph(
r.ck,
buildSkParagraph(r, node, color, options),
- transformTextCase(node.text, node.textCase).length
+ shownText(node).length,
+ paragraphLines(r, node, color, options)
)
try {
layoutForNode(layout, node)
diff --git a/packages/core/src/canvas/text/layout/index.ts b/packages/core/src/canvas/text/layout/index.ts
index 4032f2e01..3c4dd0f2b 100644
--- a/packages/core/src/canvas/text/layout/index.ts
+++ b/packages/core/src/canvas/text/layout/index.ts
@@ -10,6 +10,13 @@ import type {
ShapedLine
} from 'canvaskit-wasm'
+import {
+ placeLines,
+ shapedLinesByLine,
+ type BlockPlacement,
+ type TextLayoutBlockLines
+} from '#core/canvas/text/layout/lines'
+
/** A list item's number or bullet, laid out on its own. */
export interface TextLayoutMarker {
paragraph: Paragraph
@@ -46,6 +53,8 @@ export interface TextLayoutBlock {
/** Space above the block, from the paragraph before it. */
spaceBefore: number
marker: TextLayoutMarker | null
+ /** What placing its lines as Figma does needs; without it they stack as the paragraph's. */
+ lines?: TextLayoutBlockLines
x: number
y: number
/** Whether the block is shown, as truncation hides blocks past its last line. */
@@ -68,9 +77,17 @@ export class TextLayout {
private lines: LineMetrics[] = []
private lineOffsets: number[] = []
private truncated = false
+ private readonly placements = new Map<TextLayoutBlock, BlockPlacement>()
+ /** The text's height when layout placed its lines itself. */
+ private placedHeight: number | null = null
/** Text laid out as one native paragraph of `length` characters, not yet laid out. */
- static ofParagraph(ck: CanvasKit, paragraph: Paragraph, length: number): TextLayout {
+ static ofParagraph(
+ ck: CanvasKit,
+ paragraph: Paragraph,
+ length: number,
+ lines?: TextLayoutBlockLines
+ ): TextLayout {
return new TextLayout(ck, [
{
paragraph,
@@ -85,6 +102,7 @@ export class TextLayout {
rtl: false,
spaceBefore: 0,
marker: null,
+ lines,
x: 0,
y: 0,
visible: true
@@ -110,6 +128,7 @@ export class TextLayout {
let y = 0
let lines = 0
this.truncated = false
+ this.clearPlacements()
for (const [index, block] of this.blocks.entries()) {
const remaining = this.maxLines === undefined ? Infinity : this.maxLines - lines
block.visible = remaining > 0
@@ -134,11 +153,52 @@ export class TextLayout {
block.y = y
y += block.paragraph.getHeight()
lines += block.paragraph.getLineMetrics().length
- this.placeMarker(block)
}
+ this.placeLines(width)
+ for (const block of this.visibleBlocks()) this.placeMarker(block)
this.collectLines()
}
+ private clearPlacements(): void {
+ for (const placement of this.placements.values()) {
+ for (const piece of placement.pieces ?? []) piece.paragraph.delete()
+ }
+ this.placements.clear()
+ this.placedHeight = null
+ }
+
+ /**
+ * Places lines as Figma does when they differ in height, keeping the paragraph's placement
+ * otherwise (`placeLines`).
+ */
+ private placeLines(width: number): void {
+ const placed = placeLines(this.ck, this.visibleBlocks(), width)
+ if (!placed) return
+ for (const [block, { y, ...placement }] of placed.blocks) {
+ block.y = y
+ this.placements.set(block, placement)
+ }
+ this.placedHeight = placed.height
+ }
+
+ /** The block's line `index` stands this far below where its paragraph has it. */
+ private lineOffset(block: TextLayoutBlock, index: number): number {
+ return this.placements.get(block)?.offsets[index] ?? 0
+ }
+
+ /** How far a point `y` of the block's paragraph moves, by the line it falls on. */
+ private offsetAt(block: TextLayoutBlock, y: number): number {
+ const placement = this.placements.get(block)
+ if (!placement) return 0
+ const lines = block.paragraph.getLineMetrics()
+ const index = lines.findIndex((line) => y < line.baseline + line.descent)
+ return placement.offsets[index === -1 ? lines.length - 1 : index] ?? 0
+ }
+
+ private blockHeight(block: TextLayoutBlock): number {
+ return this.placements.get(block)?.height ?? block.paragraph.getHeight()
+ }
+
private placeMarker(block: TextLayoutBlock): void {
const marker = block.marker
const first = block.paragraph.getLineMetrics().at(0)
@@ -173,14 +233,21 @@ export class TextLayout {
this.lineOffsets.push(this.lines.length)
if (block.marker) block.marker.lineNumber = this.lines.length
const metrics = block.paragraph.getLineMetrics()
+ const boxes = this.placements.get(block)?.boxes
const blockEnd = block.start + block.length
for (const [lineIndex, line] of metrics.entries()) {
const lastOfBlock = lineIndex === metrics.length - 1
const endsAtNewline = lastOfBlock && blockIndex < visible.length - 1
// A first-line indent is room before the text, not part of the line.
const indent = lineIndex === 0 ? block.leadWidth : 0
+ const box = boxes?.[lineIndex]
this.lines.push({
...line,
+ ...(box && {
+ ascent: box.ascent,
+ descent: box.height - box.ascent,
+ height: box.height
+ }),
startIndex: this.toTextIndex(block, line.startIndex),
endIndex: this.toTextIndex(block, line.endIndex),
endExcludingWhitespaces: this.toTextIndex(block, line.endExcludingWhitespaces),
@@ -190,7 +257,7 @@ export class TextLayout {
isHardBreak: endsAtNewline || line.isHardBreak,
width: block.empty ? 0 : line.width - indent,
left: line.left + block.x + (block.rtl ? 0 : indent),
- baseline: line.baseline + block.y,
+ baseline: line.baseline + block.y + this.lineOffset(block, lineIndex),
lineNumber: this.lines.length
})
}
@@ -199,6 +266,7 @@ export class TextLayout {
getHeight(): number {
const last = this.visibleBlocks().at(-1)
+ if (this.placedHeight !== null) return this.placedHeight
return last ? last.y + last.paragraph.getHeight() : 0
}
@@ -253,14 +321,17 @@ export class TextLayout {
let block = visible.at(-1)
for (const [index, candidate] of visible.entries()) {
const next = visible.at(index + 1)
- const bottom = candidate.y + candidate.paragraph.getHeight()
+ const bottom = candidate.y + this.blockHeight(candidate)
if (!next || y < bottom + next.spaceBefore / 2) {
block = candidate
break
}
}
if (!block) return { pos: 0, affinity: this.ck.Affinity.Downstream }
- const local = block.paragraph.getGlyphPositionAtCoordinate(x - block.x, y - block.y)
+ const local = block.paragraph.getGlyphPositionAtCoordinate(
+ x - block.x,
+ this.paragraphY(block, y - block.y)
+ )
return {
pos: block.empty ? block.start : this.toTextIndex(block, local.pos),
affinity: local.affinity
@@ -286,13 +357,9 @@ export class TextLayout {
widthStyle
)
for (const { rect, dir } of local) {
+ const y = block.y + this.offsetAt(block, (rect[1] + rect[3]) / 2)
rects.push({
- rect: Float32Array.of(
- rect[0] + block.x,
- rect[1] + block.y,
- rect[2] + block.x,
- rect[3] + block.y
- ),
+ rect: Float32Array.of(rect[0] + block.x, rect[1] + y, rect[2] + block.x, rect[3] + y),
dir
})
}
@@ -340,35 +407,52 @@ export class TextLayout {
)
const rect = rects.at(0)?.rect
if (!rect) return null
+ const y = block.y + this.offsetAt(block, (rect[1] + rect[3]) / 2)
return {
x: block.x + (useRight ? rect[2] : rect[0]),
- top: block.y + rect[1],
- bottom: block.y + rect[3]
+ top: y + rect[1],
+ bottom: y + rect[3]
}
}
/**
- * Shaped lines of the text in whole-text coordinates; run offsets are UTF-8 byte offsets into
- * the whole text, as CanvasKit gives them. An empty paragraph's line has no runs.
+ * Shaped lines of the text in whole-text coordinates, one per line; run offsets are UTF-8
+ * byte offsets into the whole text, as CanvasKit gives them. An empty line, which shaping
+ * leaves out, has no runs and starts where the line before it ends.
*/
getShapedLines(): ShapedLine[] {
const shaped: ShapedLine[] = []
for (const block of this.visibleBlocks()) {
- for (const line of block.paragraph.getShapedLines()) {
+ const metrics = block.paragraph.getLineMetrics()
+ for (const [lineIndex, line] of shapedLinesByLine(block.paragraph).entries()) {
+ const y = block.y + this.lineOffset(block, lineIndex)
+ if (!line) {
+ const { baseline, ascent, descent } = metrics[lineIndex]
+ const previous = lineIndex > 0 ? shaped.at(-1) : undefined
+ const start = previous?.textRange.last ?? block.utf8Start
+ shaped.push({
+ textRange: { first: start, last: start },
+ top: baseline - ascent + y,
+ bottom: baseline + descent + y,
+ baseline: baseline + y,
+ runs: []
+ })
+ continue
+ }
shaped.push({
textRange: {
first: this.toUtf8(block, line.textRange.first),
last: this.toUtf8(block, line.textRange.last)
},
- top: line.top + block.y,
- bottom: line.bottom + block.y,
- baseline: line.baseline + block.y,
+ top: line.top + y,
+ bottom: line.bottom + y,
+ baseline: line.baseline + y,
runs: block.empty
? []
: line.runs.map((run) => ({
...run,
positions: run.positions.map(
- (value, index) => value + (index % 2 === 0 ? block.x : block.y)
+ (value, index) => value + (index % 2 === 0 ? block.x : y)
),
offsets: run.offsets.map((offset) => this.toUtf8(block, offset))
}))
@@ -391,17 +475,37 @@ export class TextLayout {
draw(canvas: Canvas, x: number, y: number): void {
for (const block of this.visibleBlocks()) {
- canvas.drawParagraph(block.paragraph, x + block.x, y + block.y)
+ const pieces = this.placements.get(block)?.pieces
+ if (!pieces) canvas.drawParagraph(block.paragraph, x + block.x, y + block.y)
+ for (const piece of pieces ?? []) {
+ canvas.drawParagraph(piece.paragraph, x + block.x + piece.x, y + block.y + piece.y)
+ }
const marker = block.marker
if (marker) canvas.drawParagraph(marker.paragraph, x + marker.x, y + marker.y)
}
}
+ /** Where in the block's paragraph a point `y` below the block's top falls, by its line. */
+ private paragraphY(block: TextLayoutBlock, y: number): number {
+ const placement = this.placements.get(block)
+ if (!placement) return y
+ const lines = block.paragraph.getLineMetrics()
+ // A point belongs to the line whose box it is in, or the nearest after the one above it.
+ const index = lines.findIndex((line, lineIndex) => {
+ const box = placement.boxes[lineIndex]
+ const baseline = line.baseline + placement.offsets[lineIndex]
+ return y < baseline - box.ascent + box.height
+ })
+ const line = lines[index === -1 ? lines.length - 1 : index]
+ return line.baseline
+ }
+
isDeleted(): boolean {
return this.blocks.every((block) => block.paragraph.isDeleted())
}
delete(): void {
+ this.clearPlacements()
for (const block of this.blocks) {
block.paragraph.delete()
block.marker?.paragraph.delete()
diff --git a/packages/core/src/canvas/text/layout/lines.ts b/packages/core/src/canvas/text/layout/lines.ts
new file mode 100644
index 000000000..c2150fe51
--- /dev/null
+++ b/packages/core/src/canvas/text/layout/lines.ts
@@ -0,0 +1,293 @@
+import type { CanvasKit, LineMetrics, Paragraph, ShapedLine } from 'canvaskit-wasm'
+
+import type { Vector } from '@open-pencil/scene-graph'
+
+/** A stretch of a paragraph's characters set at one line height, `null` for auto. */
+export interface LineHeightRun {
+ start: number
+ end: number
+ lineHeight: number | null
+}
+
+/** A block's line heights, and how to lay one of its lines out on its own. */
+export interface TextLayoutBlockLines {
+ /** Line heights by paragraph index, lead included. */
+ heights: LineHeightRun[]
+ /**
+ * The paragraph's characters from `start` as a paragraph of their own, holding its `lines`
+ * lines up to `end`, and ending in the ellipsis when `truncated`; absent when lines cannot
+ * be drawn apart from the others.
+ */
+ build?: (start: number, end: number, lines: number, truncated: boolean) => Paragraph
+}
+
+/** What placing a text layout block's lines reads of it. */
+interface LineBlock {
+ paragraph: Paragraph
+ lines?: TextLayoutBlockLines
+ lead: number
+ length: number
+ inset: number
+ spaceBefore: number
+ y: number
+}
+
+/** Lines laid out as a paragraph of their own, and where its top left goes in its block. */
+export interface LinePiece {
+ paragraph: Paragraph
+ x: number
+ y: number
+}
+
+/** Where a block's lines go when they do not stack as its paragraph has them. */
+export interface BlockPlacement {
+ height: number
+ /** How far each line stands below where the paragraph has it. */
+ offsets: number[]
+ boxes: LineBox[]
+ /** Paragraphs of lines that move together, drawn in place of the block's when lines move apart. */
+ pieces: LinePiece[] | null
+}
+
+/** A line as Figma sets it: its height, and how far its baseline stands below its top. */
+export interface LineBox {
+ height: number
+ ascent: number
+}
+
+/** The difference below which two line positions count as the same. */
+const LINE_EPSILON = 0.01
+/**
+ * Steps font metrics are measured in. Rects come in float32, whose error at a line far down a
+ * text reaches the sixth digit, so lines in the same font would measure apart.
+ */
+const METRIC_STEPS = 1e4
+
+function metric(value: number): number {
+ return Math.round(value * METRIC_STEPS) / METRIC_STEPS
+}
+
+/**
+ * A line's box as Figma sets it. The line is as tall as the tallest line height on it, auto
+ * standing for a font's own height rounded to a whole pixel, and its baseline sits where its
+ * tallest font, centred in that height, puts it. Fonts' heights are the shaped runs' own, so a
+ * fallback font counts with its metrics. Returns `null` for a line with nothing to measure.
+ */
+export function figmaLineBox(
+ ck: CanvasKit,
+ paragraph: Paragraph,
+ line: LineMetrics,
+ runs: readonly LineHeightRun[]
+): LineBox | null {
+ // An empty line is as tall as the newline that makes it.
+ const start = line.startIndex
+ const end = Math.max(line.endIndex, start + 1)
+ let height = 0
+ let natural = 0
+ let ascent = 0
+ for (const run of runs) {
+ const from = Math.max(start, run.start)
+ const to = Math.min(end, run.end)
+ if (to <= from) continue
+ const rects = paragraph.getRectsForRange(
+ from,
+ to,
+ ck.RectHeightStyle.Tight,
+ ck.RectWidthStyle.Tight
+ )
+ for (const { rect } of rects) {
+ const runNatural = metric(rect[3] - rect[1])
+ // A first-line indent is a placeholder with no height.
+ if (runNatural <= 0) continue
+ height = Math.max(height, Math.round(run.lineHeight ?? runNatural))
+ if (runNatural > natural) {
+ natural = runNatural
+ ascent = metric(line.baseline - rect[1])
+ }
+ }
+ }
+ if (natural === 0) return null
+ return { height, ascent: (height - natural) / 2 + ascent }
+}
+
+/** Whether all `values` are the same, to within the precision lines are placed with. */
+export function allSame(values: readonly number[]): boolean {
+ const first = values.at(0)
+ return first === undefined || values.every((value) => Math.abs(value - first) < LINE_EPSILON)
+}
+
+/** Each block's lines as Figma sets them, or `null` when one cannot be measured. */
+function lineBoxes(
+ ck: CanvasKit,
+ blocks: readonly LineBlock[],
+ metrics: readonly LineMetrics[][]
+): LineBox[][] | null {
+ const boxes: LineBox[][] = []
+ for (const [index, block] of blocks.entries()) {
+ const heights = block.lines?.heights
+ if (!heights) return null
+ const blockBoxes: LineBox[] = []
+ for (const line of metrics[index]) {
+ const box = figmaLineBox(ck, block.paragraph, line, heights)
+ if (!box) return null
+ blockBoxes.push(box)
+ }
+ boxes.push(blockBoxes)
+ }
+ return boxes
+}
+
+/**
+ * A paragraph's shaped lines by line number. Shaping leaves empty lines out, so each shaped
+ * line goes to the line whose baseline is nearest its own.
+ */
+export function shapedLinesByLine(paragraph: Paragraph): Array<ShapedLine | undefined> {
+ const lines = paragraph.getLineMetrics()
+ const byLine: Array<ShapedLine | undefined> = Array.from({ length: lines.length })
+ for (const shaped of paragraph.getShapedLines()) {
+ let nearest = 0
+ for (const [index, line] of lines.entries()) {
+ const distance = Math.abs(line.baseline - shaped.baseline)
+ if (distance < Math.abs(lines[nearest].baseline - shaped.baseline)) nearest = index
+ }
+ byLine[nearest] = shaped
+ }
+ return byLine
+}
+
+/** Where a shaped line's first glyph stands, if it has one. */
+function firstGlyph(line: ShapedLine | undefined): [number, number] | null {
+ const positions = line?.runs.find((run) => run.glyphs.length > 0)?.positions
+ return positions ? [positions[0], positions[1]] : null
+}
+
+/** How far glyphs a piece draws must move to land where the block's lines have them. */
+function pieceShift(
+ shaped: ReadonlyArray<ShapedLine | undefined>,
+ own: ReadonlyArray<ShapedLine | undefined>
+): (Vector & { agrees: number }) | null {
+ let shift: Vector | null = null
+ // Paragraphs snap each line to whole-pixel baselines their own way, so lines of one piece
+ // may need different shifts; the piece holds the lines that agree with its first.
+ for (const [index, line] of own.entries()) {
+ const glyph = firstGlyph(shaped[index])
+ const ownGlyph = firstGlyph(line)
+ if (!glyph || !ownGlyph) continue
+ const x = glyph[0] - ownGlyph[0]
+ const y = glyph[1] - ownGlyph[1]
+ if (!shift) shift = { x, y }
+ else if (!allSame([shift.x, x]) || !allSame([shift.y, y])) return { ...shift, agrees: index }
+ }
+ return shift && { ...shift, agrees: own.length }
+}
+
+/**
+ * The block's lines as paragraphs of their own, one for each run of lines that move by the
+ * same offset, or one per line when not `grouped`, placed so their glyphs land where the
+ * block's paragraph has them, moved by that offset. `null` when lines cannot be laid out
+ * apart from the others.
+ */
+function buildPieces(
+ block: LineBlock,
+ width: number,
+ offsets: readonly number[],
+ grouped = true
+): LinePiece[] | null {
+ const build = block.lines?.build
+ if (!build) return null
+ const lines = block.paragraph.getLineMetrics()
+ const shaped = shapedLinesByLine(block.paragraph)
+ const truncated = block.paragraph.didExceedMaxLines()
+ const textEnd = block.lead + block.length
+ const pieces: LinePiece[] = []
+ let from = 0
+ while (from < lines.length) {
+ let to = from + 1
+ if (grouped) while (to < lines.length && allSame([offsets[from], offsets[to]])) to++
+ const start = lines[from].startIndex
+ const end = to === lines.length ? textEnd : lines[to - 1].endIndex
+ // Empty lines draw nothing.
+ if (end <= start) {
+ from = to
+ continue
+ }
+ const count = to - from
+ const paragraph = build(start, end, count, to === lines.length && truncated)
+ paragraph.layout(Math.max(1, width - block.inset))
+ const own = paragraph.getLineMetrics().length === count ? shapedLinesByLine(paragraph) : null
+ const shift = own && pieceShift(shaped.slice(from, to), own)
+ if (!shift || shift.agrees < count) {
+ paragraph.delete()
+ for (const piece of pieces) piece.paragraph.delete()
+ // Lines that lay out or snap apart are drawn one by one.
+ return grouped ? buildPieces(block, width, offsets, false) : null
+ }
+ pieces.push({ paragraph, x: shift.x, y: shift.y + offsets[from] })
+ from = to
+ }
+ return pieces
+}
+
+/** Where `placeLines` puts each block, and the text's height. */
+export interface PlacedLines<Block> {
+ blocks: Map<Block, BlockPlacement & { y: number }>
+ height: number
+}
+
+/**
+ * Lines of laid-out blocks placed as Figma places them when they differ in height: each
+ * line is as tall as its tallest line height, and each baseline stands that far, plus the
+ * paragraph's spacing, below the one before, where a paragraph would stack the lines' boxes.
+ * `null` keeps the paragraphs' placement: for lines alike, where it is the same, and for
+ * lines that cannot be measured or drawn apart.
+ */
+export function placeLines<Block extends LineBlock>(
+ ck: CanvasKit,
+ blocks: readonly Block[],
+ width: number
+): PlacedLines<Block> | null {
+ const metrics = blocks.map((block) => block.paragraph.getLineMetrics())
+ // A single line has none to be spaced from.
+ if (metrics.flat().length < 2) return null
+ const boxes = lineBoxes(ck, blocks, metrics)
+ if (!boxes) return null
+ const all = boxes.flat()
+ if (allSame(all.map((box) => box.height)) && allSame(all.map((box) => box.ascent))) return null
+
+ // Distances from the first baseline add up whole-pixel line heights, so they stay exact.
+ const first = all[0]
+ const last = all[all.length - 1]
+ let below = 0
+ const baselines = blocks.map((block, index) =>
+ boxes[index].map((box, line) => {
+ if (index > 0 || line > 0) below += box.height + (line === 0 ? block.spaceBefore : 0)
+ return first.ascent + below
+ })
+ )
+ const placed = new Map<Block, BlockPlacement & { y: number }>()
+ for (const [index, block] of blocks.entries()) {
+ const lines = metrics[index]
+ const blockBoxes = boxes[index]
+ const blockBaselines = baselines[index]
+ const end = blockBoxes.length - 1
+ const y = blockBaselines[0] - lines[0].baseline
+ const offsets = lines.map((line, lineIndex) => blockBaselines[lineIndex] - y - line.baseline)
+ const apart = !allSame(offsets)
+ const pieces = apart ? buildPieces(block, width, offsets) : null
+ placed.set(block, {
+ y,
+ height: blockBaselines[end] - blockBoxes[end].ascent + blockBoxes[end].height - y,
+ offsets,
+ boxes: blockBoxes,
+ pieces
+ })
+ // Lines that cannot be drawn apart keep the paragraph's placement, and so does the text.
+ if (apart && !pieces) {
+ for (const placement of placed.values()) {
+ for (const piece of placement.pieces ?? []) piece.paragraph.delete()
+ }
+ return null
+ }
+ }
+ return { blocks: placed, height: first.ascent - last.ascent + below + last.height }
+}
diff --git a/packages/core/src/canvas/text/paragraph/index.ts b/packages/core/src/canvas/text/paragraph/index.ts
index 2d0c9b70e..0e172596d 100644
--- a/packages/core/src/canvas/text/paragraph/index.ts
+++ b/packages/core/src/canvas/text/paragraph/index.ts
@@ -21,7 +21,7 @@ import {
} from '#core/canvas/text/paint'
import type { TextRenderer } from '#core/canvas/text/renderer'
import { DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE } from '#core/constants'
-import { transformTextCase } from '#core/text/case'
+import { shownTextSlice } from '#core/text/case'
import { fontManager, weightToStyle } from '#core/text/fonts'
import type { ParagraphNode } from './inputs'
@@ -174,12 +174,14 @@ function pushStyleRun(
pushParagraphStyle(builder, textStyle, paintStyle)
}
+/** `text[start, end)` in the case each of its characters has. */
function addParagraphText(
builder: ParagraphBuilder,
- node: Pick<ParagraphNode, 'textCase'>,
- text: string
+ node: ParagraphNode,
+ start: number,
+ end: number
): void {
- builder.addText(transformTextCase(text, node.textCase))
+ builder.addText(shownTextSlice(node, start, end))
}
function addStyledRuns(
@@ -196,7 +198,7 @@ function addStyledRuns(
let pos = 0
for (const run of node.styleRuns) {
- if (pos < run.start) addParagraphText(builder, node, text.slice(pos, run.start))
+ if (pos < run.start) addParagraphText(builder, node, pos, run.start)
pushStyleRun(
r,
builder,
@@ -208,12 +210,12 @@ function addStyledRuns(
halfLeading,
paintStyle
)
- addParagraphText(builder, node, text.slice(run.start, run.start + run.length))
+ addParagraphText(builder, node, run.start, run.start + run.length)
builder.pop()
pos = run.start + run.length
}
- if (pos < text.length) addParagraphText(builder, node, text.slice(pos))
+ if (pos < text.length) addParagraphText(builder, node, pos, text.length)
}
/** What a paragraph that is one block of a longer text needs beyond its node's own style. */
@@ -305,7 +307,7 @@ export function buildSkParagraph(
}
if (block.firstLineIndent) addFirstLineIndent(ck, builder, block.firstLineIndent)
if (node.styleRuns.length === 0) {
- addParagraphText(builder, node, node.text)
+ addParagraphText(builder, node, 0, node.text.length)
} else {
addStyledRuns(
r,
diff --git a/packages/core/src/canvas/text/shape.ts b/packages/core/src/canvas/text/shape.ts
index 0bebdfff1..7ba5da141 100644
--- a/packages/core/src/canvas/text/shape.ts
+++ b/packages/core/src/canvas/text/shape.ts
@@ -15,7 +15,7 @@ import { textDecorationRects, type DecoratedGlyph } from '#core/canvas/text/deco
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 { shownText } from '#core/text/case'
import { fontManager } from '#core/text/fonts'
/**
@@ -48,7 +48,7 @@ export function shapeText(
fontProvider: TypefaceFontProvider,
node: SceneNode
): ShapedText | null {
- const text = transformTextCase(node.text, node.textCase)
+ const text = shownText(node)
if (!canShape(node, text)) return null
const paragraph = buildParagraph({ ck, fontProvider, fontsLoaded: true }, node, undefined, {
diff --git a/packages/core/src/editor/clipboard/snapshot.ts b/packages/core/src/editor/clipboard/snapshot.ts
index b8940c2a8..68a8414e6 100644
--- a/packages/core/src/editor/clipboard/snapshot.ts
+++ b/packages/core/src/editor/clipboard/snapshot.ts
@@ -1,4 +1,4 @@
-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import { styleRunReferences, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
import { clipboardPlacement, type ClipboardPlacement } from './placement'
import { captureClipboardVariables, type ClipboardVariables } from './variables'
@@ -24,7 +24,8 @@ function referencedStyleIds(nodes: SceneNode[]): Set<string> {
node.strokeStyleId,
node.textStyleId,
node.effectStyleId,
- node.gridStyleId
+ node.gridStyleId,
+ ...styleRunReferences(node.styleRuns).styles
]) {
if (id) ids.add(id)
}
diff --git a/packages/core/src/editor/clipboard/variables.ts b/packages/core/src/editor/clipboard/variables.ts
index 60e06c174..d72479f1f 100644
--- a/packages/core/src/editor/clipboard/variables.ts
+++ b/packages/core/src/editor/clipboard/variables.ts
@@ -1,4 +1,11 @@
-import type { SceneGraph, SceneNode, Variable, VariableCollection } from '@open-pencil/scene-graph'
+import {
+ remapStyleRunReferences,
+ styleRunReferences,
+ type SceneGraph,
+ type SceneNode,
+ type Variable,
+ type VariableCollection
+} from '@open-pencil/scene-graph'
export interface ClipboardVariables {
activeModes: Array<[string, string]>
@@ -23,7 +30,10 @@ export function captureClipboardVariables(
if (typeof value === 'object' && 'aliasId' in value) visit(value.aliasId)
}
}
- for (const node of nodes) for (const id of Object.values(node.boundVariables)) visit(id)
+ for (const node of nodes) {
+ for (const id of Object.values(node.boundVariables)) visit(id)
+ for (const id of styleRunReferences(node.styleRuns).variables) visit(id)
+ }
const activeModes: Array<[string, string]> = []
for (const collectionId of collections.keys()) {
const modeId = graph.activeMode.get(collectionId)
@@ -112,4 +122,8 @@ export function remapClipboardVariableBindings(
const id = node[key]
if (id && styleIds.has(id)) node[key] = styleIds.get(id) ?? id
}
+ node.styleRuns = remapStyleRunReferences(node.styleRuns, {
+ variable: (id) => variables.get(id) ?? id,
+ style: (id) => styleIds.get(id) ?? id
+ })
}
diff --git a/packages/core/src/editor/text/selection-style.ts b/packages/core/src/editor/text/selection-style.ts
index da77c7be6..983353658 100644
--- a/packages/core/src/editor/text/selection-style.ts
+++ b/packages/core/src/editor/text/selection-style.ts
@@ -115,7 +115,8 @@ export function createTextSelectionStyle(
const range = selectedRange(node.id)
if (!range) return null
const [style] = characterStyles(node, range[0], range[0] + 1)
- return { ...style }
+ // Links, styles, and bindings of characters are not the layer's own properties.
+ return pick(style, TEXT_STYLE_KEYS)
}
return { updateNode, updateNodeWithUndo, commitNodeUpdate, selectionStyle }
diff --git a/packages/core/src/figma-api/accessors/text/hyperlink.ts b/packages/core/src/figma-api/accessors/text/hyperlink.ts
new file mode 100644
index 000000000..93bc3d105
--- /dev/null
+++ b/packages/core/src/figma-api/accessors/text/hyperlink.ts
@@ -0,0 +1,59 @@
+import type { HyperlinkTarget, NodeType, SceneGraph } from '@open-pencil/scene-graph'
+
+import { invalid, received } from './messages'
+
+const HYPERLINK_TYPES = new Set(['URL', 'NODE'])
+
+/**
+ * URLs Figma links to: web addresses with a host, in lower case and without surrounding space,
+ * and mail and phone links. Measured in live Figma (2026-10-11).
+ */
+const LINK_URL = /^(?:https?:\/\/[^\s/?#]+\S*|mailto:\S+|tel:\S+)$/
+
+/** Layers a link may lead to, which Figma frames in view: containers and pages. */
+const LINK_TARGETS = new Set<NodeType>([
+ 'CANVAS',
+ 'FRAME',
+ 'SECTION',
+ 'GROUP',
+ 'COMPONENT',
+ 'COMPONENT_SET',
+ 'INSTANCE'
+])
+
+/**
+ * A link Figma takes: a URL it supports or a layer it can show, or `null` to remove one. An
+ * empty URL removes the link, as in Figma.
+ */
+export function hyperlinkTarget(
+ method: string,
+ value: unknown,
+ graph: SceneGraph
+): HyperlinkTarget | null {
+ if (value === null) return null
+ if (typeof value !== 'object' || Array.isArray(value)) {
+ throw invalid(method, `Expected object, received ${received(value)}`)
+ }
+ const target = value as Partial<Record<keyof HyperlinkTarget, unknown>>
+ if (!HYPERLINK_TYPES.has(target.type as string)) {
+ throw invalid(
+ method,
+ `Invalid enum value. Expected 'URL' | 'NODE', received '${String(target.type)}' at .type`
+ )
+ }
+ if (typeof target.value !== 'string') {
+ throw invalid(method, `Expected string, received ${received(target.value)} at .value`)
+ }
+ if (target.type === 'URL') {
+ if (target.value === '') return null
+ if (!LINK_URL.test(target.value)) {
+ throw new Error(`in ${method}: Unsupported or invalid hyperlink url`)
+ }
+ return { type: 'URL', value: target.value }
+ }
+ const layer = graph.getNode(target.value)
+ if (!layer || !LINK_TARGETS.has(layer.type)) {
+ throw new Error(`in ${method}: Invalid hyperlink target node specified`)
+ }
+ return { type: 'NODE', value: target.value }
+}
diff --git a/packages/core/src/figma-api/accessors/text/index.ts b/packages/core/src/figma-api/accessors/text/index.ts
index 1e085739e..592516ad5 100644
--- a/packages/core/src/figma-api/accessors/text/index.ts
+++ b/packages/core/src/figma-api/accessors/text/index.ts
@@ -1,10 +1,13 @@
import type {
CharacterStyleOverride,
+ HyperlinkTarget,
SceneNode,
+ TextCase,
TextParagraphSpacingField
} from '@open-pencil/scene-graph'
import {
+ graph,
raw,
updateNode,
type NodeProxyInternals,
@@ -21,7 +24,9 @@ import {
type FigmaLineHeight
} from '#core/figma-api/text'
import { getTextStyle, type TextSegmentField } from '#core/figma-api/text/style'
-import { textStyleChanges } from '#core/text/character-style'
+import { styleRunsWithPatch, textStyleChanges } from '#core/text/character-style'
+
+import { hyperlinkTarget } from './hyperlink'
/**
* Getter/setter pair for a spacing Figma keeps at zero or more. It reads `mixed` while paragraphs
@@ -105,14 +110,9 @@ export function installTextNodeProxyAccessors(
fontSize: characterStyle<number>(internals, 'fontSize', mixed, (_node, fontSize) => ({
fontSize
})),
- textStyleId: {
- get(this: ProxyThis): string {
- return raw(this, internals).textStyleId ?? ''
- },
- set(this: ProxyThis, value: string) {
- updateNode(this, internals, { textStyleId: value || null })
- }
- },
+ textStyleId: characterStyle<string>(internals, 'textStyleId', mixed, (_node, value) => ({
+ textStyleId: value || null
+ })),
fontWeight: characterStyle<number>(internals, 'fontWeight', mixed, (_node, fontWeight) => ({
fontWeight
})),
@@ -142,7 +142,20 @@ export function installTextNodeProxyAccessors(
return percent === null ? undefined : (fontSize) => ({ lineHeight: percent * fontSize })
}
),
- textCase: field(internals, 'textCase'),
+ textCase: characterStyle<TextCase>(internals, 'textCase', mixed, (_node, textCase) => ({
+ textCase
+ })),
+ hyperlink: {
+ get(this: ProxyThis): unknown {
+ return getTextStyle(raw(this, internals), 'hyperlink', mixed)
+ },
+ set(this: ProxyThis, value: HyperlinkTarget | null) {
+ const node = raw(this, internals)
+ const hyperlink = hyperlinkTarget('set_hyperlink', value, graph(this, internals))
+ const styleRuns = styleRunsWithPatch(node, 0, node.text.length, { hyperlink })
+ updateNode(this, internals, { styleRuns })
+ }
+ },
textDecoration: characterStyle<SceneNode['textDecoration']>(
internals,
'textDecoration',
diff --git a/packages/core/src/figma-api/accessors/text/messages.ts b/packages/core/src/figma-api/accessors/text/messages.ts
new file mode 100644
index 000000000..e98e40d1c
--- /dev/null
+++ b/packages/core/src/figma-api/accessors/text/messages.ts
@@ -0,0 +1,10 @@
+/** Figma's message for a value its schema rejects. */
+export function invalid(method: string, problem: string, property = 'value'): Error {
+ return new Error(`in ${method}: Property "${property}" failed validation: ${problem}`)
+}
+
+export 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
+}
diff --git a/packages/core/src/figma-api/accessors/text/ranges.ts b/packages/core/src/figma-api/accessors/text/ranges.ts
index fc5985792..fb0a6041a 100644
--- a/packages/core/src/figma-api/accessors/text/ranges.ts
+++ b/packages/core/src/figma-api/accessors/text/ranges.ts
@@ -3,9 +3,14 @@ import { uniqBy } from 'es-toolkit/array'
import type {
CharacterStyleOverride,
Fill,
+ HyperlinkTarget,
+ SceneGraph,
SceneNode,
+ TextBindableField,
+ TextCase,
TextDecoration,
- TextDecorationStyle
+ TextDecorationStyle,
+ Variable
} from '@open-pencil/scene-graph'
import {
@@ -34,14 +39,22 @@ import {
rangeHasUnderline,
type FigmaDecorationColor,
type FigmaTextLength,
+ type FigmaVariableAlias,
type StyledTextSegment,
type TextSegmentField
} from '#core/figma-api/text/style'
import { styleRunsWithPatch, type TextStylePatch } from '#core/text/character-style'
+import { hyperlinkTarget } from './hyperlink'
+import { invalid, received } from './messages'
+import { installTextReferenceMethods } from './references'
+
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 TEXT_CASES = new Set<TextCase>(['ORIGINAL', 'UPPER', 'LOWER', 'TITLE'])
+/** Text cases Figma takes that OpenPencil cannot draw yet. */
+const SMALL_CAPS = new Set(['SMALL_CAPS', 'SMALL_CAPS_FORCED'])
const PAINT_TYPES = new Set([
'SOLID',
'SHADER',
@@ -61,17 +74,6 @@ const SOLID_PAINT_KEYS = new Set([
'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)) {
@@ -248,7 +250,8 @@ type RangeSetter = (
node: SceneNode,
start: number,
end: number,
- value: unknown
+ value: unknown,
+ graph: SceneGraph
) => TextStylePatch
/** Decoration styles only apply to underlined text; Figma rejects a range with none. */
@@ -308,6 +311,21 @@ const RANGE_SETTERS: Record<string, RangeSetter> = {
if (typeof value !== 'boolean')
throw invalid(method, `Expected boolean, received ${received(value)}`)
return { textDecorationSkipInk: value }
+ }),
+ setRangeTextCase: (method, _node, _start, _end, value) => {
+ if (SMALL_CAPS.has(value as string)) {
+ throw new Error(`in ${method}: OpenPencil does not support the ${String(value)} text case`)
+ }
+ if (!TEXT_CASES.has(value as TextCase)) {
+ throw invalid(
+ method,
+ `Invalid enum value. Expected ${[...TEXT_CASES, ...SMALL_CAPS].map((name) => `'${name}'`).join(' | ')}, received '${String(value)}'`
+ )
+ }
+ return { textCase: value as TextCase }
+ },
+ setRangeHyperlink: (method, _node, _start, _end, value, graph) => ({
+ hyperlink: hyperlinkTarget(method, value, graph)
})
}
@@ -325,7 +343,11 @@ const RANGE_GETTERS: Record<string, TextSegmentField> = {
getRangeTextDecorationThickness: 'textDecorationThickness',
getRangeTextDecorationColor: 'textDecorationColor',
getRangeTextDecorationSkipInk: 'textDecorationSkipInk',
- getRangeOpenTypeFeatures: 'openTypeFeatures'
+ getRangeOpenTypeFeatures: 'openTypeFeatures',
+ getRangeTextCase: 'textCase',
+ getRangeHyperlink: 'hyperlink',
+ getRangeTextStyleId: 'textStyleId',
+ getRangeFillStyleId: 'fillStyleId'
}
type RangeGetter<T> = (start: number, end: number) => T | symbol
@@ -363,6 +385,27 @@ export interface TextRangeMethods {
getRangeTextDecorationSkipInk: RangeGetter<boolean | null>
setRangeTextDecorationSkipInk: RangeSetterMethod<boolean>
getRangeOpenTypeFeatures: RangeGetter<Record<string, boolean>>
+ getRangeTextCase: RangeGetter<TextCase>
+ setRangeTextCase: RangeSetterMethod<TextCase>
+ getRangeHyperlink: RangeGetter<HyperlinkTarget | null>
+ setRangeHyperlink: RangeSetterMethod<HyperlinkTarget | null>
+ getRangeTextStyleId: RangeGetter<string>
+ setRangeTextStyleId: RangeSetterMethod<string>
+ setRangeTextStyleIdAsync: (start: number, end: number, styleId: string) => Promise<void>
+ getRangeFillStyleId: RangeGetter<string>
+ setRangeFillStyleId: RangeSetterMethod<string>
+ setRangeFillStyleIdAsync: (start: number, end: number, styleId: string) => Promise<void>
+ getRangeBoundVariable: (
+ start: number,
+ end: number,
+ field: TextBindableField
+ ) => FigmaVariableAlias | null | symbol
+ setRangeBoundVariable: (
+ start: number,
+ end: number,
+ field: TextBindableField,
+ variable: Variable | null
+ ) => void
getRangeListOptions: RangeGetter<TextListOptions>
setRangeListOptions: RangeSetterMethod<TextListOptions>
getRangeIndentation: RangeGetter<number>
@@ -400,7 +443,7 @@ export function installTextRangeMethods(
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)
+ const patch = setter(method, node, start, end, value, graph(this, internals))
updateNode(this, internals, { styleRuns: styleRunsWithPatch(node, start, end, patch) })
}
}
@@ -462,5 +505,6 @@ export function installTextRangeMethods(
}
}
}
+ installTextReferenceMethods(methods, internals, mixed)
Object.defineProperties(prototype, methods)
}
diff --git a/packages/core/src/figma-api/accessors/text/references.ts b/packages/core/src/figma-api/accessors/text/references.ts
new file mode 100644
index 000000000..4f6f8e9f4
--- /dev/null
+++ b/packages/core/src/figma-api/accessors/text/references.ts
@@ -0,0 +1,87 @@
+import {
+ graph,
+ raw,
+ updateNode,
+ type NodeProxyInternals,
+ type ProxyThis
+} from '#core/figma-api/accessor-utils'
+import { setRangeParagraphSpacing } from '#core/figma-api/text'
+import {
+ assertTextBindableField,
+ getRangeBoundVariable,
+ rangeBindingChanges,
+ rangeSharedStylePatch
+} from '#core/figma-api/text/bindings'
+import { assertTextRange } from '#core/figma-api/text/style'
+import { styleRunsWithPatch } from '#core/text/character-style'
+
+import { invalid, received } from './messages'
+
+/** Methods that give characters a text or fill style, deprecated and async alike. */
+const SHARED_STYLE_SETTERS = {
+ setRangeTextStyleId: 'text',
+ setRangeTextStyleIdAsync: 'text',
+ setRangeFillStyleId: 'fill',
+ setRangeFillStyleIdAsync: 'fill'
+} as const
+
+/**
+ * Figma's range methods for what characters refer to outside the text: the text and fill styles
+ * they use and the variables their fields are bound to.
+ */
+export function installTextReferenceMethods(
+ methods: PropertyDescriptorMap,
+ internals: NodeProxyInternals,
+ mixed: symbol
+): void {
+ for (const [method, kind] of Object.entries(SHARED_STYLE_SETTERS)) {
+ const set = function (this: ProxyThis, start: number, end: number, styleId: unknown) {
+ const node = raw(this, internals)
+ if (typeof styleId !== 'string') {
+ throw invalid(method, `Expected string, received ${received(styleId)}`, 'styleId')
+ }
+ assertTextRange(method, node, start, end)
+ const patch = rangeSharedStylePatch(graph(this, internals), kind, styleId)
+ updateNode(this, internals, { styleRuns: styleRunsWithPatch(node, start, end, patch) })
+ }
+ methods[method] = {
+ value: method.endsWith('Async')
+ ? async function (this: ProxyThis, start: number, end: number, styleId: unknown) {
+ set.call(this, start, end, styleId)
+ }
+ : set
+ }
+ }
+ methods.getRangeBoundVariable = {
+ value(this: ProxyThis, start: number, end: number, field: unknown) {
+ const method = 'getRangeBoundVariable'
+ const node = raw(this, internals)
+ assertTextRange(method, node, start, end)
+ return getRangeBoundVariable(node, start, end, assertTextBindableField(method, field), mixed)
+ }
+ }
+ methods.setRangeBoundVariable = {
+ value(this: ProxyThis, start: number, end: number, field: unknown, variable: unknown) {
+ const method = 'setRangeBoundVariable'
+ const node = raw(this, internals)
+ const bindable = assertTextBindableField(method, field)
+ assertTextRange(method, node, start, end)
+ const g = graph(this, internals)
+ const changes = rangeBindingChanges(g, node, start, end, bindable, variable)
+ updateNode(this, internals, { styleRuns: changes.styleRuns })
+ if (
+ changes.paragraphValue !== null &&
+ (bindable === 'paragraphSpacing' || bindable === 'paragraphIndent')
+ ) {
+ setRangeParagraphSpacing(
+ g,
+ raw(this, internals),
+ bindable,
+ start,
+ end,
+ changes.paragraphValue
+ )
+ }
+ }
+ }
+}
diff --git a/packages/core/src/figma-api/accessors/visual.ts b/packages/core/src/figma-api/accessors/visual.ts
index f09cd3411..5563cb31c 100644
--- a/packages/core/src/figma-api/accessors/visual.ts
+++ b/packages/core/src/figma-api/accessors/visual.ts
@@ -21,14 +21,26 @@ import { textStyleChanges } from '#core/text/character-style'
function styleReference(
internals: NodeProxyInternals,
- field: 'fillStyleId' | 'strokeStyleId' | 'effectStyleId' | 'gridStyleId'
+ field: 'fillStyleId' | 'strokeStyleId' | 'effectStyleId' | 'gridStyleId',
+ mixed: symbol
): PropertyDescriptor {
return {
- get(this: ProxyThis): string {
- return raw(this, internals)[field] ?? ''
+ get(this: ProxyThis): string | symbol {
+ const node = raw(this, internals)
+ // Characters of a text can each use a fill style of their own.
+ if (field === 'fillStyleId' && node.type === 'TEXT') {
+ return getTextStyle(node, 'fillStyleId', mixed) as string | symbol
+ }
+ return node[field] ?? ''
},
set(this: ProxyThis, value: string) {
- updateNode(this, internals, { [field]: value || null })
+ const node = raw(this, internals)
+ const changes = { [field]: value || null }
+ updateNode(
+ this,
+ internals,
+ field === 'fillStyleId' && node.type === 'TEXT' ? textStyleChanges(node, changes) : changes
+ )
}
}
}
@@ -127,10 +139,10 @@ export function installVisualNodeProxyAccessors(
}
},
// Applied shared styles, as Figma exposes them; an assignment inside an instance is an override.
- fillStyleId: styleReference(internals, 'fillStyleId'),
- strokeStyleId: styleReference(internals, 'strokeStyleId'),
- effectStyleId: styleReference(internals, 'effectStyleId'),
- gridStyleId: styleReference(internals, 'gridStyleId'),
+ fillStyleId: styleReference(internals, 'fillStyleId', mixed),
+ strokeStyleId: styleReference(internals, 'strokeStyleId', mixed),
+ effectStyleId: styleReference(internals, 'effectStyleId', mixed),
+ gridStyleId: styleReference(internals, 'gridStyleId', mixed),
opacity: {
get(this: ProxyThis): number {
return raw(this, internals).opacity
diff --git a/packages/core/src/figma-api/compatibility.ts b/packages/core/src/figma-api/compatibility.ts
index af36254b4..1b9240716 100644
--- a/packages/core/src/figma-api/compatibility.ts
+++ b/packages/core/src/figma-api/compatibility.ts
@@ -124,6 +124,12 @@ type TextListKeys =
| 'setRangeTextDecorationOffset'
| 'setRangeTextDecorationThickness'
| 'setRangeTextDecorationSkipInk'
+ | 'setRangeTextCase'
+ | 'setRangeHyperlink'
+ | 'setRangeTextStyleId'
+ | 'setRangeTextStyleIdAsync'
+ | 'setRangeFillStyleId'
+ | 'setRangeFillStyleIdAsync'
| 'hangingList'
type TextListSurfaceMatch = Expect<
Extends<Pick<FigmaNodeProxy, TextListKeys>, Pick<TextNode, TextListKeys>>
@@ -153,6 +159,15 @@ type TextMixedKeys =
| 'getRangeTextDecorationThickness'
| 'getRangeTextDecorationSkipInk'
| 'getRangeAllFontNames'
+ | 'getRangeTextCase'
+ | 'getRangeHyperlink'
+ | 'getRangeTextStyleId'
+ | 'getRangeFillStyleId'
+ | 'getRangeBoundVariable'
+ | 'textCase'
+ | 'hyperlink'
+ | 'textStyleId'
+ | 'fillStyleId'
| 'fontSize'
| 'fontName'
| 'fontWeight'
diff --git a/packages/core/src/figma-api/proxy.ts b/packages/core/src/figma-api/proxy.ts
index de6e3368b..fa1ccf60d 100644
--- a/packages/core/src/figma-api/proxy.ts
+++ b/packages/core/src/figma-api/proxy.ts
@@ -5,6 +5,7 @@ import {
} from '@open-pencil/scene-graph'
import type {
GroupFitOptions,
+ HyperlinkTarget,
SceneGraph,
SceneNode,
NodeType,
@@ -179,7 +180,10 @@ export class FigmaNodeProxy {
declare textAutoResize: string
declare letterSpacing: FigmaLetterSpacing | symbol
declare lineHeight: FigmaLineHeight | symbol
- declare textCase: string
+ declare textCase: SceneNode['textCase'] | symbol
+ declare hyperlink: HyperlinkTarget | null | symbol
+ declare textStyleId: string | symbol
+ declare fillStyleId: string | symbol
declare textDecoration: SceneNode['textDecoration'] | symbol
declare maxLines: number | null
declare listSpacing: number | symbol
@@ -226,6 +230,18 @@ export class FigmaNodeProxy {
declare setRangeParagraphSpacing: TextRangeMethods['setRangeParagraphSpacing']
declare getRangeParagraphIndent: TextRangeMethods['getRangeParagraphIndent']
declare setRangeParagraphIndent: TextRangeMethods['setRangeParagraphIndent']
+ declare getRangeTextCase: TextRangeMethods['getRangeTextCase']
+ declare setRangeTextCase: TextRangeMethods['setRangeTextCase']
+ declare getRangeHyperlink: TextRangeMethods['getRangeHyperlink']
+ declare setRangeHyperlink: TextRangeMethods['setRangeHyperlink']
+ declare getRangeTextStyleId: TextRangeMethods['getRangeTextStyleId']
+ declare setRangeTextStyleId: TextRangeMethods['setRangeTextStyleId']
+ declare setRangeTextStyleIdAsync: TextRangeMethods['setRangeTextStyleIdAsync']
+ declare getRangeFillStyleId: TextRangeMethods['getRangeFillStyleId']
+ declare setRangeFillStyleId: TextRangeMethods['setRangeFillStyleId']
+ declare setRangeFillStyleIdAsync: TextRangeMethods['setRangeFillStyleIdAsync']
+ declare getRangeBoundVariable: TextRangeMethods['getRangeBoundVariable']
+ declare setRangeBoundVariable: TextRangeMethods['setRangeBoundVariable']
constructor(id: string, graph: SceneGraph, api: NodeProxyHost) {
this[INTERNAL_ID] = id
diff --git a/packages/core/src/figma-api/text/bindings.ts b/packages/core/src/figma-api/text/bindings.ts
new file mode 100644
index 000000000..76812d554
--- /dev/null
+++ b/packages/core/src/figma-api/text/bindings.ts
@@ -0,0 +1,153 @@
+import { mapValues, omit, pick } from 'es-toolkit/object'
+
+import {
+ getSharedStyles,
+ SHARED_TEXT_STYLE_FIELDS,
+ TEXT_BINDABLE_FIELDS,
+ type CharacterStyleOverride,
+ type SceneGraph,
+ type SceneNode,
+ type StyleRun,
+ type TextBindableField,
+ type Variable
+} from '@open-pencil/scene-graph'
+import { copyFills } from '@open-pencil/scene-graph/copy'
+
+import { styleNameToWeight } from '#core/figma-api/fonts'
+import { styleRunsWithPatch } from '#core/text/character-style'
+
+import { getStyledTextSegments, variableAlias, type FigmaVariableAlias } from './style'
+
+/** Fields a string variable binds; the rest take numbers. */
+const STRING_FIELDS: ReadonlySet<TextBindableField> = new Set(['fontFamily', 'fontStyle'])
+const PARAGRAPH_FIELDS = new Set(['paragraphSpacing', 'paragraphIndent'] as const)
+
+function isParagraphField(
+ field: TextBindableField
+): field is 'paragraphSpacing' | 'paragraphIndent' {
+ return (PARAGRAPH_FIELDS as ReadonlySet<string>).has(field)
+}
+
+/**
+ * The style a text or fill style gives characters that use it, with the reference that keeps
+ * them attached. An empty ID detaches them; a style the document does not hold attaches by ID
+ * alone, as the text's own setters do.
+ */
+export function rangeSharedStylePatch(
+ graph: SceneGraph,
+ kind: 'text' | 'fill',
+ styleId: string
+): CharacterStyleOverride {
+ const key = kind === 'text' ? 'textStyleId' : 'fillStyleId'
+ if (!styleId) return { [key]: null }
+ const found = getSharedStyles(graph, kind).find((style) => style.id === styleId)
+ const style = found ? graph.getNode(found.nodeId) : undefined
+ if (!style) return { [key]: styleId }
+ if (kind === 'fill') return { fillStyleId: styleId, fills: copyFills(style.fills) }
+ return { textStyleId: styleId, ...structuredClone(pick(style, SHARED_TEXT_STYLE_FIELDS)) }
+}
+
+/** Figma's message for a text field it cannot bind. */
+export function assertTextBindableField(method: string, field: unknown): TextBindableField {
+ if (!(TEXT_BINDABLE_FIELDS as readonly unknown[]).includes(field)) {
+ throw new Error(
+ `in ${method}: Property "field" failed validation: Invalid enum value. Expected ` +
+ `${TEXT_BINDABLE_FIELDS.map((name) => `'${name}'`).join(' | ')}, received '${String(field)}'`
+ )
+ }
+ return field as TextBindableField
+}
+
+/** The variable a binding takes: one the document holds, of the type the field takes. */
+function boundVariable(
+ graph: SceneGraph,
+ method: string,
+ field: TextBindableField,
+ variable: unknown
+): Variable {
+ const id = (variable as { id?: unknown } | null)?.id
+ const found = typeof id === 'string' ? graph.variables.get(id) : undefined
+ if (!found) throw new Error(`in ${method}: Variable not found`)
+ const expected = STRING_FIELDS.has(field) ? 'STRING' : 'FLOAT'
+ if (found.type !== expected) {
+ throw new Error(
+ `in ${method}: Cannot bind a ${found.type} variable to "${field}", which takes ${expected}`
+ )
+ }
+ return found
+}
+
+/** What the characters show for a bound field: the variable's value in their mode. */
+function boundValue(
+ graph: SceneGraph,
+ node: SceneNode,
+ field: TextBindableField,
+ variable: Variable
+): CharacterStyleOverride {
+ if (STRING_FIELDS.has(field)) {
+ const value = graph.resolveVariableForNode(node.id, variable.id)
+ if (typeof value !== 'string') return {}
+ if (field === 'fontFamily') return { fontFamily: value }
+ const { weight, italic } = styleNameToWeight(value)
+ return { fontWeight: weight, italic }
+ }
+ const value = graph.resolveNumberVariableForNode(node.id, variable.id)
+ if (value === undefined || !Number.isFinite(value) || isParagraphField(field)) return {}
+ return { [field]: value }
+}
+
+/**
+ * The runs that bind `field` of `text[start, end)` to a variable, or unbind it, showing the
+ * variable's value there as Figma does, and the value a bound paragraph spacing or indent gives
+ * the range's paragraphs.
+ */
+export function rangeBindingChanges(
+ graph: SceneGraph,
+ node: SceneNode,
+ start: number,
+ end: number,
+ field: TextBindableField,
+ variable: unknown
+): { styleRuns: StyleRun[]; paragraphValue: number | null } {
+ const bound =
+ variable === null ? null : boundVariable(graph, 'setRangeBoundVariable', field, variable)
+ const value = bound ? boundValue(graph, node, field, bound) : {}
+ let styleRuns = node.styleRuns
+ // Characters bound apart keep their other bindings.
+ for (const segment of getStyledTextSegments(node, ['boundVariables'], start, end)) {
+ const aliases = (segment.boundVariables ?? {}) as Record<string, FigmaVariableAlias>
+ const ids = mapValues(aliases, (alias) => alias.id)
+ const boundVariables = bound ? { ...ids, [field]: bound.id } : omit(ids, [field])
+ styleRuns = styleRunsWithPatch({ ...node, styleRuns }, segment.start, segment.end, {
+ ...value,
+ boundVariables
+ })
+ }
+ const resolved = bound ? graph.resolveNumberVariableForNode(node.id, bound.id) : undefined
+ const paragraphValue =
+ isParagraphField(field) && resolved !== undefined && Number.isFinite(resolved)
+ ? Math.max(0, resolved)
+ : null
+ return { styleRuns, paragraphValue }
+}
+
+/** The variable `field` of every character of the range is bound to, `null`, or `mixed`. */
+export function getRangeBoundVariable(
+ node: SceneNode,
+ start: number,
+ end: number,
+ field: TextBindableField,
+ mixed: symbol
+): FigmaVariableAlias | null | symbol {
+ const segments = getStyledTextSegments(node, ['boundVariables'], start, end)
+ const ids = new Set(
+ segments.map(
+ (segment) =>
+ (segment.boundVariables as Partial<Record<string, FigmaVariableAlias>> | undefined)?.[field]
+ ?.id ?? null
+ )
+ )
+ if (ids.size > 1) return mixed
+ const [id] = ids
+ return id ? variableAlias(id) : null
+}
diff --git a/packages/core/src/figma-api/text/style.ts b/packages/core/src/figma-api/text/style.ts
index 490b2717a..f79d59c4a 100644
--- a/packages/core/src/figma-api/text/style.ts
+++ b/packages/core/src/figma-api/text/style.ts
@@ -1,3 +1,4 @@
+import { mapValues, pickBy } from 'es-toolkit/object'
import { isEqual } from 'es-toolkit/predicate'
import {
@@ -76,9 +77,19 @@ function spacing(field: 'paragraphSpacing' | 'listSpacing' | 'paragraphIndent')
return ({ node, paragraph }: FieldContext) => paragraphSpacingAt(node, paragraph, field)
}
+/** Figma's reference to a variable, as bound fields read it. */
+export function variableAlias(id: string): FigmaVariableAlias {
+ return { type: 'VARIABLE_ALIAS', id }
+}
+
+export interface FigmaVariableAlias {
+ type: 'VARIABLE_ALIAS'
+ id: string
+}
+
/**
- * 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.
+ * Figma's value of each field for one character. Fields the model keeps for the whole text 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,
@@ -94,20 +105,21 @@ const FIELD_READERS: Record<TextSegmentField, (context: FieldContext) => unknown
textDecorationOffset: whenUnderlined((style) => pixels(style.textUnderlineOffset)),
textDecorationThickness: whenUnderlined((style) => pixels(style.textDecorationThickness)),
textDecorationColor: whenUnderlined(decorationColor),
- textCase: ({ node }) => node.textCase,
+ textCase: ({ style }) => style.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 ?? '',
+ textStyleId: ({ style }) => style.textStyleId ?? '',
+ fillStyleId: ({ style }) => style.fillStyleId ?? '',
listOptions: ({ node, paragraph }) => ({
type: paragraphStyleAt(node.textParagraphs, paragraph).listType
}),
indentation: ({ node, paragraph }) =>
paragraphStyleAt(node.textParagraphs, paragraph).indentation,
- hyperlink: () => null,
+ hyperlink: ({ style }) => (style.hyperlink ? { ...style.hyperlink } : null),
openTypeFeatures: ({ style }) => fontFeatureMap(style),
- boundVariables: () => ({}),
+ boundVariables: ({ style }) =>
+ mapValues(pickBy(style.boundVariables, Boolean), (id) => variableAlias(String(id))),
textStyleOverrides: () => [],
paragraphSpacing: spacing('paragraphSpacing'),
listSpacing: spacing('listSpacing'),
diff --git a/packages/core/src/io/subgraph.ts b/packages/core/src/io/subgraph.ts
index 5a9c6b225..ca968a27c 100644
--- a/packages/core/src/io/subgraph.ts
+++ b/packages/core/src/io/subgraph.ts
@@ -1,4 +1,4 @@
-import { SceneGraph } from '@open-pencil/scene-graph'
+import { SceneGraph, styleRunReferences } from '@open-pencil/scene-graph'
import type { ExportTarget } from './types'
@@ -28,7 +28,8 @@ function includeReferencedStyles(source: SceneGraph, ids: Set<string>): void {
node.strokeStyleId,
node.textStyleId,
node.effectStyleId,
- node.gridStyleId
+ node.gridStyleId,
+ ...styleRunReferences(node.styleRuns).styles
]) {
if (styleId) referencedStyleIds.add(styleId)
}
@@ -140,9 +141,11 @@ function collectReferencedResources(source: SceneGraph, graph: SceneGraph) {
for (const fill of node.fills) {
if (fill.type === 'IMAGE' && fill.imageHash) imageHashes.add(fill.imageHash)
}
- for (const variableId of Object.values(node.boundVariables)) {
- collectVariableClosure(source, variableId, variableIds)
- }
+ const bound = [
+ ...Object.values(node.boundVariables),
+ ...styleRunReferences(node.styleRuns).variables
+ ]
+ for (const variableId of bound) collectVariableClosure(source, variableId, variableIds)
}
return { imageHashes, variableIds }
}
diff --git a/packages/core/src/text/case.ts b/packages/core/src/text/case.ts
index 081f80966..6fd68482e 100644
--- a/packages/core/src/text/case.ts
+++ b/packages/core/src/text/case.ts
@@ -1,13 +1,126 @@
-import type { TextCase } from '@open-pencil/scene-graph'
+import type { SceneNode, TextCase } from '@open-pencil/scene-graph'
-export function transformTextCase(text: string, textCase: TextCase): string {
+type CasedText = Pick<SceneNode, 'text' | 'textCase' | 'styleRuns'>
+
+const WORD = /[\p{L}\p{N}][\p{L}\p{M}\p{N}]*/gu
+const WORD_END = /[\p{L}\p{M}\p{N}]$/u
+const WORD_REST = /^[\p{L}\p{M}\p{N}]+/u
+
+/** A word with its first character, which may be astral, in upper case and the rest in lower. */
+function capitalized(word: string): string {
+ const first = String.fromCodePoint(word.codePointAt(0) ?? 0)
+ return first.toLocaleUpperCase() + word.slice(first.length).toLocaleLowerCase()
+}
+
+/**
+ * `text` in `textCase`. Title case capitalizes each word; a stretch that `continuesWord` starts
+ * inside a word, so its first word goes on in lower case.
+ */
+export function transformTextCase(text: string, textCase: TextCase, continuesWord = false): string {
if (textCase === 'UPPER') return text.toLocaleUpperCase()
if (textCase === 'LOWER') return text.toLocaleLowerCase()
if (textCase === 'TITLE') {
- return text.replace(
- /[\p{L}\p{N}][\p{L}\p{M}\p{N}]*/gu,
- (word) => word.charAt(0).toLocaleUpperCase() + word.slice(1).toLocaleLowerCase()
- )
+ // The rest of a word the stretch starts inside, marks and all, goes on in lower case.
+ const rest = continuesWord ? (WORD_REST.exec(text)?.[0] ?? '') : ''
+ return rest.toLocaleLowerCase() + text.slice(rest.length).replace(WORD, capitalized)
}
return text
}
+
+/** Whether the character at `index` goes on with a word the characters before it started. */
+function continuesWord(text: string, index: number): boolean {
+ return index > 0 && WORD_END.test(text.slice(Math.max(0, index - 2), index))
+}
+
+/** A stretch of a text shown in one case. */
+export interface TextCaseSegment {
+ start: number
+ end: number
+ textCase: TextCase
+}
+
+/** The text in stretches of one case each: its runs' own, and the text's between them. */
+export function textCaseSegments(node: CasedText): TextCaseSegment[] {
+ const segments: TextCaseSegment[] = []
+ const add = (start: number, end: number, textCase: TextCase) => {
+ if (end <= start) return
+ const previous = segments.at(-1)
+ if (previous?.end === start && previous.textCase === textCase) previous.end = end
+ else segments.push({ start, end, textCase })
+ }
+ 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)
+ add(at, start, node.textCase)
+ add(start, end, run.style.textCase ?? node.textCase)
+ at = Math.max(at, end)
+ }
+ add(at, node.text.length, node.textCase)
+ return segments
+}
+
+/** `text[start, end)` as it is shown, in the case each of its characters has. */
+export function shownTextSlice(node: CasedText, start: number, end: number): string {
+ let shown = ''
+ for (const segment of textCaseSegments(node)) {
+ const from = Math.max(start, segment.start)
+ const to = Math.min(end, segment.end)
+ if (to <= from) continue
+ shown += transformTextCase(
+ node.text.slice(from, to),
+ segment.textCase,
+ continuesWord(node.text, from)
+ )
+ }
+ return shown
+}
+
+/** A text as it is shown, in the case each of its characters has. */
+export function shownText(node: CasedText): string {
+ if (node.styleRuns.every((run) => run.style.textCase === undefined)) {
+ return transformTextCase(node.text, node.textCase)
+ }
+ return shownTextSlice(node, 0, node.text.length)
+}
+
+/**
+ * Each character of the shown text with the index of the character of `text` it comes from;
+ * a case can give one character several, as `ß` upper-cases to `SS`. Each stretch is cased as
+ * a whole, as `shownText` cases it, so a letter that depends on its word, such as a final `ς`,
+ * is the one shown.
+ */
+export function shownCharacters(
+ node: CasedText
+): Array<{ character: string; sourceIndex: number }> {
+ const result: Array<{ character: string; sourceIndex: number }> = []
+ for (const segment of textCaseSegments(node)) {
+ const slice = node.text.slice(segment.start, segment.end)
+ const whole = Array.from(
+ transformTextCase(slice, segment.textCase, continuesWord(node.text, segment.start))
+ )
+ const sources: Array<{ shown: string[]; sourceIndex: number }> = []
+ let sourceIndex = segment.start
+ for (const sourceCharacter of slice) {
+ const shown = transformTextCase(
+ sourceCharacter,
+ segment.textCase,
+ continuesWord(node.text, sourceIndex)
+ )
+ sources.push({ shown: Array.from(shown), sourceIndex })
+ sourceIndex += sourceCharacter.length
+ }
+ // Where casing the stretch whole shows as many characters as casing each one, each source
+ // character takes its own share of the whole; otherwise each keeps its own casing.
+ const aligned =
+ sources.reduce((count, source) => count + source.shown.length, 0) === whole.length
+ let at = 0
+ for (const source of sources) {
+ for (const character of source.shown) {
+ result.push({ character: aligned ? whole[at] : character, sourceIndex: source.sourceIndex })
+ at++
+ }
+ }
+ }
+ return result
+}
diff --git a/packages/core/src/text/character-style.ts b/packages/core/src/text/character-style.ts
index 57cf13029..1ec727d9f 100644
--- a/packages/core/src/text/character-style.ts
+++ b/packages/core/src/text/character-style.ts
@@ -1,7 +1,16 @@
-import { omit } from 'es-toolkit/object'
+import { omit, pick } from 'es-toolkit/object'
import { isEqual } from 'es-toolkit/predicate'
-import type { CharacterStyleOverride, SceneNode, StyleRun } from '@open-pencil/scene-graph'
+import {
+ SHARED_TEXT_STYLE_FIELDS,
+ styleDetachmentChanges,
+ TEXT_BINDABLE_FIELDS,
+ type CharacterStyleOverride,
+ type HyperlinkTarget,
+ type SceneNode,
+ type StyleRun,
+ type TextBoundVariables
+} from '@open-pencil/scene-graph'
/** A character's style: the text's own, with its run's overrides over it. */
export type CharacterStyle = Required<
@@ -18,11 +27,16 @@ export type CharacterStyle = Required<
| 'textDecorationFills'
| 'textDecorationSkipInk'
| 'fontFeatures'
+ | 'textCase'
>
> & {
lineHeight: number | null
textDecorationThickness: number | null
textUnderlineOffset: number | null
+ hyperlink: HyperlinkTarget | null
+ textStyleId: string | null
+ fillStyleId: string | null
+ boundVariables: TextBoundVariables
}
export type TextStyleKey = (typeof TEXT_STYLE_KEYS)[number]
@@ -41,7 +55,20 @@ export const TEXT_STYLE_KEYS = [
'textDecorationFills',
'textDecorationSkipInk',
'textUnderlineOffset',
- 'fontFeatures'
+ 'fontFeatures',
+ 'textCase'
+] as const satisfies readonly (keyof CharacterStyle)[]
+
+/**
+ * What a range of characters can hold that is not a style of the text's own: a link, the
+ * styles it uses, and its bindings. The text's styles and bindings are what ranges start from.
+ */
+const RANGE_STYLE_KEYS = ['hyperlink', 'textStyleId', 'fillStyleId', 'boundVariables'] as const
+
+/** Every field a character's style has, as runs override it. */
+export const CHARACTER_STYLE_KEYS = [
+ ...TEXT_STYLE_KEYS,
+ ...RANGE_STYLE_KEYS
] as const satisfies readonly (keyof CharacterStyle)[]
export function nodeStyle(node: SceneNode): CharacterStyle {
@@ -59,7 +86,12 @@ export function nodeStyle(node: SceneNode): CharacterStyle {
textDecorationFills: node.textDecorationFills,
textDecorationSkipInk: node.textDecorationSkipInk,
textUnderlineOffset: node.textUnderlineOffset,
- fontFeatures: node.fontFeatures
+ fontFeatures: node.fontFeatures,
+ textCase: node.textCase,
+ hyperlink: null,
+ textStyleId: node.textStyleId,
+ fillStyleId: node.fillStyleId,
+ boundVariables: pick(node.boundVariables, TEXT_BINDABLE_FIELDS)
}
}
@@ -79,7 +111,7 @@ export function characterStyles(node: SceneNode, start: number, end: number): Ch
function definedOverrides(style: CharacterStyleOverride): Partial<CharacterStyle> {
const defined: Partial<Record<keyof CharacterStyle, unknown>> = {}
- for (const key of TEXT_STYLE_KEYS) {
+ for (const key of CHARACTER_STYLE_KEYS) {
if (style[key] !== undefined) defined[key] = style[key]
}
return defined as Partial<CharacterStyle>
@@ -92,7 +124,7 @@ function withoutRedundantOverrides(node: SceneNode, runs: StyleRun[]): StyleRun[
for (const run of runs) {
const style = omit(
run.style,
- TEXT_STYLE_KEYS.filter(
+ CHARACTER_STYLE_KEYS.filter(
(key) => run.style[key] !== undefined && isEqual(run.style[key], base[key])
)
)
@@ -117,6 +149,31 @@ function withoutRedundantOverrides(node: SceneNode, runs: StyleRun[]): StyleRun[
*/
export type TextStylePatch = CharacterStyleOverride | ((fontSize: number) => CharacterStyleOverride)
+/**
+ * The styles characters leave when `style` changes what a style gave them, as a text leaves its
+ * own: a font size leaves the text style, and fills leave the fill style.
+ */
+function detachedStyles(
+ node: SceneNode,
+ current: CharacterStyleOverride,
+ style: CharacterStyleOverride | undefined
+): CharacterStyleOverride {
+ if (!style) return {}
+ const styled = {
+ ...node,
+ textStyleId: current.textStyleId !== undefined ? current.textStyleId : node.textStyleId,
+ fillStyleId: current.fillStyleId !== undefined ? current.fillStyleId : node.fillStyleId
+ }
+ const changes = pick(style, [...TEXT_STYLE_KEYS, 'fills', 'textStyleId', 'fillStyleId'])
+ const detached = styleDetachmentChanges(styled, changes)
+ return pick(
+ detached,
+ (['textStyleId', 'fillStyleId'] as const).filter(
+ (key) => !Object.hasOwn(changes, key) && Object.hasOwn(detached, key)
+ )
+ )
+}
+
/** Style runs with `patch` over `text[start, end)`, as Figma restyles a range. */
export function styleRunsWithPatch(
node: SceneNode,
@@ -140,7 +197,7 @@ export function styleRunsWithPatch(
style = patches.get(fontSize) ?? sized(fontSize)
patches.set(fontSize, style)
}
- chars[index] = { ...chars[index], ...style }
+ chars[index] = { ...chars[index], ...style, ...detachedStyles(node, 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.
@@ -165,10 +222,18 @@ export function styleRunsWithPatch(
*/
export function textStyleChanges(
node: SceneNode,
- changes: Partial<Pick<SceneNode, TextStyleKey>>,
+ changes: Partial<Pick<SceneNode, TextStyleKey | 'textStyleId' | 'fillStyleId'>>,
sized?: (fontSize: number) => CharacterStyleOverride
): Partial<SceneNode> {
- const keys = Object.keys(changes) as TextStyleKey[]
+ const changed = Object.keys(changes) as (keyof CharacterStyleOverride)[]
+ // A style a range keeps no longer gives it what the whole text now sets.
+ const keys = [
+ ...changed,
+ ...(changed.some((key) => (SHARED_TEXT_STYLE_FIELDS as readonly string[]).includes(key))
+ ? (['textStyleId'] as const)
+ : []),
+ ...(changed.includes('fills') ? (['fillStyleId'] as const) : [])
+ ]
const runs = node.styleRuns.map((run) => ({ ...run, style: omit(run.style, keys) }))
const updated = { ...node, ...changes }
const styleRuns = withoutRedundantOverrides(updated, runs)
diff --git a/packages/core/src/text/requirements.ts b/packages/core/src/text/requirements.ts
index 6e62494aa..bd771b51a 100644
--- a/packages/core/src/text/requirements.ts
+++ b/packages/core/src/text/requirements.ts
@@ -1,7 +1,7 @@
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { DEFAULT_FONT_FAMILY } from '#core/constants'
-import { transformTextCase } from '#core/text/case'
+import { shownCharacters } from '#core/text/case'
import { cjkFallbackScriptForLanguage, type FontFallbackScript } from '#core/text/fallbacks'
import { weightToStyle } from '#core/text/font/style'
@@ -57,19 +57,6 @@ function textLanguageAt(node: SceneNode, index: number): string | null {
return run?.style.textLanguage ?? node.textLanguage
}
-function transformedCharactersWithSourceOffsets(
- node: SceneNode
-): Array<{ character: string; sourceIndex: number }> {
- const result: Array<{ character: string; sourceIndex: number }> = []
- let sourceIndex = 0
- for (const sourceCharacter of node.text) {
- for (const character of transformTextCase(sourceCharacter, node.textCase)) {
- result.push({ character, sourceIndex })
- }
- sourceIndex += sourceCharacter.length
- }
- return result
-}
export interface GraphFontRequirements {
characters: string
nodes: SceneNode[]
@@ -88,7 +75,7 @@ export function collectGraphFontRequirements(
if (!node) return
nodes.push(node)
if (node.type === 'TEXT') {
- for (const { character, sourceIndex } of transformedCharactersWithSourceOffsets(node)) {
+ for (const { character, sourceIndex } of shownCharacters(node)) {
characters.add(character)
const script = fallbackScriptForCharacter(character, textLanguageAt(node, sourceIndex))
if (script) scripts.add(script)
diff --git a/packages/core/src/text/style-runs.ts b/packages/core/src/text/style-runs.ts
index 87bc5ee6b..241106259 100644
--- a/packages/core/src/text/style-runs.ts
+++ b/packages/core/src/text/style-runs.ts
@@ -1,4 +1,5 @@
import { omit } from 'es-toolkit/object'
+import { isEqual } from 'es-toolkit/predicate'
import type { CharacterStyleOverride, StyleRun, TextDecoration } from '@open-pencil/scene-graph'
@@ -75,18 +76,6 @@ export function selectionHasStyle(
return true
}
-function stylesEqual(a: CharacterStyleOverride | null, b: CharacterStyleOverride | null): boolean {
- if (a === b) return true
- if (!a || !b) return a === b
- const aKeys = Object.keys(a) as (keyof CharacterStyleOverride)[]
- const bKeys = Object.keys(b) as (keyof CharacterStyleOverride)[]
- if (aKeys.length !== bKeys.length) return false
- for (const k of aKeys) {
- if (a[k] !== b[k]) return false
- }
- return true
-}
-
function isEmptyStyle(style: CharacterStyleOverride | null): boolean {
return !style || Object.keys(style).length === 0
}
@@ -105,7 +94,7 @@ function compactRuns(chars: (CharacterStyleOverride | null)[]): StyleRun[] {
i++
continue
}
- while (i < chars.length && stylesEqual(chars[i], style)) i++
+ while (i < chars.length && isEqual(chars[i], style)) i++
result.push({ start, length: i - start, style: { ...style } })
}
return result
diff --git a/packages/core/tests/canvas/text/lines.test.ts b/packages/core/tests/canvas/text/lines.test.ts
new file mode 100644
index 000000000..8fe6bde0c
--- /dev/null
+++ b/packages/core/tests/canvas/text/lines.test.ts
@@ -0,0 +1,204 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+import type { CanvasKit, TypefaceFontProvider } from 'canvaskit-wasm'
+
+import { SceneGraph, type SceneNode, type StyleRun } from '@open-pencil/scene-graph'
+
+import type { TextLayout } from '#core/canvas/text/layout'
+import { buildParagraph } from '#core/canvas/text/layout/build'
+import { getCanvasKit } from '#core/canvaskit'
+import { fontManager } from '#core/text/fonts'
+
+const run = (start: number, length: number, style: StyleRun['style']): StyleRun => ({
+ start,
+ length,
+ style
+})
+
+let ck: CanvasKit
+let provider: TypefaceFontProvider
+
+function layOut(props: Partial<SceneNode>): TextLayout {
+ const graph = new SceneGraph()
+ const node = graph.createNode('TEXT', graph.getPages()[0].id, {
+ fontFamily: 'Inter',
+ fontSize: 24,
+ lineHeight: null,
+ width: 400,
+ height: 400,
+ textAutoResize: 'WIDTH_AND_HEIGHT',
+ ...props
+ })
+ return buildParagraph({ ck, fontProvider: provider, fontsLoaded: true }, node, undefined, {
+ halfLeading: true
+ })
+}
+
+function expectBaselines(layout: TextLayout, figma: number[]): void {
+ const baselines = layout.getLineMetrics().map((line) => line.baseline)
+ expect(baselines).toHaveLength(figma.length)
+ for (const [index, baseline] of baselines.entries()) {
+ expect(Math.abs(baseline - figma[index])).toBeLessThan(0.01)
+ }
+}
+
+const SURFACE_WIDTH = 400
+
+/** Whether each pixel is ink, drawing the layout at scale 1, by row. */
+function inkRows(layout: TextLayout): boolean[][] {
+ const height = Math.ceil(layout.getHeight()) + 20
+ const surface = expectDefined(ck.MakeSurface(SURFACE_WIDTH, height), 'surface')
+ try {
+ const canvas = surface.getCanvas()
+ canvas.clear(ck.WHITE)
+ layout.draw(canvas, 0, 0)
+ const pixels = expectDefined(
+ canvas.readPixels(0, 0, {
+ width: SURFACE_WIDTH,
+ height,
+ colorType: ck.ColorType.RGBA_8888,
+ alphaType: ck.AlphaType.Unpremul,
+ colorSpace: ck.ColorSpace.SRGB
+ }),
+ 'pixels'
+ )
+ return Array.from({ length: height }, (_, y) =>
+ Array.from({ length: SURFACE_WIDTH }, (_, x) => pixels[(y * SURFACE_WIDTH + x) * 4] < 128)
+ )
+ } finally {
+ surface.delete()
+ }
+}
+
+/** The lowest row with ink between `left` and `right`. */
+function lowestInk(layout: TextLayout, left: number, right: number): number {
+ return inkRows(layout).findLastIndex((row) => row.slice(left, right).includes(true))
+}
+
+/** The rightmost column with ink between rows `top` and `bottom`. */
+function rightmostInk(layout: TextLayout, top: number, bottom: number): number {
+ return Math.max(
+ ...inkRows(layout)
+ .slice(top, bottom)
+ .map((row) => row.lastIndexOf(true))
+ )
+}
+
+// Baselines and heights measured in live Figma (2026-10-11) from the lines it saves, Inter.
+describe('lines of mixed sizes', () => {
+ beforeAll(async () => {
+ ck = await getCanvasKit()
+ provider = ck.TypefaceFontProvider.Make()
+ fontManager.attachProvider(ck, provider)
+ const inter = expectDefined(
+ await fontManager.fetchBundledFont('/Inter-Regular.ttf'),
+ 'bundled Inter font'
+ )
+ provider.registerFont(inter, 'Inter')
+ fontManager.markLoaded('Inter', 'Regular', inter)
+ })
+
+ afterAll(() => {
+ fontManager.detachProvider(provider)
+ provider.delete()
+ })
+
+ test('steps each baseline down by the height of the line it starts', () => {
+ const below = layOut({
+ text: 'first line\nSmall LARGE',
+ styleRuns: [run(17, 5, { fontSize: 40 })]
+ })
+ expectBaselines(below, [23.227, 71.227])
+ expect(Math.ceil(below.getHeight())).toBe(81)
+
+ const above = layOut({
+ text: 'Small LARGE\nsecond line',
+ styleRuns: [run(6, 5, { fontSize: 40 })]
+ })
+ expectBaselines(above, [38.545, 67.545])
+ expect(Math.ceil(above.getHeight())).toBe(74)
+ })
+
+ test('gives a line the tallest line height on it, wrapped lines too', () => {
+ const fixed = layOut({ text: 'one\ntwo\nthree', styleRuns: [run(4, 3, { lineHeight: 50 })] })
+ expectBaselines(fixed, [23.227, 73.227, 102.227])
+ expect(Math.ceil(fixed.getHeight())).toBe(108)
+
+ const wrapped = layOut({
+ text: 'small words LARGE then wraps to more lines here',
+ width: 160,
+ textAutoResize: 'HEIGHT',
+ styleRuns: [run(12, 5, { fontSize: 40 })]
+ })
+ expectBaselines(wrapped, [23.227, 71.227, 100.227, 129.227, 158.227])
+ })
+
+ test('stretches justified lines where they are placed', () => {
+ const layout = layOut({
+ text: 'small words LARGE then wraps to more lines here',
+ width: 160,
+ textAutoResize: 'HEIGHT',
+ textAlignHorizontal: 'JUSTIFIED',
+ styleRuns: [run(12, 5, { fontSize: 40 })]
+ })
+ expectBaselines(layout, [23.227, 71.227, 100.227, 129.227, 158.227])
+ // The line after "LARGE", which stands alone on its line, has words to stretch between.
+ const third = layout.getLineMetrics()[2]
+ const right = rightmostInk(layout, Math.ceil(third.baseline) - 10, Math.ceil(third.baseline))
+ expect(right).toBeGreaterThan(155)
+ })
+
+ test('centres the tallest font of a line in its line height', () => {
+ const layout = layOut({
+ text: 'Small LARGE\nsecond',
+ lineHeight: 30,
+ styleRuns: [run(6, 5, { fontSize: 40 })]
+ })
+ expectBaselines(layout, [29.545, 59.545])
+ expect(Math.ceil(layout.getHeight())).toBe(66)
+ })
+
+ test('adds paragraph spacing, and sizes an empty line by its newline', () => {
+ const spaced = layOut({
+ text: 'one\ntwo BIG\nthree',
+ paragraphSpacing: 10,
+ styleRuns: [run(8, 3, { fontSize: 40 })]
+ })
+ expectBaselines(spaced, [23.227, 81.227, 120.227])
+ expect(Math.ceil(spaced.getHeight())).toBe(126)
+
+ const empty = layOut({ text: 'one\n\nthree', styleRuns: [run(4, 1, { fontSize: 40 })] })
+ expectBaselines(empty, [23.227, 71.227, 100.227])
+ expect(Math.ceil(empty.getHeight())).toBe(106)
+ })
+
+ test('draws, selects, and hits each line where it is placed', () => {
+ const layout = layOut({
+ text: 'first line\nSmall LARGE',
+ styleRuns: [run(17, 5, { fontSize: 40 })]
+ })
+ const baseline = layout.getLineMetrics()[1].baseline
+ const [rect] = layout.getRectsForRange(
+ 17,
+ 22,
+ ck.RectHeightStyle.Tight,
+ ck.RectWidthStyle.Tight
+ )
+ expect(rect.rect[1]).toBeLessThan(baseline)
+ expect(rect.rect[3]).toBeGreaterThan(baseline)
+ const caret = expectDefined(layout.getCaretRect(19, false), 'caret')
+ expect(caret.top).toBeLessThan(baseline)
+ expect(caret.bottom).toBeGreaterThan(baseline)
+ expect(layout.getGlyphPositionAtCoordinate(rect.rect[0] + 1, baseline - 10).pos).toBe(17)
+
+ // "LARGE" has no descenders: its ink ends on the baseline.
+ const ink = lowestInk(layout, Math.ceil(rect.rect[0]), Math.floor(rect.rect[2]))
+ expect(Math.abs(ink + 1 - baseline)).toBeLessThan(1)
+ for (const line of layout.getShapedLines()) {
+ for (const glyphRun of line.runs) {
+ expect(Math.abs(glyphRun.positions[1] - line.baseline)).toBeLessThan(1)
+ }
+ }
+ })
+})
diff --git a/packages/core/tests/canvas/text/shape.test.ts b/packages/core/tests/canvas/text/shape.test.ts
index 9467a68b3..5bb811fa4 100644
--- a/packages/core/tests/canvas/text/shape.test.ts
+++ b/packages/core/tests/canvas/text/shape.test.ts
@@ -58,6 +58,31 @@ describe('text shaping for saved glyphs', () => {
expect(shaped.logicalIndexToCharacterOffsetMap[second.firstCharacter]).toBe(0)
})
+ test('saves text with blank lines and a closing newline, which shaping leaves out', async () => {
+ // Figma draws pasted text only from its saved glyphs, so a text without them is blank.
+ const blank = expectDefined(await shape({ text: 'one\n\nthree' }), 'text with a blank line')
+ expect(blank.baselines.map((line) => [line.firstCharacter, line.endCharacter])).toEqual([
+ [0, 4],
+ [4, 5],
+ [5, 10]
+ ])
+ const [first, , third] = blank.baselines.map((line) => line.position.y)
+ expect(blank.glyphs.map((glyph) => [glyph.firstCharacter, glyph.y])).toEqual([
+ [0, first],
+ [1, first],
+ [2, first],
+ [5, third],
+ [6, third],
+ [7, third],
+ [8, third],
+ [9, third]
+ ])
+
+ const closing = expectDefined(await shape({ text: 'one\n' }), 'text ending in a newline')
+ expect(closing.baselines).toHaveLength(2)
+ expect(closing.glyphs).toHaveLength(3)
+ })
+
test('places lines by horizontal and vertical alignment', async () => {
const top = expectDefined(await shape({ text: 'Centered', height: 64 }), 'top')
const centered = expectDefined(
diff --git a/packages/core/tests/editor/text/selection-style.test.ts b/packages/core/tests/editor/text/selection-style.test.ts
index 3859bb317..5e9d4287d 100644
--- a/packages/core/tests/editor/text/selection-style.test.ts
+++ b/packages/core/tests/editor/text/selection-style.test.ts
@@ -1,12 +1,12 @@
import { afterEach, describe, expect, test } from 'bun:test'
+import { expectDefined } from '#core-tests/helpers/assert'
+
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(() => {
@@ -33,7 +33,11 @@ async function editingWorld() {
renderer.destroy()
})
const page = editor.state.currentPageId
- const text = editor.graph.createNode('TEXT', page, { text: 'Hello world', width: 200, height: 20 })
+ 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
@@ -84,3 +88,24 @@ describe('panel edits while text is edited', () => {
expect(editor.getTextSelectionStyle(node())).toBeNull()
})
})
+
+describe('text case while text is edited', () => {
+ test('case the selected characters and show their case', async () => {
+ const { editor, id, node } = await editingWorld()
+
+ editor.updateNodeWithUndo(id, { textCase: 'UPPER' }, 'Change text case')
+
+ expect(node().textCase).toBe('ORIGINAL')
+ expect(node().styleRuns).toEqual([{ start: 6, length: 5, style: { textCase: 'UPPER' } }])
+ expect(editor.getTextSelectionStyle(node())?.textCase).toBe('UPPER')
+ editor.undoAction()
+ expect(node().styleRuns).toEqual([])
+ })
+
+ test('show only the layer properties of the selected characters', async () => {
+ const { editor, node } = await editingWorld()
+ const style = expectDefined(editor.getTextSelectionStyle(node()), 'selection style')
+ expect(Object.keys(style)).not.toContain('boundVariables')
+ expect(Object.keys(style)).not.toContain('hyperlink')
+ })
+})
diff --git a/packages/core/tests/figma-api/text/references.test.ts b/packages/core/tests/figma-api/text/references.test.ts
new file mode 100644
index 000000000..98a5ee030
--- /dev/null
+++ b/packages/core/tests/figma-api/text/references.test.ts
@@ -0,0 +1,268 @@
+import { describe, expect, test } from 'bun:test'
+
+import { FigmaAPI, SceneGraph } from '@open-pencil/core'
+import type { Color } from '@open-pencil/scene-graph'
+
+// Shapes and messages follow `@figma/plugin-typings` and the Plugin API documentation for the
+// range methods; validation messages follow those Figma reports for the other range setters.
+function styledText(characters = 'Hello world') {
+ const api = new FigmaAPI(new SceneGraph())
+ const text = api.createText()
+ text.characters = characters
+ return { api, text }
+}
+
+const RED: Color = { r: 1, g: 0, b: 0, a: 1 }
+const LINK = { type: 'URL' as const, value: 'https://openpencil.dev' }
+
+function textStyle(api: FigmaAPI, id: string, fields: Record<string, unknown>) {
+ const page = api.graph.getPages()[0]
+ const style = api.graph.createNode('TEXT', page.id, {
+ name: 'Heading',
+ sharedStyleType: 'TEXT',
+ internalOnly: true,
+ ...fields
+ })
+ style.source.id = id
+ return style
+}
+
+function fillStyle(api: FigmaAPI, id: string) {
+ const page = api.graph.getPages()[0]
+ const style = api.graph.createNode('RECTANGLE', page.id, {
+ name: 'Brand/Red',
+ sharedStyleType: 'FILL',
+ internalOnly: true,
+ fills: [{ type: 'SOLID', color: RED, opacity: 1, visible: true }]
+ })
+ style.source.id = id
+ return style
+}
+
+describe('text case ranges', () => {
+ test('case a range, reading the node mixed until it is cased again', () => {
+ const { text } = styledText()
+ text.setRangeTextCase(0, 5, 'UPPER')
+
+ expect(text.getRangeTextCase(0, 5)).toBe('UPPER')
+ expect(typeof text.getRangeTextCase(4, 7)).toBe('symbol')
+ expect(typeof text.textCase).toBe('symbol')
+ expect(text.getStyledTextSegments(['textCase'])).toEqual([
+ { characters: 'Hello', start: 0, end: 5, textCase: 'UPPER' },
+ { characters: ' world', start: 5, end: 11, textCase: 'ORIGINAL' }
+ ])
+
+ text.textCase = 'LOWER'
+ expect(text.textCase).toBe('LOWER')
+ expect(text.getRangeTextCase(0, 5)).toBe('LOWER')
+ })
+
+ test('reject what Figma rejects, and small caps OpenPencil cannot draw', () => {
+ const { text } = styledText()
+ expect(() => text.setRangeTextCase(0, 5, 'SHOUT' as 'UPPER')).toThrow(
+ `in setRangeTextCase: Property "value" failed validation: Invalid enum value. Expected 'ORIGINAL' | 'UPPER' | 'LOWER' | 'TITLE' | 'SMALL_CAPS' | 'SMALL_CAPS_FORCED', received 'SHOUT'`
+ )
+ expect(() => text.setRangeTextCase(0, 5, 'SMALL_CAPS' as 'UPPER')).toThrow(
+ 'in setRangeTextCase: OpenPencil does not support the SMALL_CAPS text case'
+ )
+ expect(() => text.setRangeTextCase(3, 3, 'UPPER')).toThrow(
+ "in setRangeTextCase: Empty range selected. 'end' must be greater than 'start'"
+ )
+ })
+})
+
+describe('hyperlink ranges', () => {
+ test('link a range, read null where none is, and mixed across both', () => {
+ const { text } = styledText()
+ text.setRangeHyperlink(6, 11, LINK)
+
+ expect(text.getRangeHyperlink(6, 11)).toEqual(LINK)
+ expect(text.getRangeHyperlink(0, 5)).toBeNull()
+ expect(typeof text.getRangeHyperlink(0, 11)).toBe('symbol')
+ expect(typeof text.hyperlink).toBe('symbol')
+
+ text.setRangeHyperlink(6, 11, null)
+ expect(text.getRangeHyperlink(0, 11)).toBeNull()
+ expect(text.hyperlink).toBeNull()
+ expect(text.getStyledTextSegments(['hyperlink'])).toHaveLength(1)
+ })
+
+ test('link the whole text from the node, to a URL or a node', () => {
+ const { api, text } = styledText()
+ const frame = api.createFrame()
+ text.hyperlink = { type: 'NODE', value: frame.id }
+ expect(text.getRangeHyperlink(0, 11)).toEqual({ type: 'NODE', value: frame.id })
+ expect(text.hyperlink).toEqual({ type: 'NODE', value: frame.id })
+ })
+
+ test('reject links Figma rejects', () => {
+ const { text } = styledText()
+ expect(() => text.setRangeHyperlink(0, 5, 'https://x' as never)).toThrow(
+ 'in setRangeHyperlink: Property "value" failed validation: Expected object, received string'
+ )
+ expect(() => text.setRangeHyperlink(0, 5, { type: 'PAGE', value: 'x' } as never)).toThrow(
+ `in setRangeHyperlink: Property "value" failed validation: Invalid enum value. Expected 'URL' | 'NODE', received 'PAGE' at .type`
+ )
+ expect(() => text.setRangeHyperlink(0, 5, { type: 'URL', value: 3 } as never)).toThrow(
+ 'in setRangeHyperlink: Property "value" failed validation: Expected string, received number at .value'
+ )
+ })
+
+ // Measured in live Figma (2026-10-11).
+ test('link only to web, mail, and phone addresses, and to layers Figma can frame', () => {
+ const { api, text } = styledText()
+ for (const value of ['https://example.com/a?b=1#c', 'http://x.co', 'mailto:[email protected]', 'tel:+1']) {
+ text.setRangeHyperlink(0, 5, { type: 'URL', value })
+ expect(text.getRangeHyperlink(0, 5)).toEqual({ type: 'URL', value })
+ }
+ for (const value of [
+ 'example.com',
+ 'ftp://x.co',
+ 'HTTPS://X.CO',
+ 'https://',
+ ' https://x.co'
+ ]) {
+ expect(() => text.setRangeHyperlink(0, 5, { type: 'URL', value })).toThrow(
+ 'in setRangeHyperlink: Unsupported or invalid hyperlink url'
+ )
+ }
+ text.setRangeHyperlink(0, 5, { type: 'URL', value: '' })
+ expect(text.getRangeHyperlink(0, 5)).toBeNull()
+
+ for (const layer of [api.createFrame(), api.createSection(), api.currentPage]) {
+ text.setRangeHyperlink(0, 5, { type: 'NODE', value: layer.id })
+ expect(text.getRangeHyperlink(0, 5)).toEqual({ type: 'NODE', value: layer.id })
+ }
+ for (const value of [api.createRectangle().id, text.id, 'missing']) {
+ expect(() => text.setRangeHyperlink(0, 5, { type: 'NODE', value })).toThrow(
+ 'in setRangeHyperlink: Invalid hyperlink target node specified'
+ )
+ }
+ })
+})
+
+describe('style ranges', () => {
+ test('give a range a text style and its fields, and detach it when restyled', async () => {
+ const { api, text } = styledText()
+ textStyle(api, '1:20', { fontSize: 32, fontWeight: 700, textCase: 'UPPER' })
+
+ await text.setRangeTextStyleIdAsync(0, 5, '1:20')
+ expect(text.getRangeTextStyleId(0, 5)).toBe('1:20')
+ expect(text.getRangeFontSize(0, 5)).toBe(32)
+ expect(text.getRangeTextCase(0, 5)).toBe('UPPER')
+ expect(text.getRangeTextStyleId(6, 11)).toBe('')
+ expect(typeof text.textStyleId).toBe('symbol')
+
+ text.setRangeFontSize(0, 2, 10)
+ expect(text.getRangeTextStyleId(0, 2)).toBe('')
+ expect(text.getRangeTextStyleId(2, 5)).toBe('1:20')
+
+ text.setRangeTextStyleId(0, 5, '')
+ expect(text.getRangeTextStyleId(0, 11)).toBe('')
+ })
+
+ test('give a range a fill style and its paints, and detach it when filled', async () => {
+ const { api, text } = styledText()
+ fillStyle(api, '1:30')
+
+ await text.setRangeFillStyleIdAsync(0, 5, '1:30')
+ expect(text.getRangeFillStyleId(0, 5)).toBe('1:30')
+ expect(text.getRangeFills(0, 5)).toMatchObject([{ type: 'SOLID', color: RED }])
+ expect(typeof text.fillStyleId).toBe('symbol')
+
+ text.setRangeFills(0, 5, [{ type: 'SOLID', color: { r: 0, g: 0, b: 1 } }])
+ expect(text.getRangeFillStyleId(0, 5)).toBe('')
+ })
+
+ test('set the node style for every character', async () => {
+ const { api, text } = styledText()
+ fillStyle(api, '1:30')
+ await text.setRangeFillStyleIdAsync(0, 5, '1:30')
+ text.fillStyleId = ''
+ expect(text.fillStyleId).toBe('')
+ expect(text.getRangeFillStyleId(0, 11)).toBe('')
+ })
+
+ test('take only string style IDs', () => {
+ const { text } = styledText()
+ expect(() => text.setRangeTextStyleId(0, 5, 7 as never)).toThrow(
+ 'in setRangeTextStyleId: Property "styleId" failed validation: Expected string, received number'
+ )
+ })
+})
+
+describe('bound variable ranges', () => {
+ function sized() {
+ const { api, text } = styledText()
+ const collection = api.createVariableCollection('Type')
+ const size = api.createVariable('size/lg', 'FLOAT', collection.id, 28)
+ const family = api.createVariable('font/body', 'STRING', collection.id, 'Roboto')
+ return { api, text, collection, size, family }
+ }
+
+ test('bind a range, show the variable value there, and follow it when it changes', () => {
+ const { api, text, collection, size } = sized()
+ text.setRangeBoundVariable(0, 5, 'fontSize', size)
+
+ expect(text.getRangeBoundVariable(0, 5, 'fontSize')).toEqual({
+ type: 'VARIABLE_ALIAS',
+ id: size.id
+ })
+ expect(text.getRangeBoundVariable(6, 11, 'fontSize')).toBeNull()
+ expect(typeof text.getRangeBoundVariable(0, 11, 'fontSize')).toBe('symbol')
+ expect(text.getRangeFontSize(0, 5)).toBe(28)
+ expect(text.getStyledTextSegments(['boundVariables'], 0, 5)).toEqual([
+ {
+ characters: 'Hello',
+ start: 0,
+ end: 5,
+ boundVariables: { fontSize: { type: 'VARIABLE_ALIAS', id: size.id } }
+ }
+ ])
+
+ api.setVariableValue(size.id, collection.defaultModeId, 40)
+ expect(text.getRangeFontSize(0, 5)).toBe(40)
+
+ text.setRangeBoundVariable(0, 5, 'fontSize', null)
+ expect(text.getRangeBoundVariable(0, 11, 'fontSize')).toBeNull()
+ expect(text.getRangeFontSize(0, 5)).toBe(40)
+ })
+
+ test('keep other bindings of the characters bound apart', () => {
+ const { text, size, family } = sized()
+ text.setRangeBoundVariable(0, 5, 'fontSize', size)
+ text.setRangeBoundVariable(3, 8, 'fontFamily', family)
+
+ expect(text.getRangeBoundVariable(0, 5, 'fontSize')).toEqual({
+ type: 'VARIABLE_ALIAS',
+ id: size.id
+ })
+ expect(text.getRangeFontName(3, 8)).toMatchObject({ family: 'Roboto' })
+ expect(text.getRangeBoundVariable(3, 8, 'fontFamily')).toEqual({
+ type: 'VARIABLE_ALIAS',
+ id: family.id
+ })
+ })
+
+ test('bind paragraph spacing for the paragraphs of the range', () => {
+ const { api, text } = styledText('One\nTwo')
+ const collection = api.createVariableCollection('Space')
+ const gap = api.createVariable('gap', 'FLOAT', collection.id, 12)
+ text.setRangeBoundVariable(0, 2, 'paragraphSpacing', gap)
+ expect(text.getRangeParagraphSpacing(0, 2)).toBe(12)
+ expect(text.getRangeParagraphSpacing(5, 6)).toBe(0)
+ })
+
+ test('reject fields and variables Figma cannot bind', () => {
+ const { text, size, family } = sized()
+ expect(() => text.setRangeBoundVariable(0, 5, 'opacity' as 'fontSize', size)).toThrow(
+ `in setRangeBoundVariable: Property "field" failed validation: Invalid enum value. Expected 'fontFamily' | 'fontSize'`
+ )
+ expect(() => text.setRangeBoundVariable(0, 5, 'fontSize', family)).toThrow(
+ 'in setRangeBoundVariable: Cannot bind a STRING variable to "fontSize", which takes FLOAT'
+ )
+ expect(() => text.setRangeBoundVariable(0, 5, 'fontSize', { ...size, id: 'missing' })).toThrow(
+ 'in setRangeBoundVariable: Variable not found'
+ )
+ })
+})
diff --git a/packages/core/tests/text/case.test.ts b/packages/core/tests/text/case.test.ts
new file mode 100644
index 000000000..e74775246
--- /dev/null
+++ b/packages/core/tests/text/case.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createDefaultNode, type StyleRun, type TextCase } from '@open-pencil/scene-graph'
+
+import { shownCharacters, shownText, shownTextSlice } from '#core/text/case'
+
+function text(characters: string, styleRuns: StyleRun[], textCase: TextCase = 'ORIGINAL') {
+ return createDefaultNode(() => 'text', 'TEXT', { text: characters, styleRuns, textCase })
+}
+
+describe('text case by range', () => {
+ test('show each range in its own case and the rest in the text case', () => {
+ const node = text('upper then lower', [{ start: 0, length: 5, style: { textCase: 'UPPER' } }])
+ expect(shownText(node)).toBe('UPPER then lower')
+ expect(shownTextSlice(node, 3, 8)).toBe('ER th')
+
+ const cased = text(
+ 'LOUD AND quiet',
+ [{ start: 9, length: 5, style: { textCase: 'LOWER' } }],
+ 'UPPER'
+ )
+ expect(shownText(cased)).toBe('LOUD AND quiet')
+ })
+
+ test('capitalize only words a title-cased range starts', () => {
+ const node = text('midword and more', [
+ { start: 3, length: 4, style: { textCase: 'TITLE' } },
+ { start: 8, length: 8, style: { textCase: 'TITLE' } }
+ ])
+ expect(shownText(node)).toBe('midword And More')
+
+ const marked = text('a\u0301bc de', [{ start: 1, length: 6, style: { textCase: 'TITLE' } }])
+ expect(shownText(marked)).toBe('a\u0301bc De')
+ })
+
+ test('map every shown character back to the character it comes from', () => {
+ const node = text('aß b', [{ start: 0, length: 2, style: { textCase: 'UPPER' } }])
+ expect(shownText(node)).toBe('ASS b')
+ expect(shownCharacters(node).map((shown) => shown.sourceIndex)).toEqual([0, 1, 1, 2, 3])
+ })
+
+ test('show each character as its whole word is cased, final sigma and astral letters too', () => {
+ const greek = text('AΟΣ', [{ start: 0, length: 3, style: { textCase: 'TITLE' } }])
+ expect(shownText(greek)).toBe('Aος')
+ expect(
+ shownCharacters(greek)
+ .map((shown) => shown.character)
+ .join('')
+ ).toBe('Aος')
+
+ const deseret = text('𐐨𐐨', [{ start: 0, length: 4, style: { textCase: 'TITLE' } }])
+ expect(shownText(deseret)).toBe('𐐀𐐨')
+ expect(shownCharacters(deseret).map((shown) => shown.sourceIndex)).toEqual([0, 2])
+ })
+})
diff --git a/packages/design-jsx/src/export/text.ts b/packages/design-jsx/src/export/text.ts
index 12ec87919..3a720f388 100644
--- a/packages/design-jsx/src/export/text.ts
+++ b/packages/design-jsx/src/export/text.ts
@@ -25,16 +25,23 @@ export interface TextChildren {
inline: boolean
}
-/** Each character's style where it differs from the text's own, as a span writes it. */
+/**
+ * Each character's style where it differs from the text's own, as a span writes it, with the
+ * URL it links to; a span cannot write a link to a node.
+ */
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 style: SpanStyle = pick(run.style, SPAN_STYLE_FIELDS)
+ if (run.style.hyperlink?.type === 'URL') style.hyperlink = run.style.hyperlink
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) => value === undefined || isEqual(value, node[key]))
+ omitBy(
+ style,
+ (value, key) => value === undefined || (key !== 'hyperlink' && isEqual(value, node[key]))
+ )
)
}
@@ -50,6 +57,8 @@ function spanProps(style: SpanStyle, node: SceneNode): JSXProp[] {
if (style.textDecoration !== undefined)
props.push(['textDecoration', style.textDecoration.toLowerCase()])
collectDecorationProps(style, node, props)
+ if (style.textCase !== undefined) props.push(['textCase', style.textCase.toLowerCase()])
+ if (style.hyperlink) props.push(['href', style.hyperlink.value])
return props
}
diff --git a/packages/design-jsx/src/reference/authoring.md b/packages/design-jsx/src/reference/authoring.md
index 60e158350..f3e9bbe5b 100644
--- a/packages/design-jsx/src/reference/authoring.md
+++ b/packages/design-jsx/src/reference/authoring.md
@@ -23,7 +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`. Decorations take CSS's names and values: `textDecorationStyle` (`solid`, `dotted`, `wavy`), `textDecorationColor` (`currentColor` follows the text), `textDecorationThickness` and `textUnderlineOffset` (pixels or `auto`), and `textDecorationSkipInk`. `lineHeight="auto"` follows the font, and `fills={[]}` paints no text. Verify fonts actually load before judging dimensions; do not assume every font is available.
-- `Span` styles some characters of a `Text` with `Text`'s own prop names: `size`, `font`, `weight`, `italic`, `color`, `fills`, `lineHeight`, `letterSpacing`, `textDecoration`, and the decoration details. Spans nest; the inner one wins. `Paragraph` writes one paragraph: `list="ordered"` or `list="unordered"` makes it a list item nested at `level` 1–5, and `spacing`, `listSpacing`, and `indent` override the `Text`'s `paragraphSpacing`, `listSpacing`, and `paragraphIndent` for it; `hangingList` on the `Text` hangs list markers outside the text box. A `Text` holds only `Paragraph`s or none; without them, a line break in its text still starts a paragraph.
+- `Span` styles some characters of a `Text` with `Text`'s own prop names: `size`, `font`, `weight`, `italic`, `color`, `fills`, `lineHeight`, `letterSpacing`, `textDecoration`, the decoration details, and `textCase`. `href` links its characters to a URL without changing how they look. Spans nest; the inner one wins. `Paragraph` writes one paragraph: `list="ordered"` or `list="unordered"` makes it a list item nested at `level` 1–5, and `spacing`, `listSpacing`, and `indent` override the `Text`'s `paragraphSpacing`, `listSpacing`, and `paragraphIndent` for it; `hangingList` on the `Text` hangs list markers outside the text box. A `Text` holds only `Paragraph`s or none; without them, a line break in its text still starts a paragraph.
- `Icon` uses an Iconify name, size, and color. Prefer icons to emoji when reliable vector output is needed. Image fills belong on appropriate leaf shapes, not containers whose children must remain visible.
- Design JSX props are the portable authoring interface. Some CSS-style aliases are supported, but this is not a browser CSS engine; do not assume arbitrary HTML, classes, or styles work.
diff --git a/packages/design-jsx/src/schema.ts b/packages/design-jsx/src/schema.ts
index 82644f083..e68e8a359 100644
--- a/packages/design-jsx/src/schema.ts
+++ b/packages/design-jsx/src/schema.ts
@@ -71,7 +71,7 @@ export const DESIGN_JSX_PARAGRAPH_PROPERTY_NAMES = [
'indent'
] as const
-/** Props `<Span>` takes: `<Text>`'s character styles, under the same names. */
+/** Props `<Span>` takes: `<Text>`'s character styles, under the same names, and a link. */
export const DESIGN_JSX_SPAN_PROPERTY_NAMES = [
'style',
'size',
@@ -91,7 +91,9 @@ export const DESIGN_JSX_SPAN_PROPERTY_NAMES = [
'textDecorationColor',
'textDecorationThickness',
'textUnderlineOffset',
- 'textDecorationSkipInk'
+ 'textDecorationSkipInk',
+ 'textCase',
+ 'href'
] as const
/** Props `<Text>` sets every paragraph's spacing with; a `<Paragraph>` sets its own. */
diff --git a/packages/design-jsx/src/text-content.ts b/packages/design-jsx/src/text-content.ts
index fb634b13d..3076d2f7b 100644
--- a/packages/design-jsx/src/text-content.ts
+++ b/packages/design-jsx/src/text-content.ts
@@ -41,10 +41,15 @@ export const SPAN_STYLE_FIELDS = [
'textDecorationFills',
'textDecorationThickness',
'textUnderlineOffset',
- 'textDecorationSkipInk'
+ 'textDecorationSkipInk',
+ 'textCase'
] as const satisfies readonly (keyof CharacterStyleOverride & keyof SceneNode)[]
-export type SpanStyle = Pick<CharacterStyleOverride, (typeof SPAN_STYLE_FIELDS)[number]>
+/** A span's character styles and the URL it links to, which only characters have. */
+export type SpanStyle = Pick<
+ CharacterStyleOverride,
+ (typeof SPAN_STYLE_FIELDS)[number] | 'hyperlink'
+>
/** The fields an element's props set on a text node, as `propsToOverrides` reads them. */
export type SpanOverrides = (props: Record<string, unknown>) => Partial<SceneNode>
@@ -80,8 +85,16 @@ export function isTextContent(child: TreeNode | string): boolean {
return isTreeNode(child) && (child.type === SPAN || child.type === PARAGRAPH)
}
+const SpanLink = v.object({ href: v.optional(v.pipe(v.string(), v.trim(), v.nonEmpty())) })
+
function spanStyle(props: Record<string, unknown>, spanOverrides: SpanOverrides): SpanStyle {
- return omitBy(pick(spanOverrides(props), SPAN_STYLE_FIELDS), (value) => value === undefined)
+ const style: SpanStyle = omitBy(
+ pick(spanOverrides(props), SPAN_STYLE_FIELDS),
+ (value) => value === undefined
+ )
+ const { href } = parseScriptInput('Invalid <Span> props', SpanLink, props)
+ if (href) style.hyperlink = { type: 'URL', value: href }
+ return style
}
function appendContent(
diff --git a/packages/design-jsx/tests/export/text.test.ts b/packages/design-jsx/tests/export/text.test.ts
index 783df60e4..1d790f30c 100644
--- a/packages/design-jsx/tests/export/text.test.ts
+++ b/packages/design-jsx/tests/export/text.test.ts
@@ -16,6 +16,21 @@ function exportText(fields: Partial<SceneNode>): string {
}
describe('rich text export', () => {
+ test('writes a range case and a URL link as Span props', () => {
+ const code = exportText({
+ text: 'Read docs',
+ styleRuns: [
+ {
+ start: 5,
+ length: 4,
+ style: { textCase: 'UPPER', hyperlink: { type: 'URL', value: 'https://openpencil.dev' } }
+ },
+ { start: 0, length: 4, style: { hyperlink: { type: 'NODE', value: '1:2' } } }
+ ]
+ })
+ expect(code).toContain('Read <Span textCase="upper" href="https://openpencil.dev">docs</Span>')
+ })
+
test('writes styled characters as spans with only what differs', () => {
const code = exportText({
text: 'Hello world!',
diff --git a/packages/design-jsx/tests/text-content.test.ts b/packages/design-jsx/tests/text-content.test.ts
index 758cea5a7..126ce0d3b 100644
--- a/packages/design-jsx/tests/text-content.test.ts
+++ b/packages/design-jsx/tests/text-content.test.ts
@@ -25,6 +25,27 @@ async function renderText(source: string): Promise<{ node: SceneNode; warnings:
}
describe('Span', () => {
+ test('cases and links its characters', async () => {
+ const { node, warnings } = await renderText(
+ '<Text textCase="upper">Read <Span textCase="original" href="https://openpencil.dev">the docs</Span></Text>'
+ )
+ expect(warnings).toEqual([])
+ expect(node.textCase).toBe('UPPER')
+ expect(node.styleRuns).toEqual([
+ {
+ start: 5,
+ length: 8,
+ style: { textCase: 'ORIGINAL', hyperlink: { type: 'URL', value: 'https://openpencil.dev' } }
+ }
+ ])
+ })
+
+ test('rejects an empty link', async () => {
+ await expect(renderText('<Text><Span href="">a</Span></Text>')).rejects.toThrow(
+ 'Invalid <Span> props'
+ )
+ })
+
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>'
diff --git a/packages/docs/programmable/cli/scripting.md b/packages/docs/programmable/cli/scripting.md
index 3c50a81f3..7e9b79835 100644
--- a/packages/docs/programmable/cli/scripting.md
+++ b/packages/docs/programmable/cli/scripting.md
@@ -195,7 +195,7 @@ Common node properties are readable/writable through the proxy, including:
- Appearance: `fills`, `strokes`, `effects`, `opacity`, `visible`, `locked`, `blendMode`, `clipsContent`
- Radius: `cornerRadius`, `topLeftRadius`, `topRightRadius`, `bottomRightRadius`, `bottomLeftRadius`
- 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 ranges: `getStyledTextSegments(fields, start?, end?)`, and `getRange…` / `setRange…` for `FontSize`, `FontName`, `Fills`, `LetterSpacing`, `LineHeight`, `TextDecoration` with its `Style`, `Offset`, `Thickness`, `Color`, and `SkipInk`, `TextCase`, `Hyperlink` (a `{ type: 'URL' | 'NODE', value }` link, or `null`), `TextStyleId` and `FillStyleId` (set with `setRangeTextStyleIdAsync` and `setRangeFillStyleIdAsync`, which give the range the style's fields), and `getRangeBoundVariable` / `setRangeBoundVariable` for the text fields Figma binds, plus `getRangeFontWeight`, `getRangeAllFontNames`, and `getRangeOpenTypeFeatures`. Lengths read in pixels; a percent given to a setter is of the font size
- Text lists and paragraphs: `getRangeListOptions` / `setRangeListOptions` for bulleted (`UNORDERED`) and numbered (`ORDERED`) items, `getRangeIndentation` / `setRangeIndentation` for nesting (1–5 for list items), `listSpacing`, `paragraphSpacing`, and `paragraphIndent` for the whole text (`figma.mixed` when paragraphs differ) or per paragraph with `getRangeListSpacing` / `setRangeListSpacing`, `getRangeParagraphSpacing` / `setRangeParagraphSpacing`, and `getRangeParagraphIndent` / `setRangeParagraphIndent`, and `hangingList`
- Auto-layout: `layoutMode`, `primaryAxisAlignItems`, `counterAxisAlignItems`, `itemSpacing`, padding, sizing, and layout positioning fields
- Stroke helpers: `strokeWeight`, `strokeAlign`, `dashPattern`
diff --git a/packages/docs/reference/design-authoring.md b/packages/docs/reference/design-authoring.md
index 7b52ea215..096ba6daf 100644
--- a/packages/docs/reference/design-authoring.md
+++ b/packages/docs/reference/design-authoring.md
@@ -25,7 +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`. Decorations take CSS's names and values: `textDecorationStyle` (`solid`, `dotted`, `wavy`), `textDecorationColor` (`currentColor` follows the text), `textDecorationThickness` and `textUnderlineOffset` (pixels or `auto`), and `textDecorationSkipInk`. `lineHeight="auto"` follows the font, and `fills={[]}` paints no text. Verify fonts actually load before judging dimensions; do not assume every font is available.
-- `Span` styles some characters of a `Text` with `Text`'s own prop names: `size`, `font`, `weight`, `italic`, `color`, `fills`, `lineHeight`, `letterSpacing`, `textDecoration`, and the decoration details. Spans nest; the inner one wins. `Paragraph` writes one paragraph: `list="ordered"` or `list="unordered"` makes it a list item nested at `level` 1–5, and `spacing`, `listSpacing`, and `indent` override the `Text`'s `paragraphSpacing`, `listSpacing`, and `paragraphIndent` for it; `hangingList` on the `Text` hangs list markers outside the text box. A `Text` holds only `Paragraph`s or none; without them, a line break in its text still starts a paragraph.
+- `Span` styles some characters of a `Text` with `Text`'s own prop names: `size`, `font`, `weight`, `italic`, `color`, `fills`, `lineHeight`, `letterSpacing`, `textDecoration`, the decoration details, and `textCase`. `href` links its characters to a URL without changing how they look. Spans nest; the inner one wins. `Paragraph` writes one paragraph: `list="ordered"` or `list="unordered"` makes it a list item nested at `level` 1–5, and `spacing`, `listSpacing`, and `indent` override the `Text`'s `paragraphSpacing`, `listSpacing`, and `paragraphIndent` for it; `hangingList` on the `Text` hangs list markers outside the text box. A `Text` holds only `Paragraph`s or none; without them, a line break in its text still starts a paragraph.
- `Icon` uses an Iconify name, size, and color. Prefer icons to emoji when reliable vector output is needed. Image fills belong on appropriate leaf shapes, not containers whose children must remain visible.
- Design JSX props are the portable authoring interface. Some CSS-style aliases are supported, but this is not a browser CSS engine; do not assume arbitrary HTML, classes, or styles work.
diff --git a/packages/dom-css/AGENTS.md b/packages/dom-css/AGENTS.md
index 9a0aaebca..97a294898 100644
--- a/packages/dom-css/AGENTS.md
+++ b/packages/dom-css/AGENTS.md
@@ -16,4 +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`).
+- Rich text maps one way in both directions: style runs are spans that set only what differs from the text, linked runs are `<a href>` in the text's own look, 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.ts
index 530a06f47..08e3c6589 100644
--- a/packages/dom-css/src/export/projection.ts
+++ b/packages/dom-css/src/export/projection.ts
@@ -14,7 +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'
+import { textCaseToCSS, textElementContent } from './text'
const DOM_CSS_PLUGIN_ID = 'open-pencil-dom-css'
const IMAGE_SOURCE_URL_KEY = 'image-source-url'
@@ -76,13 +76,6 @@ function alignToCSS(
return undefined
}
-function textCaseToCSS(value: SceneNode['textCase']): string | undefined {
- if (value === 'UPPER') return 'uppercase'
- if (value === 'LOWER') return 'lowercase'
- if (value === 'TITLE') return 'capitalize'
- return undefined
-}
-
/** Whether a layer sizes itself to its content along an axis, so CSS should too. */
function hugs(node: SceneNode, axis: 'width' | 'height'): boolean {
if (node.type === 'TEXT')
diff --git a/packages/dom-css/src/export/text.ts b/packages/dom-css/src/export/text.ts
index 4633cf67e..b7564b9a9 100644
--- a/packages/dom-css/src/export/text.ts
+++ b/packages/dom-css/src/export/text.ts
@@ -8,6 +8,7 @@ import {
textListItems,
textParagraphRanges,
type CharacterStyleOverride,
+ type HyperlinkTarget,
type SceneNode,
type TextListItem,
type TextParagraphRange
@@ -32,6 +33,7 @@ type CharacterStyle = Pick<
| 'textDecorationFills'
| 'textDecorationSkipInk'
| 'textUnderlineOffset'
+ | 'textCase'
>
type CharacterStyleKey = keyof CharacterStyle
@@ -49,7 +51,8 @@ const CHARACTER_STYLE_KEYS: readonly CharacterStyleKey[] = [
'textDecorationThickness',
'textDecorationFills',
'textDecorationSkipInk',
- 'textUnderlineOffset'
+ 'textUnderlineOffset',
+ 'textCase'
]
/** A list's indent per level, in ems of its first character, as the canvas lays lists out. */
@@ -66,11 +69,33 @@ const DECORATION_PROPERTIES = new Set([
const px = (value: number) => `${value}px`
-/** Characters `[start, end)` and the run style over them. */
+/** Characters `[start, end)`, the run style over them, and where they link to. */
interface StyledRange {
start: number
end: number
style: CharacterStyle
+ href: string | null
+}
+
+/** Links a page can follow: to the web, to mail, or to a phone; others are left out. */
+const LINK_PROTOCOLS = new Set(['http:', 'https:', 'mailto:', 'tel:'])
+
+/** A link as an `href`, for a link to a URL a page can follow. */
+function linkHref(link: HyperlinkTarget | null | undefined): string | null {
+ if (link?.type !== 'URL') return null
+ try {
+ return LINK_PROTOCOLS.has(new URL(link.value).protocol) ? link.value : null
+ } catch {
+ // Not an absolute URL, which a page could not follow from anywhere it is placed.
+ return null
+ }
+}
+
+export function textCaseToCSS(value: SceneNode['textCase']): string | undefined {
+ if (value === 'UPPER') return 'uppercase'
+ if (value === 'LOWER') return 'lowercase'
+ if (value === 'TITLE') return 'capitalize'
+ return undefined
}
function characterStyle(node: SceneNode, override: CharacterStyleOverride = {}): CharacterStyle {
@@ -90,11 +115,16 @@ function styledRanges(node: SceneNode): StyledRange[] {
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) })
+ if (start > at) ranges.push({ start: at, end: start, style: base, href: null })
+ if (end > start) {
+ const href = linkHref(run.style.hyperlink)
+ ranges.push({ start, end, style: characterStyle(node, run.style), href })
+ }
at = Math.max(at, end)
}
- if (at < node.text.length) ranges.push({ start: at, end: node.text.length, style: base })
+ if (at < node.text.length) {
+ ranges.push({ start: at, end: node.text.length, style: base, href: null })
+ }
return ranges
}
@@ -129,6 +159,7 @@ function characterCSS(style: CharacterStyle, decorated: boolean): DesignStyleDec
'font-style': style.italic ? 'italic' : 'normal',
'letter-spacing': px(style.letterSpacing),
'line-height': style.lineHeight === null ? 'normal' : px(style.lineHeight),
+ 'text-transform': textCaseToCSS(style.textCase) ?? 'none',
...(decorated ? decorationCSS(style) : {})
}
}
@@ -173,10 +204,22 @@ function element(
return { type: 'element', tagName, attrs: {}, inlineStyle, children }
}
-/** `text[start, end)` as text and spans, each span setting only what differs from the layer. */
+/**
+ * A link styled as the text around it: a link draws in the text's colour and with only the
+ * decoration its characters have, as in Figma, not in a browser's link style.
+ */
+function linkElement(href: string, css: DesignStyleDeclaration, text: string): DesignElement {
+ const style = { color: 'inherit', 'text-decoration-line': 'none', ...css }
+ return { ...element('a', style, [textNode(text)]), attrs: { href } }
+}
+
+/**
+ * `text[start, end)` as text and spans, each span setting only what differs from the layer;
+ * linked characters are a link instead.
+ */
function inlineContent(projection: TextProjection, start: number, end: number): DesignNode[] {
const { node, ranges, base, decorated } = projection
- const pieces: { css: DesignStyleDeclaration; text: string }[] = []
+ const pieces: { css: DesignStyleDeclaration; text: string; href: string | null }[] = []
for (const range of ranges) {
const from = Math.max(start, range.start)
const to = Math.min(end, range.end)
@@ -184,12 +227,14 @@ function inlineContent(projection: TextProjection, start: number, end: number):
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 })
+ if (previous && previous.href === range.href && isEqual(previous.css, css)) {
+ previous.text += text
+ } else pieces.push({ css, text, href: range.href })
}
- return pieces.map(({ css, text }) =>
- Object.keys(css).length === 0 ? textNode(text) : element('span', css, [textNode(text)])
- )
+ return pieces.map(({ css, text, href }) => {
+ if (href) return linkElement(href, css, text)
+ return 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. */
diff --git a/packages/dom-css/src/import/scene-graph.ts b/packages/dom-css/src/import/scene-graph.ts
index a4006d83d..10abeab03 100644
--- a/packages/dom-css/src/import/scene-graph.ts
+++ b/packages/dom-css/src/import/scene-graph.ts
@@ -25,6 +25,7 @@ import {
import {
blockRichText,
characterStyleFromCSS,
+ elementLink,
holdsTextBlocks,
inlineRichText,
isInlineContent,
@@ -181,13 +182,6 @@ function applyCornerRadii(node: SceneNode, style: DesignStyleDeclaration): void
].some((radius) => radius !== fallback)
}
-function textCaseFromCSS(value: string | undefined): SceneNode['textCase'] {
- if (value === 'uppercase') return 'UPPER'
- if (value === 'lowercase') return 'LOWER'
- if (value === 'capitalize') return 'TITLE'
- return 'ORIGINAL'
-}
-
function applyFlexGap(node: SceneNode, style: DesignStyleDeclaration): void {
const gap = firstCSSNumber(style, 'gap')
const rowGap = firstCSSNumber(style, 'row-gap')
@@ -361,7 +355,8 @@ const CHARACTER_FIELDS = [
'textDecorationThickness',
'textDecorationFills',
'textDecorationSkipInk',
- 'textUnderlineOffset'
+ 'textUnderlineOffset',
+ 'textCase'
] as const satisfies readonly (keyof CSSCharacterStyle)[]
function applyTextStyle(node: SceneNode, style: DesignStyleDeclaration): void {
@@ -380,9 +375,6 @@ function applyTextStyle(node: SceneNode, style: DesignStyleDeclaration): void {
node.textAlignHorizontal = textAlign
}
- const textCase = textCaseFromCSS(pickStyle(style, 'text-transform'))
- if (textCase !== 'ORIGINAL') node.textCase = textCase
-
if (pickStyle(style, 'white-space') === 'nowrap') node.maxLines = 1
}
@@ -442,6 +434,14 @@ function createTextNode(
return node
}
+/** A link of text alone links all of it. */
+function linkText(node: SceneNode, element: DesignElement): void {
+ const hyperlink = elementLink(element)
+ if (hyperlink && node.text.length > 0) {
+ node.styleRuns = [{ start: 0, length: node.text.length, style: { hyperlink } }]
+ }
+}
+
function hasBoxStyle(style: DesignStyleDeclaration): boolean {
return [
'aspect-ratio',
@@ -503,7 +503,9 @@ function createElementNode(
!hasBoxStyle(style) &&
element.children.every((child) => child.type === 'text')
) {
- return createTextNode(graph, parentId, textContent(element), style, display, parentFlow)
+ const text = createTextNode(graph, parentId, textContent(element), style, display, parentFlow)
+ linkText(text, element)
+ return text
}
if (!hasBoxStyle(style) && holdsRichText(element)) {
return createRichTextNode(graph, parentId, element, style, display, parentFlow)
diff --git a/packages/dom-css/src/import/text.ts b/packages/dom-css/src/import/text.ts
index 429f1b2f7..13088af91 100644
--- a/packages/dom-css/src/import/text.ts
+++ b/packages/dom-css/src/import/text.ts
@@ -3,6 +3,7 @@ import { isEqual } from 'es-toolkit/predicate'
import type {
CharacterStyleOverride,
+ HyperlinkTarget,
SceneNode,
StyleRun,
TextParagraphStyle
@@ -28,8 +29,12 @@ export type CSSCharacterStyle = Pick<
| 'textDecorationFills'
| 'textDecorationSkipInk'
| 'textUnderlineOffset'
+ | 'textCase'
>
+/** A character's style and the link it is part of. */
+type CharacterOfText = CSSCharacterStyle & { hyperlink?: HyperlinkTarget }
+
/**
* What characters take from the elements around them: the properties CSS inherits, and the
* decoration, which CSS draws through descendants.
@@ -43,6 +48,7 @@ const CHARACTER_PROPERTIES = [
'letter-spacing',
'line-height',
'white-space',
+ 'text-transform',
'text-decoration-line',
'text-decoration-style',
'text-decoration-color',
@@ -86,6 +92,13 @@ function decorationStyle(value: string | undefined): SceneNode['textDecorationSt
return 'SOLID'
}
+function textCaseFromCSS(value: string | undefined): SceneNode['textCase'] {
+ if (value === 'uppercase') return 'UPPER'
+ if (value === 'lowercase') return 'LOWER'
+ if (value === 'capitalize') return 'TITLE'
+ return 'ORIGINAL'
+}
+
/** The character style of CSS declarations, over `base` for what they leave out. */
export function characterStyleFromCSS(
style: DesignStyleDeclaration,
@@ -98,6 +111,7 @@ export function characterStyleFromCSS(
const line = pickStyle(style, 'text-decoration-line')
const fontStyle = pickStyle(style, 'font-style')
const lineHeight = pickStyle(style, 'line-height')
+ const textTransform = pickStyle(style, 'text-transform')
return {
fontFamily: family || base.fontFamily,
fontSize: parseCSSNumber(pickStyle(style, 'font-size')) ?? base.fontSize,
@@ -123,7 +137,8 @@ export function characterStyleFromCSS(
textDecorationSkipInk:
pickStyle(style, 'text-decoration-skip-ink') === undefined
? base.textDecorationSkipInk
- : pickStyle(style, 'text-decoration-skip-ink') !== 'none'
+ : pickStyle(style, 'text-decoration-skip-ink') !== 'none',
+ textCase: textTransform === undefined ? base.textCase : textCaseFromCSS(textTransform)
}
}
@@ -221,7 +236,9 @@ export interface RichText {
interface Collector {
base: CSSCharacterStyle
text: string
- styles: CSSCharacterStyle[]
+ styles: CharacterOfText[]
+ /** The link the characters added now are part of. */
+ link: HyperlinkTarget | null
paragraphs: TextParagraphStyle[]
spaceAfter: number[]
indents: number[]
@@ -235,9 +252,17 @@ function preservesWhitespace(style: DesignStyleDeclaration): boolean {
return whiteSpace === 'pre' || whiteSpace === 'pre-wrap' || whiteSpace === 'pre-line'
}
-function appendCharacters(collector: Collector, text: string, style: CSSCharacterStyle): void {
+function appendCharacters(collector: Collector, text: string, style: CharacterOfText): void {
+ const styled = collector.link ? { ...style, hyperlink: collector.link } : style
collector.text += text
- collector.styles.push(...Array.from({ length: text.length }, () => style))
+ collector.styles.push(...Array.from({ length: text.length }, () => styled))
+}
+
+/** Where a link element goes, for an `<a>` with an `href`. */
+export function elementLink(element: DesignElement): HyperlinkTarget | null {
+ if (element.tagName.toLowerCase() !== 'a' || !Object.hasOwn(element.attrs, 'href')) return null
+ const href = element.attrs.href.trim()
+ return href ? { type: 'URL', value: href } : null
}
/**
@@ -270,7 +295,10 @@ function addInline(
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())) {
+ const around = collector.link
+ collector.link = elementLink(node) ?? around
addInline(collector, node.children, characterDeclarations(node, style))
+ collector.link = around
}
}
}
@@ -361,12 +389,13 @@ function addList(
}
/** Runs of characters whose style differs from the text's own. */
-function styleRunsFrom(styles: readonly CSSCharacterStyle[], base: CSSCharacterStyle): StyleRun[] {
+function styleRunsFrom(styles: readonly CharacterOfText[], 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] })
+ for (const key of Object.keys(style) as (keyof CharacterOfText)[]) {
+ const own = key === 'hyperlink' ? undefined : base[key]
+ if (!isEqual(style[key], own)) Object.assign(override, { [key]: style[key] })
}
const previous = runs.at(-1)
if (
@@ -393,11 +422,12 @@ function richTextFrom(collector: Collector): RichText {
}
}
-function collector(base: CSSCharacterStyle): Collector {
+function collector(base: CSSCharacterStyle, link: HyperlinkTarget | null): Collector {
return {
base,
text: '',
styles: [],
+ link,
paragraphs: [],
spaceAfter: [],
indents: [],
@@ -412,7 +442,8 @@ export function inlineRichText(
style: DesignStyleDeclaration,
base: CSSCharacterStyle
): RichText {
- const text = collector(base)
+ // A link the element is itself, as an `<a>` holding spans, links all its characters.
+ const text = collector(base, elementLink(element))
addTrimmed(text, element.children, characterDeclarations(element, style))
return richTextFrom(text)
}
@@ -423,7 +454,7 @@ export function blockRichText(
style: DesignStyleDeclaration,
base: CSSCharacterStyle
): RichText {
- const text = collector(base)
+ const text = collector(base, elementLink(element))
const around = characterDeclarations(element, style)
const blocks = LIST_TAGS.has(element.tagName.toLowerCase()) ? [element] : element.children
for (const block of blocks) {
diff --git a/packages/dom-css/tests/export/text.test.ts b/packages/dom-css/tests/export/text.test.ts
index a9cb3ad5c..ae06bbf4d 100644
--- a/packages/dom-css/tests/export/text.test.ts
+++ b/packages/dom-css/tests/export/text.test.ts
@@ -15,6 +15,8 @@ const RED: Fill = {
opacity: 1,
visible: true
}
+/** A link that runs script, which no export may write. */
+const SCRIPT_SCHEME = ['java', 'script:'].join('')
const PLAIN: TextParagraphStyle = { listType: 'NONE', indentation: 0 }
function text(props: Parameters<SceneGraph['createNode']>[2]) {
@@ -128,4 +130,40 @@ describe('text export', () => {
expect(layerIds).toEqual([node.id, null, null, null, null])
expect(code.match(/<(?!\/)[A-Za-z]/g)).toHaveLength(layerIds.length)
})
+
+ test('writes a range in its own case as text-transform', () => {
+ const { html } = text({
+ text: 'loud quiet',
+ textCase: 'UPPER',
+ styleRuns: [{ start: 5, length: 5, style: { textCase: 'ORIGINAL' } }]
+ })
+ expect(html).toContain('text-transform: uppercase')
+ expect(html).toContain('loud <span style="text-transform: none">quiet</span>')
+ })
+
+ test('writes linked characters as a link in the look of the text around it', () => {
+ const { graph, node, html } = text({
+ text: 'Read the docs now',
+ styleRuns: [
+ {
+ start: 9,
+ length: 4,
+ style: { hyperlink: { type: 'URL', value: 'https://openpencil.dev/docs' } }
+ },
+ {
+ start: 14,
+ length: 3,
+ style: { hyperlink: { type: 'URL', value: `${SCRIPT_SCHEME}alert(1)` } }
+ }
+ ]
+ })
+ expect(html).toContain(
+ 'Read the <a href="https://openpencil.dev/docs" style="color: inherit; text-decoration-line: none">docs</a> now'
+ )
+ expect(html).not.toContain(SCRIPT_SCHEME)
+ const jsx = sceneNodesToTailwindJSX(graph, [node.id])
+ expect(jsx).toContain(
+ '<a href="https://openpencil.dev/docs" className="text-inherit no-underline">docs</a>'
+ )
+ })
})
diff --git a/packages/dom-css/tests/import/text.test.ts b/packages/dom-css/tests/import/text.test.ts
index c8ec8accd..48bec59dd 100644
--- a/packages/dom-css/tests/import/text.test.ts
+++ b/packages/dom-css/tests/import/text.test.ts
@@ -152,4 +152,49 @@ describe('rich text import', () => {
})
expect(back.hangingList).toBe(true)
})
+
+ test('reads links in text as linked ranges, and a link of text alone as linked text', async () => {
+ const [text] = await texts(
+ '<p>Read <a href="https://openpencil.dev/docs">the <b>docs</b></a> now</p>'
+ )
+ const link = { type: 'URL' as const, value: 'https://openpencil.dev/docs' }
+ expect(text?.styleRuns).toEqual([
+ { start: 5, length: 4, style: { hyperlink: link } },
+ { start: 9, length: 4, style: { hyperlink: link, fontWeight: 700 } }
+ ])
+ const [alone] = await texts('<a href="https://openpencil.dev">Home</a>')
+ expect(alone?.styleRuns).toEqual([
+ {
+ start: 0,
+ length: 4,
+ style: { hyperlink: { type: 'URL', value: 'https://openpencil.dev' } }
+ }
+ ])
+ const [rich] = await texts('<a href="https://openpencil.dev">Go <b>home</b></a>')
+ expect(
+ rich?.styleRuns.every((run) => run.style.hyperlink?.value === 'https://openpencil.dev')
+ ).toBe(true)
+ expect(rich?.styleRuns.reduce((sum, run) => sum + run.length, 0)).toBe(rich?.text.length)
+ })
+
+ test('reads text-transform on a span as the case of its characters', async () => {
+ const [text] = await texts(
+ '<p style="text-transform: uppercase">loud <span style="text-transform: none">quiet</span></p>'
+ )
+ expect(text?.textCase).toBe('UPPER')
+ expect(text?.styleRuns).toEqual([{ start: 5, length: 5, style: { textCase: 'ORIGINAL' } }])
+ })
+
+ test('reads back the links and cases it writes', async () => {
+ const styleRuns = [
+ {
+ start: 0,
+ length: 4,
+ style: { hyperlink: { type: 'URL' as const, value: 'https://openpencil.dev/' } }
+ },
+ { start: 5, length: 4, style: { textCase: 'UPPER' as const } }
+ ]
+ const { back } = await roundTrip({ text: 'Home loud', styleRuns })
+ expect(back?.styleRuns).toEqual(styleRuns)
+ })
})
diff --git a/packages/fig/src/document/bindings/references.ts b/packages/fig/src/document/bindings/references.ts
index db1b221d1..9dbaab0d3 100644
--- a/packages/fig/src/document/bindings/references.ts
+++ b/packages/fig/src/document/bindings/references.ts
@@ -71,6 +71,8 @@ function createRecordNormalizer(resolve: ReturnType<typeof createResourceResolve
for (const field of STYLE_REFERENCE_FIELDS) {
normalize(node[field] as NodeChange['variableSetID'], field, path)
}
+ // A text's ranges bind variables and use styles in their own style overrides.
+ for (const override of node.textData?.styleOverrideTable ?? []) visit(override, path)
visitChildren(node, path, visit)
}
visit(record, [])
diff --git a/packages/fig/src/document/materialize.ts b/packages/fig/src/document/materialize.ts
index 5707b83ef..5d08d60ac 100644
--- a/packages/fig/src/document/materialize.ts
+++ b/packages/fig/src/document/materialize.ts
@@ -1,5 +1,10 @@
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
-import { generateId, SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
+import {
+ generateId,
+ remapStyleRunReferences,
+ SceneGraph,
+ type SceneNode
+} from '@open-pencil/scene-graph'
import {
reconcileLiveComponentEdits,
@@ -400,6 +405,15 @@ function materializeReaderInto(
const id = node[field]
if (id && sources.has(id)) node[field] = sources.get(id) ?? id
}
+ // Ranges name their styles and linked layers by record too; a layer left out stays named.
+ if (node.styleRuns.length > 0) {
+ const source = (id: string) => sources.get(id) ?? id
+ node.styleRuns = remapStyleRunReferences(node.styleRuns, {
+ variable: (id) => id,
+ style: source,
+ node: source
+ })
+ }
}
// These passes apply to the nodes this page added, not to the whole graph.
const materialized = [...graph.nodes.values()].filter((node) => !existingNodeIds.has(node.id))
diff --git a/packages/fig/src/node-change/convert.ts b/packages/fig/src/node-change/convert.ts
index 5a12b8d56..b64e30610 100644
--- a/packages/fig/src/node-change/convert.ts
+++ b/packages/fig/src/node-change/convert.ts
@@ -28,6 +28,7 @@ import {
extractPluginRelaunchData,
readNodeChangePluginData
} from './plugin-data'
+import { styleRefId } from './style/refs'
import { importStyleRuns } from './style/runs'
import { importParagraphStyles } from './text/lines'
import {
@@ -317,8 +318,9 @@ function convertPolygonProps(
/**
* A text's line height. Figma writes auto as 100 percent, and OpenPencil once wrote none for
- * it; a text in auto lines up each line at its own font's height. A height in pixels is the one
- * the saved lines were laid out at, which a style the text uses may set apart from its own.
+ * it; a text in auto lines up each line at its own font's height. Figma saves each line at the
+ * larger of its line height and its tallest font's height, so a first line shorter than the
+ * text's height in pixels was laid out at another one, which a style the text uses set.
*/
function importedTextLineHeight(nc: NodeChange): number | null {
if (!nc.lineHeight || isFigmaAutoLineHeight(nc.lineHeight)) return null
@@ -326,7 +328,8 @@ function importedTextLineHeight(nc: NodeChange): number | null {
if (
nc.lineHeight.units === 'PIXELS' &&
derivedLineHeight !== undefined &&
- Number.isFinite(derivedLineHeight)
+ Number.isFinite(derivedLineHeight) &&
+ derivedLineHeight < nc.lineHeight.value
)
return derivedLineHeight
return convertLineHeight(nc.lineHeight, nc.fontSize)
@@ -568,15 +571,6 @@ function getVectorStrokeJoin(nc: NodeChange, vectorNetwork: VectorNetwork | null
'MITER') as StrokeJoin
}
-function styleRefId(value: unknown): string | null {
- if (!value || typeof value !== 'object' || !('guid' in value)) return null
- const guid = value.guid
- if (!guid || typeof guid !== 'object') return null
- // The unset GUID denotes an explicitly cleared style reference.
- if (isUnsetGuid(guid as GUID)) return null
- return guidToString(guid as GUID)
-}
-
function sharedStyleType(value: string | undefined): SharedStyleType | null {
if (value === 'FILL' || value === 'TEXT' || value === 'EFFECT' || value === 'GRID') return value
return null
diff --git a/packages/fig/src/node-change/export/node.ts b/packages/fig/src/node-change/export/node.ts
index 5dca240ea..e687ec229 100644
--- a/packages/fig/src/node-change/export/node.ts
+++ b/packages/fig/src/node-change/export/node.ts
@@ -29,6 +29,7 @@ import {
mergePluginData,
serializePluginRelaunchData
} from '../plugin-data'
+import { applyTextRunReferences } from '../text/run-references'
import {
applyColorVariableBinding,
createFillPaints,
@@ -816,6 +817,19 @@ function applySharedStyleProps(
if (node.guides.length > 0) nc.guides = exportCanvasGuides(node.guides)
}
+/** A text's props, and what its ranges refer to, which needs the document's identities. */
+function serializeText(context: SceneNodeToKiwiContext, node: SceneNode, nc: KiwiNodeChange): void {
+ context.serializeTextProps(
+ node,
+ nc,
+ context.graph,
+ context.fontDigestMap,
+ context.blobs,
+ context.glyphBlobMap
+ )
+ if (nc.textData) applyTextRunReferences(context, node, nc.textData)
+}
+
function applyNodeVisualProps(
context: SceneNodeToKiwiContext,
node: SceneNode,
@@ -849,16 +863,7 @@ function applyNodeVisualProps(
}))
}
- if (node.type === 'TEXT') {
- context.serializeTextProps(
- node,
- nc,
- context.graph,
- context.fontDigestMap,
- context.blobs,
- context.glyphBlobMap
- )
- }
+ if (node.type === 'TEXT') serializeText(context, node, nc)
if (node.type !== 'VECTOR') nc.frameMaskDisabled = !node.clipsContent
applySharedStyleProps(context, node, nc)
diff --git a/packages/fig/src/node-change/export/resolved-bindings.ts b/packages/fig/src/node-change/export/resolved-bindings.ts
index 2dbbc8e92..611620af6 100644
--- a/packages/fig/src/node-change/export/resolved-bindings.ts
+++ b/packages/fig/src/node-change/export/resolved-bindings.ts
@@ -1,6 +1,7 @@
import {
resolvedNumericBindings,
resolvedPaintBindings,
+ resolvedRunBindings,
resolvedValueBindings,
type SceneGraph,
type SceneNode
@@ -17,7 +18,8 @@ export function nodeWithResolvedBindings(graph: SceneGraph, node: SceneNode): Sc
const changes = {
...resolvedNumericBindings(graph, node, 'default'),
...resolvedPaintBindings(graph, node, 'default'),
- ...resolvedValueBindings(graph, node, 'default')
+ ...resolvedValueBindings(graph, node, 'default'),
+ ...resolvedRunBindings(graph, node, 'default')
}
return Object.keys(changes).length > 0 ? { ...node, ...changes } : node
}
diff --git a/packages/fig/src/node-change/style/refs.ts b/packages/fig/src/node-change/style/refs.ts
index 2378a6f01..e10143634 100644
--- a/packages/fig/src/node-change/style/refs.ts
+++ b/packages/fig/src/node-change/style/refs.ts
@@ -1,5 +1,5 @@
-import type { NodeChange, StyleReference } from '@open-pencil/kiwi/fig/codec'
-import { guidToString } from '@open-pencil/kiwi/fig/guid'
+import type { GUID, NodeChange, StyleReference } from '@open-pencil/kiwi/fig/codec'
+import { guidToString, isUnsetGuid } from '@open-pencil/kiwi/fig/guid'
const TEXT_STYLE_FIELDS = [
'fontSize',
@@ -87,3 +87,12 @@ export function applyStyleRefsToFields(
applyEffectAndGridStyleRefs(changeMap, fields, assetRefs)
applyTextStyleRef(changeMap, fields, assetRefs)
}
+
+/** A style reference's ID, or `null` for none and for the unset GUID, which clears one. */
+export function styleRefId(value: unknown): string | null {
+ if (!value || typeof value !== 'object' || !('guid' in value)) return null
+ const guid = value.guid
+ if (!guid || typeof guid !== 'object') return null
+ if (isUnsetGuid(guid as GUID)) return null
+ return guidToString(guid as GUID)
+}
diff --git a/packages/fig/src/node-change/style/runs.ts b/packages/fig/src/node-change/style/runs.ts
index f93bff557..30f0264de 100644
--- a/packages/fig/src/node-change/style/runs.ts
+++ b/packages/fig/src/node-change/style/runs.ts
@@ -1,11 +1,56 @@
-import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { isEmptyObject } from 'es-toolkit/predicate'
+
+import type { GUID, NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { guidToString, isUnsetGuid } from '@open-pencil/kiwi/fig/guid'
import { styleToWeight } from '@open-pencil/scene-graph'
-import type { CharacterStyleOverride, StyleRun } from '@open-pencil/scene-graph'
+import type {
+ CharacterStyleOverride,
+ HyperlinkTarget,
+ StyleRun,
+ TextCase
+} from '@open-pencil/scene-graph'
import { convertFontFeatures } from '../font/features'
import { convertFontVariations } from '../font/variations'
import { convertFills } from '../paint'
import { convertLetterSpacing, convertLineHeight, mapTextDecoration } from '../text/values'
+import { textRunVariableBindings } from '../variable/bindings'
+import { styleRefId } from './refs'
+
+const TEXT_CASES = new Set<unknown>(['ORIGINAL', 'UPPER', 'LOWER', 'TITLE'] satisfies TextCase[])
+
+/** A link Figma keeps on characters: to a URL, or to a node by its GUID. */
+export function importHyperlink(value: unknown): HyperlinkTarget | undefined {
+ if (!value || typeof value !== 'object') return undefined
+ const link = value as { url?: unknown; guid?: GUID }
+ if (typeof link.url === 'string' && link.url !== '') return { type: 'URL', value: link.url }
+ if (link.guid && !isUnsetGuid(link.guid)) return { type: 'NODE', value: guidToString(link.guid) }
+ return undefined
+}
+
+/**
+ * What a range refers to beyond its look: its case, link, styles, and bindings. A style the
+ * text uses itself is the range's own only when the range names another.
+ */
+function applyRangeReferences(
+ style: CharacterStyleOverride,
+ override: NodeChange,
+ text: Pick<NodeChange, 'styleIdForText' | 'styleIdForFill'>
+): void {
+ if (TEXT_CASES.has(override.textCase)) style.textCase = override.textCase as TextCase
+ const hyperlink = importHyperlink(override.hyperlink)
+ if (hyperlink) style.hyperlink = hyperlink
+ for (const [key, field] of [
+ ['textStyleId', 'styleIdForText'],
+ ['fillStyleId', 'styleIdForFill']
+ ] as const) {
+ if (override[field] === undefined) continue
+ const id = styleRefId(override[field])
+ if (id !== styleRefId(text[field])) style[key] = id
+ }
+ const boundVariables = textRunVariableBindings(override)
+ if (!isEmptyObject(boundVariables)) style.boundVariables = boundVariables
+}
function applyTextDecorationOverride(style: CharacterStyleOverride, override: NodeChange): void {
const deco = override.textDecoration
@@ -25,10 +70,8 @@ function applyTextDecorationOverride(style: CharacterStyleOverride, override: No
}
}
-function convertStyleOverride(
- override: NodeChange,
- fallbackFontSize: number | undefined
-): CharacterStyleOverride {
+function convertStyleOverride(override: NodeChange, text: NodeChange): CharacterStyleOverride {
+ const fallbackFontSize = text.fontSize
const style: CharacterStyleOverride = {}
if (override.fontName) {
style.fontFamily = override.fontName.family
@@ -55,18 +98,17 @@ function convertStyleOverride(
const fills = convertFills(override.fillPaints)
if (fills.length > 0) style.fills = fills
}
+ applyRangeReferences(style, override, text)
return style
}
-function buildStyleMap(
- table: NodeChange[],
- fallbackFontSize: number | undefined
-): Map<number, CharacterStyleOverride> {
+function buildStyleMap(table: NodeChange[], text: NodeChange): Map<number, CharacterStyleOverride> {
const styleMap = new Map<number, CharacterStyleOverride>()
for (const override of table) {
const id = override.styleID as number | undefined
- if (id === undefined) continue
- const style = convertStyleOverride(override, fallbackFontSize)
+ // Characters with style 0 have the text's own.
+ if (id === undefined || id === 0) continue
+ const style = convertStyleOverride(override, text)
if (Object.keys(style).length > 0) styleMap.set(id, style)
}
return styleMap
@@ -82,10 +124,8 @@ function collectStyleRuns(
for (let i = 1; i <= ids.length; i++) {
if (i === ids.length || ids[i] !== currentId) {
- if (currentId !== 0) {
- const style = styleMap.get(currentId)
- if (style) runs.push({ start, length: i - start, style })
- }
+ const style = styleMap.get(currentId)
+ if (style) runs.push({ start, length: i - start, style })
if (i < ids.length) {
currentId = ids[i]
start = i
@@ -95,15 +135,29 @@ function collectStyleRuns(
return runs
}
+/**
+ * A link the text keeps for itself goes on every character, apart from those that name their
+ * own: the model keeps links on ranges only.
+ */
+function withTextLink(
+ ids: number[],
+ length: number,
+ styleMap: Map<number, CharacterStyleOverride>,
+ link: HyperlinkTarget
+): number[] {
+ for (const style of styleMap.values()) style.hyperlink ??= link
+ styleMap.set(0, { hyperlink: link })
+ return Array.from({ length }, (_, index) => ids[index] ?? 0)
+}
+
export function importStyleRuns(nc: NodeChange): StyleRun[] {
const td = nc.textData
- if (!td?.characterStyleIDs || !td.styleOverrideTable) return []
-
- const ids = td.characterStyleIDs
- if (ids.length === 0 || td.styleOverrideTable.length === 0) return []
-
- const styleMap = buildStyleMap(td.styleOverrideTable, nc.fontSize)
- if (styleMap.size === 0) return []
-
+ const link = importHyperlink(nc.hyperlink)
+ const length = td?.characters.length ?? 0
+ const styleMap = buildStyleMap(td?.styleOverrideTable ?? [], nc)
+ const ids = link
+ ? withTextLink(td?.characterStyleIDs ?? [], length, styleMap, link)
+ : (td?.characterStyleIDs ?? [])
+ if (ids.length === 0 || styleMap.size === 0) return []
return collectStyleRuns(ids, styleMap)
}
diff --git a/packages/fig/src/node-change/text/data-export.ts b/packages/fig/src/node-change/text/data-export.ts
index 5fd143b24..327e8f58c 100644
--- a/packages/fig/src/node-change/text/data-export.ts
+++ b/packages/fig/src/node-change/text/data-export.ts
@@ -66,6 +66,7 @@ function textStyleOverrideToKiwi(
: { value: style.lineHeight, units: 'PIXELS' }
}
applyTextDecorationOverrideFields(override, style, fillToKiwiPaint)
+ if (style.textCase) override.textCase = style.textCase
if (style.fills && style.fills.length > 0) {
override.fillPaints = style.fills.map(fillToKiwiPaint)
}
@@ -95,6 +96,13 @@ function collectTextStyleOverrides(node: SceneNode): {
return { charIds, styleMap }
}
+/** The character styles written to the override table, each with its index there. */
+export function textStyleOverrides(
+ node: SceneNode
+): { id: number; style: CharacterStyleOverride }[] {
+ return [...collectTextStyleOverrides(node).styleMap.values()]
+}
+
/** The style each character is written with, as an index into its override table. */
export function characterStyleIDs(node: SceneNode): number[] {
return collectTextStyleOverrides(node).charIds
diff --git a/packages/fig/src/node-change/text/run-references.ts b/packages/fig/src/node-change/text/run-references.ts
new file mode 100644
index 000000000..dcbab3a14
--- /dev/null
+++ b/packages/fig/src/node-change/text/run-references.ts
@@ -0,0 +1,60 @@
+import type { GUID, NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { stringToGuid, UNSET_GUID } from '@open-pencil/kiwi/fig/guid'
+import type { CharacterStyleOverride, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+
+import { textRunVariableEntries } from '../variable/bindings'
+import { textStyleOverrides } from './data-export'
+
+/** The identities a document's records are written with. */
+export interface TextRunReferenceContext {
+ graph: SceneGraph
+ nodeIdToGuid?: Map<string, GUID>
+ varIdToGuid?: Map<string, GUID>
+}
+
+function applyRunReferences(
+ context: TextRunReferenceContext,
+ override: NodeChange,
+ style: CharacterStyleOverride
+): void {
+ const guid = (id: string) => context.nodeIdToGuid?.get(id) ?? stringToGuid(id)
+ const link = style.hyperlink
+ if (link)
+ override.hyperlink = link.type === 'URL' ? { url: link.value } : { guid: guid(link.value) }
+ // The unset GUID writes a range that leaves the text's style.
+ if (style.textStyleId !== undefined) {
+ override.styleIdForText = {
+ guid: style.textStyleId ? guid(style.textStyleId) : { ...UNSET_GUID }
+ }
+ }
+ if (style.fillStyleId !== undefined) {
+ override.styleIdForFill = {
+ guid: style.fillStyleId ? guid(style.fillStyleId) : { ...UNSET_GUID }
+ }
+ }
+ const entries = textRunVariableEntries(
+ style.boundVariables ?? {},
+ context.graph,
+ context.varIdToGuid
+ )
+ // Figma writes a range's bindings as parameters only.
+ if (entries.length > 0) override.parameterConsumptionMap = { entries }
+}
+
+/**
+ * Writes what each range of a text refers to into its style override: its link, the styles it
+ * uses in place of the text's, and its bindings, all of which name other records.
+ */
+export function applyTextRunReferences(
+ context: TextRunReferenceContext,
+ node: SceneNode,
+ textData: NonNullable<NodeChange['textData']>
+): void {
+ const table = textData.styleOverrideTable
+ if (!table) return
+ const styles = new Map(textStyleOverrides(node).map(({ id, style }) => [id, style]))
+ for (const override of table) {
+ const style = styles.get(override.styleID as number)
+ if (style) applyRunReferences(context, override, style)
+ }
+}
diff --git a/packages/fig/src/node-change/variable/bindings.ts b/packages/fig/src/node-change/variable/bindings.ts
index 0a29a607c..33c1a59ed 100644
--- a/packages/fig/src/node-change/variable/bindings.ts
+++ b/packages/fig/src/node-change/variable/bindings.ts
@@ -1,11 +1,14 @@
import { effectiveFigmaRawNodeFields } from '#fig/source-metadata'
+import { invert } from 'es-toolkit/object'
import type { VariableConsumptionEntry, GUID } from '@open-pencil/kiwi/fig/codec'
import { guidToString, stringToGuid } from '@open-pencil/kiwi/fig/guid'
import {
isNumericVariableBindingField,
type SceneNode,
- type SceneGraph
+ type SceneGraph,
+ type TextBindableField,
+ type TextBoundVariables
} from '@open-pencil/scene-graph'
import { cloneRecord } from '../clone'
@@ -52,7 +55,7 @@ export const VARIABLE_BINDING_FIELDS_INVERSE: Record<string, string> = Object.fr
Object.entries(VARIABLE_BINDING_FIELDS).map(([field, kiwiField]) => [kiwiField, field])
)
-interface VariableConsumptionSource extends Record<string, unknown> {
+export interface VariableConsumptionSource extends Record<string, unknown> {
variableConsumptionMap?: { entries?: VariableConsumptionEntry[] }
parameterConsumptionMap?: unknown
}
@@ -115,6 +118,55 @@ export function variableBindingEntry(
): VariableConsumptionEntry | undefined {
const variableField = VARIABLE_BINDING_FIELDS[field]
if (!variableField) return undefined
+ return consumptionEntry(variableField, variableId, graph, ids, multiplier, expression)
+}
+
+/** Kiwi's field for each text field a range of characters binds, where Kiwi has one. */
+export const TEXT_RUN_BINDING_FIELDS = {
+ fontFamily: 'FONT_FAMILY',
+ fontStyle: 'FONT_STYLE',
+ fontSize: 'FONT_SIZE',
+ letterSpacing: 'LETTER_SPACING',
+ lineHeight: 'LINE_HEIGHT',
+ paragraphSpacing: 'PARAGRAPH_SPACING',
+ paragraphIndent: 'PARAGRAPH_INDENT'
+} as const satisfies Partial<Record<TextBindableField, string>>
+
+const TEXT_RUN_BINDING_FIELDS_INVERSE: Partial<Record<string, TextBindableField>> =
+ invert(TEXT_RUN_BINDING_FIELDS)
+
+/** The entries a range of characters' bindings are written with, in its style override. */
+export function textRunVariableEntries(
+ bound: TextBoundVariables,
+ graph: SceneGraph,
+ ids?: Map<string, GUID>
+): VariableConsumptionEntry[] {
+ return Object.entries(bound).flatMap(([field, variableId]) => {
+ const variableField = (TEXT_RUN_BINDING_FIELDS as Partial<Record<string, string>>)[field]
+ if (!variableField || !variableId || !graph.variables.has(variableId)) return []
+ return [consumptionEntry(variableField, variableId, graph, ids)]
+ })
+}
+
+/** The text fields a style override binds, by variable ID. */
+export function textRunVariableBindings(override: VariableConsumptionSource): TextBoundVariables {
+ const bound: TextBoundVariables = {}
+ for (const entry of variableConsumptionEntries(override)) {
+ const field = entry.variableField && TEXT_RUN_BINDING_FIELDS_INVERSE[entry.variableField]
+ const guid = field ? linearVariableExpression(entry.variableData)?.reference?.guid : undefined
+ if (field && guid) bound[field] = guidToString(guid)
+ }
+ return bound
+}
+
+function consumptionEntry(
+ variableField: string,
+ variableId: string | undefined,
+ graph: SceneGraph,
+ ids?: Map<string, GUID>,
+ multiplier = 1,
+ expression = false
+): VariableConsumptionEntry {
if (!variableId) return { variableField }
const variable = graph.variables.get(variableId)
if (!variable) throw new Error(`Missing bound variable ${variableId}`)
diff --git a/packages/fig/tests/document/bindings/references.test.ts b/packages/fig/tests/document/bindings/references.test.ts
index bcdf46843..4a024105a 100644
--- a/packages/fig/tests/document/bindings/references.test.ts
+++ b/packages/fig/tests/document/bindings/references.test.ts
@@ -149,3 +149,43 @@ test('a record normalized on its own resolves as the document pass resolves it',
expect(entries[0]?.variableData?.value?.alias).not.toHaveProperty('guid')
expect(entries[1]?.variableData?.value?.alias).toHaveProperty('guid', guid(9))
})
+
+test('ranges of text resolve the variables and styles they name by library key', () => {
+ // A copy from Figma names a range's variable and style by key, as it names a layer's.
+ const [, , text] = resolveDocumentBindingReferences(
+ [
+ { guid: guid(1), type: 'VARIABLE', key: 'size', version: 'v1' },
+ { guid: guid(2), type: 'TEXT', styleType: 'TEXT', key: 'heading', version: 'v1' },
+ {
+ guid: guid(3),
+ type: 'TEXT',
+ textData: {
+ characters: 'bound',
+ styleOverrideTable: [
+ {
+ styleID: 1,
+ styleIdForText: { assetRef: { key: 'heading', version: 'v1' } },
+ parameterConsumptionMap: {
+ entries: [
+ {
+ variableField: 'FONT_SIZE',
+ variableData: {
+ dataType: 'ALIAS',
+ value: { alias: { assetRef: { key: 'size', version: 'v1' } } }
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+ } as NodeChange
+ ],
+ () => undefined
+ )
+ const [override] = text.textData?.styleOverrideTable ?? []
+ expect(override.styleIdForText?.guid).toEqual(guid(2))
+ expect(override.parameterConsumptionMap?.entries?.[0].variableData?.value?.alias?.guid).toEqual(
+ guid(1)
+ )
+})
diff --git a/packages/fig/tests/node-change/style/runs.test.ts b/packages/fig/tests/node-change/style/runs.test.ts
new file mode 100644
index 000000000..44c5c144a
--- /dev/null
+++ b/packages/fig/tests/node-change/style/runs.test.ts
@@ -0,0 +1,146 @@
+import { describe, expect, test } from 'bun:test'
+
+import { sceneNodeToKiwi } from '#fig/node-change/index'
+import { importStyleRuns } from '#fig/node-change/style/runs'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { UNSET_GUID } from '@open-pencil/kiwi/fig/guid'
+import { SceneGraph, type StyleRun } from '@open-pencil/scene-graph'
+
+// Field names and shapes from the Kiwi schema (`packages/kiwi/src/fig/schema/fig.kiwi`): a style
+// override is a NodeChange, which holds `textCase`, `hyperlink`, `styleIdForText`,
+// `styleIdForFill`, and variable consumption entries the way a layer does.
+const SIZE_ALIAS = {
+ variableField: 'FONT_SIZE',
+ variableData: {
+ dataType: 'ALIAS',
+ resolvedDataType: 'FLOAT',
+ value: { alias: { guid: { sessionID: 7, localID: 1 } } }
+ }
+}
+
+function textChange(overrides: NodeChange[], ids: number[], fields: NodeChange = {}): NodeChange {
+ return {
+ type: 'TEXT',
+ fontSize: 12,
+ textData: { characters: 'Hello world', characterStyleIDs: ids, styleOverrideTable: overrides },
+ ...fields
+ }
+}
+
+describe('character ranges in .fig style overrides', () => {
+ test('read case, links, styles, and bindings from the overrides', () => {
+ const runs = importStyleRuns(
+ textChange(
+ [
+ {
+ styleID: 1,
+ textCase: 'UPPER',
+ hyperlink: { url: 'https://openpencil.dev' },
+ styleIdForText: { guid: { sessionID: 1, localID: 20 } },
+ parameterConsumptionMap: { entries: [SIZE_ALIAS] }
+ },
+ {
+ styleID: 2,
+ hyperlink: { guid: { sessionID: 3, localID: 4 } },
+ styleIdForFill: { guid: { ...UNSET_GUID } },
+ textCase: 'SMALL_CAPS'
+ }
+ ],
+ [1, 1, 1, 1, 1, 0, 2, 2],
+ { styleIdForFill: { guid: { sessionID: 1, localID: 30 } } }
+ )
+ )
+ expect(runs).toEqual([
+ {
+ start: 0,
+ length: 5,
+ style: {
+ textCase: 'UPPER',
+ hyperlink: { type: 'URL', value: 'https://openpencil.dev' },
+ textStyleId: '1:20',
+ boundVariables: { fontSize: '7:1' }
+ }
+ },
+ {
+ start: 6,
+ length: 2,
+ style: { hyperlink: { type: 'NODE', value: '3:4' }, fillStyleId: null }
+ }
+ ])
+ })
+
+ test('give a link the text keeps for itself to every character', () => {
+ const runs = importStyleRuns(
+ textChange([{ styleID: 1, fontSize: 20 }], [1, 1], { hyperlink: { url: 'https://a.b' } })
+ )
+ const link = { type: 'URL' as const, value: 'https://a.b' }
+ expect(runs).toEqual([
+ { start: 0, length: 2, style: { fontSize: 20, hyperlink: link } },
+ { start: 2, length: 9, style: { hyperlink: link } }
+ ])
+ })
+
+ test('write them back as Figma reads them', () => {
+ const graph = new SceneGraph()
+ const collection = graph.createCollection('Type')
+ const size = graph.createVariable('size', 'FLOAT', collection.id, 20)
+ const styleRuns: StyleRun[] = [
+ {
+ start: 0,
+ length: 5,
+ style: {
+ textCase: 'TITLE',
+ hyperlink: { type: 'URL', value: 'https://openpencil.dev' },
+ textStyleId: '1:20',
+ fillStyleId: null,
+ boundVariables: { fontSize: size.id }
+ }
+ }
+ ]
+ const node = graph.createNode('TEXT', graph.getPages()[0].id, {
+ text: 'Hello world',
+ fillStyleId: '1:30',
+ styleRuns
+ })
+ const varIdToGuid = new Map([[size.id, { sessionID: 7, localID: 1 }]])
+ const [change] = sceneNodeToKiwi(
+ node,
+ { sessionID: 1, localID: 1 },
+ 0,
+ { value: 2 },
+ graph,
+ [],
+ {
+ varIdToGuid
+ }
+ )
+ const [override] = change.textData?.styleOverrideTable ?? []
+ expect(override).toMatchObject({
+ styleID: 1,
+ textCase: 'TITLE',
+ hyperlink: { url: 'https://openpencil.dev' },
+ styleIdForText: { guid: { sessionID: 1, localID: 20 } },
+ styleIdForFill: { guid: UNSET_GUID },
+ parameterConsumptionMap: {
+ entries: [
+ {
+ variableField: 'FONT_SIZE',
+ variableData: {
+ dataType: 'ALIAS',
+ value: { alias: { guid: { sessionID: 7, localID: 1 } } }
+ }
+ }
+ ]
+ }
+ })
+ // The binding is written with the value it resolves to, which the range then holds.
+ const [run] = importStyleRuns({ ...change, fontSize: 12 })
+ expect(run).toMatchObject({ start: 0, length: 5 })
+ expect(run.style).toMatchObject({
+ ...styleRuns[0].style,
+ fontSize: 20,
+ boundVariables: { fontSize: '7:1' }
+ })
+ })
+})
diff --git a/packages/scene-graph/src/copy.ts b/packages/scene-graph/src/copy.ts
index 08207bcae..5d358ee78 100644
--- a/packages/scene-graph/src/copy.ts
+++ b/packages/scene-graph/src/copy.ts
@@ -56,7 +56,7 @@ export function copyEffect(e: Effect): Effect {
}
export function copyStyleRun(r: StyleRun): StyleRun {
- return {
+ const copy: StyleRun = {
...r,
style: {
...r.style,
@@ -70,6 +70,9 @@ export function copyStyleRun(r: StyleRun): StyleRun {
fontFeatures: r.style.fontFeatures ? r.style.fontFeatures.map((v) => ({ ...v })) : undefined
}
}
+ if (r.style.hyperlink) copy.style.hyperlink = { ...r.style.hyperlink }
+ if (r.style.boundVariables) copy.style.boundVariables = { ...r.style.boundVariables }
+ return copy
}
// --- Array copy functions ---
diff --git a/packages/scene-graph/src/shared-styles.ts b/packages/scene-graph/src/shared-styles.ts
index b32e151b2..5a98e87f9 100644
--- a/packages/scene-graph/src/shared-styles.ts
+++ b/packages/scene-graph/src/shared-styles.ts
@@ -16,7 +16,8 @@ const STYLE_TYPES = {
grid: 'GRID'
} as const satisfies Record<SharedStyleKind, SharedStyleType>
-const TEXT_STYLE_KEYS = new Set<keyof SceneNode>([
+/** The fields a text style gives what uses it; changing one leaves the style. */
+export const SHARED_TEXT_STYLE_FIELDS = [
'fontFamily',
'fontWeight',
'italic',
@@ -26,7 +27,9 @@ const TEXT_STYLE_KEYS = new Set<keyof SceneNode>([
'textDecoration',
'textCase',
'fontFeatures'
-])
+] as const satisfies readonly (keyof SceneNode)[]
+
+const TEXT_STYLE_KEYS = new Set<keyof SceneNode>(SHARED_TEXT_STYLE_FIELDS)
export function sharedStyleRefKey(kind: SharedStyleKind): (typeof STYLE_REF_KEYS)[SharedStyleKind] {
return STYLE_REF_KEYS[kind]
diff --git a/packages/scene-graph/src/text/index.ts b/packages/scene-graph/src/text/index.ts
index de28f35ca..474dd5a62 100644
--- a/packages/scene-graph/src/text/index.ts
+++ b/packages/scene-graph/src/text/index.ts
@@ -1,2 +1,3 @@
export * from './lists'
export * from './paragraphs'
+export * from './references'
diff --git a/packages/scene-graph/src/text/references.ts b/packages/scene-graph/src/text/references.ts
new file mode 100644
index 000000000..9bfe9b195
--- /dev/null
+++ b/packages/scene-graph/src/text/references.ts
@@ -0,0 +1,50 @@
+import { mapValues } from 'es-toolkit/object'
+
+import type { StyleRun } from '../types'
+
+/** What a text's runs refer to outside the text: the variables they bind and the styles they use. */
+export interface StyleRunReferences {
+ variables: string[]
+ styles: string[]
+}
+
+/** The variables and styles a text's runs refer to, which copies and transfers carry with it. */
+export function styleRunReferences(runs: readonly StyleRun[]): StyleRunReferences {
+ const variables = new Set<string>()
+ const styles = new Set<string>()
+ for (const { style } of runs) {
+ for (const id of Object.values(style.boundVariables ?? {})) if (id) variables.add(id)
+ if (style.textStyleId) styles.add(style.textStyleId)
+ if (style.fillStyleId) styles.add(style.fillStyleId)
+ }
+ return { variables: [...variables], styles: [...styles] }
+}
+
+/**
+ * Runs whose variables, styles, and linked layers are renamed, as a copy into another document
+ * renames them. Layers are renamed only when given, since a link may name a layer left behind.
+ */
+export function remapStyleRunReferences(
+ runs: readonly StyleRun[],
+ rename: {
+ variable: (id: string) => string
+ style: (id: string) => string
+ node?: (id: string) => string
+ }
+): StyleRun[] {
+ return runs.map((run) => {
+ const { boundVariables, textStyleId, fillStyleId, hyperlink } = run.style
+ const linksLayer = hyperlink?.type === 'NODE' && rename.node !== undefined
+ if (!boundVariables && !textStyleId && !fillStyleId && !linksLayer) return run
+ const style = { ...run.style }
+ if (hyperlink?.type === 'NODE' && rename.node) {
+ style.hyperlink = { type: 'NODE', value: rename.node(hyperlink.value) }
+ }
+ if (boundVariables) {
+ style.boundVariables = mapValues(boundVariables, (id) => (id ? rename.variable(id) : id))
+ }
+ if (textStyleId) style.textStyleId = rename.style(textStyleId)
+ if (fillStyleId) style.fillStyleId = rename.style(fillStyleId)
+ return { ...run, style }
+ })
+}
diff --git a/packages/scene-graph/src/transfer/nodes.ts b/packages/scene-graph/src/transfer/nodes.ts
index 5c4844d72..f4d4858e1 100644
--- a/packages/scene-graph/src/transfer/nodes.ts
+++ b/packages/scene-graph/src/transfer/nodes.ts
@@ -1,13 +1,17 @@
import { cloneNodeProps } from '../copy'
import { remapInstanceOverrideState } from '../instance-overrides'
+import { remapStyleRunReferences, styleRunReferences } from '../text/references'
import type { ComponentPropertyType, SceneNode } from '../types'
import { requireTransferReference as required } from './references'
import type { VariableTransferReferences } from './variables'
export function semanticTransferReferences(node: SceneNode): string[] {
+ const runs = styleRunReferences(node.styleRuns)
return [
...(node.componentId ? [node.componentId] : []),
...Object.values(node.boundVariables),
+ ...runs.variables,
+ ...runs.styles,
...[
node.fillStyleId,
node.strokeStyleId,
@@ -89,6 +93,14 @@ export function prepareNodeTransfer(
] as const) {
result[field] = source[field] ? style(source[field]) : null
}
+ if (result.styleRuns) {
+ // A link to a layer the transfer leaves behind keeps naming it.
+ result.styleRuns = remapStyleRunReferences(result.styleRuns, {
+ variable,
+ style,
+ node: (id) => refs.nodes.get(id) ?? id
+ })
+ }
for (const paths of [result.fillGeometry, result.strokeGeometry]) {
for (const path of paths ?? []) if (path.fillStyleId) path.fillStyleId = style(path.fillStyleId)
}
diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.ts
index df8e60856..ece385196 100644
--- a/packages/scene-graph/src/types.ts
+++ b/packages/scene-graph/src/types.ts
@@ -270,6 +270,29 @@ export interface FontFeature {
enabled: boolean
}
+/** Where a stretch of text links to, as Figma's `HyperlinkTarget`: a URL, or a node by its ID. */
+export interface HyperlinkTarget {
+ type: 'URL' | 'NODE'
+ value: string
+}
+
+/** The text fields a range of characters can bind to a variable, as Figma lists them. */
+export const TEXT_BINDABLE_FIELDS = [
+ 'fontFamily',
+ 'fontSize',
+ 'fontStyle',
+ 'fontWeight',
+ 'letterSpacing',
+ 'lineHeight',
+ 'paragraphSpacing',
+ 'paragraphIndent'
+] as const
+
+export type TextBindableField = (typeof TEXT_BINDABLE_FIELDS)[number]
+
+/** Variable IDs bound to text fields, by field. */
+export type TextBoundVariables = Partial<Record<TextBindableField, string>>
+
export interface CharacterStyleOverride {
fontWeight?: number
italic?: boolean
@@ -287,6 +310,15 @@ export interface CharacterStyleOverride {
fontVariations?: FontVariation[]
fontFeatures?: FontFeature[]
textLanguage?: string | null
+ textCase?: TextCase
+ /** A link over the characters; `null`, like leaving it out, links nowhere. */
+ hyperlink?: HyperlinkTarget | null
+ /** The text style the characters use in place of the text's own; `null` uses none. */
+ textStyleId?: string | null
+ /** The fill style the characters use in place of the text's own; `null` uses none. */
+ fillStyleId?: string | null
+ /** The characters' text field bindings, in place of the text's own. */
+ boundVariables?: TextBoundVariables
}
export interface StyleRun {
diff --git a/packages/scene-graph/src/variables/bindings.ts b/packages/scene-graph/src/variables/bindings.ts
index 8de633e40..f82ef6d41 100644
--- a/packages/scene-graph/src/variables/bindings.ts
+++ b/packages/scene-graph/src/variables/bindings.ts
@@ -2,7 +2,7 @@ import { copyFills, copyStrokes } from '../copy'
import type { SceneGraph } from '../index'
import { hasInstanceOverride } from '../instances'
import type { Color } from '../primitives'
-import type { Fill, SceneNode, Stroke } from '../types'
+import type { Fill, SceneNode, Stroke, StyleRun } from '../types'
import type { VariableModeFallback } from '../variables'
import { NUMERIC_FIELDS, isNumericVariableBindingField } from './fields'
export { isNumericVariableBindingField } from './fields'
@@ -82,6 +82,43 @@ export function resolvedValueBindings(
return updates
}
+/** Fields of a range of characters a bound number gives its value; the rest need fonts loaded. */
+const NUMERIC_RUN_FIELDS = ['fontSize', 'fontWeight', 'letterSpacing', 'lineHeight'] as const
+
+/**
+ * The runs a text's character bindings resolve to in its mode, when a bound number differs from
+ * what its characters hold. Bound font families and styles are left as stored, as the text's own.
+ */
+export function resolvedRunBindings(
+ graph: SceneGraph,
+ node: SceneNode,
+ fallback: VariableModeFallback = 'active'
+): Pick<Partial<SceneNode>, 'styleRuns'> {
+ const styleRuns = node.styleRuns.map((run): StyleRun => {
+ const bound = run.style.boundVariables
+ if (!bound) return run
+ let style = run.style
+ for (const field of NUMERIC_RUN_FIELDS) {
+ const variableId = bound[field]
+ if (!variableId) continue
+ const value = graph.resolveNumberVariableForNode(node.id, variableId, fallback)
+ if (value === undefined || !Number.isFinite(value) || style[field] === value) continue
+ style = { ...style, [field]: value }
+ }
+ return style === run.style ? run : { ...run, style }
+ })
+ const changed = styleRuns.some((run, index) => run !== node.styleRuns[index])
+ return changed ? { styleRuns } : {}
+}
+
+/** The variables a node binds, its own and its characters'. */
+function boundVariableIds(node: SceneNode): string[] {
+ return [
+ ...Object.values(node.boundVariables),
+ ...node.styleRuns.flatMap((run) => Object.values(run.style.boundVariables ?? {}))
+ ].filter((id): id is string => typeof id === 'string')
+}
+
/**
* A bound paint takes its whole color from the variable, alpha included, the way Figma stores
* it: the variable's RGB at full alpha, and its alpha as the paint's opacity.
@@ -162,7 +199,7 @@ function scopedNodes(graph: SceneGraph, scope: BindingScope | undefined): Iterab
if ('subtrees' in scope) return subtreeNodes(graph, scope.subtrees)
const variables = variablesResolvingThrough(graph, scope.variables)
return [...graph.getAllNodes()].filter((node) =>
- Object.values(node.boundVariables).some((id) => variables.has(id))
+ boundVariableIds(node).some((id) => variables.has(id))
)
}
@@ -176,7 +213,8 @@ export function reconcileVariableBindings(graph: SceneGraph, scope?: BindingScop
for (const node of scopedNodes(graph, scope)) {
const updates = {
...resolvedNumericBindings(graph, node),
- ...resolvedValueBindings(graph, node)
+ ...resolvedValueBindings(graph, node),
+ ...resolvedRunBindings(graph, node)
}
if (Object.keys(updates).length === 0) continue
graph.updateNode(node.id, updates)
diff --git a/packages/scene-graph/tests/text/references.test.ts b/packages/scene-graph/tests/text/references.test.ts
new file mode 100644
index 000000000..52ac36d3e
--- /dev/null
+++ b/packages/scene-graph/tests/text/references.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ remapStyleRunReferences,
+ styleRunReferences,
+ type StyleRun
+} from '@open-pencil/scene-graph'
+
+const RUNS: StyleRun[] = [
+ { start: 0, length: 2, style: { boundVariables: { fontSize: 'v1' }, textStyleId: 's1' } },
+ { start: 2, length: 2, style: { fillStyleId: 's2', hyperlink: { type: 'URL', value: 'x' } } },
+ { start: 4, length: 2, style: { fontSize: 20 } }
+]
+
+describe('style run references', () => {
+ test('list the variables and styles characters use', () => {
+ expect(styleRunReferences(RUNS)).toEqual({ variables: ['v1'], styles: ['s1', 's2'] })
+ })
+
+ test('rename them, keeping runs without any as they are', () => {
+ const renamed = remapStyleRunReferences(RUNS, {
+ variable: (id) => `new-${id}`,
+ style: (id) => `new-${id}`
+ })
+ expect(renamed.map((run) => run.style)).toEqual([
+ { boundVariables: { fontSize: 'new-v1' }, textStyleId: 'new-s1' },
+ { fillStyleId: 'new-s2', hyperlink: { type: 'URL', value: 'x' } },
+ { fontSize: 20 }
+ ])
+ expect(renamed[2]).toBe(RUNS[2])
+ })
+
+ test('rename linked layers only when given a renaming for them', () => {
+ const linked: StyleRun[] = [
+ { start: 0, length: 4, style: { hyperlink: { type: 'NODE', value: 'frame' } } }
+ ]
+ const rename = { variable: (id: string) => id, style: (id: string) => id }
+ expect(remapStyleRunReferences(linked, rename)[0]).toBe(linked[0])
+ expect(
+ remapStyleRunReferences(linked, { ...rename, node: (id) => `new-${id}` })[0].style
+ ).toEqual({ hyperlink: { type: 'NODE', value: 'new-frame' } })
+ })
+})
diff --git a/skills/open-pencil/SKILL.md b/skills/open-pencil/SKILL.md
index ec996bd33..123f2bf74 100644
--- a/skills/open-pencil/SKILL.md
+++ b/skills/open-pencil/SKILL.md
@@ -171,7 +171,7 @@ openpencil eval design.fig -w -c '
'
```
-Text styles follow Figma's per-character model: `getStyledTextSegments(fields)` reads runs, `getRange…`/`setRange…` read and set font, size, fills, letter spacing, line height, 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.
+Text styles follow Figma's per-character model: `getStyledTextSegments(fields)` reads runs, `getRange…`/`setRange…` read and set font, size, fills, letter spacing, line height, decorations, text case, hyperlinks, text and fill style IDs, and bound variables for `[start, end)`, and a text's `fontSize`, `fontName`, `fills`, and similar read `figma.mixed` while characters differ. Check for it before using the value.
Next to `figma`, scripts get `openpencil`: what OpenPencil adds to the Figma API, in its style. A main component can behave as a Reka UI control, by its own property and slot names:
diff --git a/skills/open-pencil/references/design-authoring.md b/skills/open-pencil/references/design-authoring.md
index 7b52ea215..096ba6daf 100644
--- a/skills/open-pencil/references/design-authoring.md
+++ b/skills/open-pencil/references/design-authoring.md
@@ -25,7 +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`. Decorations take CSS's names and values: `textDecorationStyle` (`solid`, `dotted`, `wavy`), `textDecorationColor` (`currentColor` follows the text), `textDecorationThickness` and `textUnderlineOffset` (pixels or `auto`), and `textDecorationSkipInk`. `lineHeight="auto"` follows the font, and `fills={[]}` paints no text. Verify fonts actually load before judging dimensions; do not assume every font is available.
-- `Span` styles some characters of a `Text` with `Text`'s own prop names: `size`, `font`, `weight`, `italic`, `color`, `fills`, `lineHeight`, `letterSpacing`, `textDecoration`, and the decoration details. Spans nest; the inner one wins. `Paragraph` writes one paragraph: `list="ordered"` or `list="unordered"` makes it a list item nested at `level` 1–5, and `spacing`, `listSpacing`, and `indent` override the `Text`'s `paragraphSpacing`, `listSpacing`, and `paragraphIndent` for it; `hangingList` on the `Text` hangs list markers outside the text box. A `Text` holds only `Paragraph`s or none; without them, a line break in its text still starts a paragraph.
+- `Span` styles some characters of a `Text` with `Text`'s own prop names: `size`, `font`, `weight`, `italic`, `color`, `fills`, `lineHeight`, `letterSpacing`, `textDecoration`, the decoration details, and `textCase`. `href` links its characters to a URL without changing how they look. Spans nest; the inner one wins. `Paragraph` writes one paragraph: `list="ordered"` or `list="unordered"` makes it a list item nested at `level` 1–5, and `spacing`, `listSpacing`, and `indent` override the `Text`'s `paragraphSpacing`, `listSpacing`, and `paragraphIndent` for it; `hangingList` on the `Text` hangs list markers outside the text box. A `Text` holds only `Paragraph`s or none; without them, a line break in its text still starts a paragraph.
- `Icon` uses an Iconify name, size, and color. Prefer icons to emoji when reliable vector output is needed. Image fills belong on appropriate leaf shapes, not containers whose children must remain visible.
- Design JSX props are the portable authoring interface. Some CSS-style aliases are supported, but this is not a browser CSS engine; do not assume arbitrary HTML, classes, or styles work.
diff --git a/tests/e2e/canvas/text/lines-visual.spec.ts b/tests/e2e/canvas/text/lines-visual.spec.ts
new file mode 100644
index 000000000..7ce46e2ce
--- /dev/null
+++ b/tests/e2e/canvas/text/lines-visual.spec.ts
@@ -0,0 +1,77 @@
+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'
+
+const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')
+
+test('places lines of mixed sizes as Figma does', async () => {
+ await editor.page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('Missing editor')
+ const big = (start: number, length: number) => ({ start, length, style: { fontSize: 36 } })
+ const wrapping = 'Small words LARGE then wraps onto more lines'
+ const texts = [
+ { x: 40, y: 40, text: wrapping, styleRuns: [big(12, 5)] },
+ { x: 280, y: 40, text: wrapping, styleRuns: [big(12, 5)], textAlignHorizontal: 'CENTER' },
+ {
+ x: 520,
+ y: 40,
+ text: wrapping,
+ styleRuns: [big(12, 5)],
+ textAlignHorizontal: 'JUSTIFIED'
+ },
+ {
+ x: 40,
+ y: 220,
+ text: 'one\ntwo with a tall line\nthree',
+ styleRuns: [{ start: 4, length: 20, style: { lineHeight: 48 } }]
+ },
+ {
+ x: 280,
+ y: 220,
+ text: 'Small LARGE\nunder a fixed line height',
+ lineHeight: 24,
+ styleRuns: [big(6, 5)]
+ },
+ {
+ x: 520,
+ y: 220,
+ text: 'First item\nSecond BIG item wraps\nThird',
+ styleRuns: [big(18, 3)],
+ paragraphSpacing: 8,
+ textDecoration: 'UNDERLINE',
+ textParagraphs: [
+ { listType: 'UNORDERED', indentation: 1 },
+ { listType: 'UNORDERED', indentation: 1 },
+ { listType: 'UNORDERED', indentation: 1 }
+ ]
+ }
+ ] as const
+ for (const props of texts) {
+ store.graph.createNode('TEXT', store.state.currentPageId, {
+ width: 200,
+ height: 160,
+ fontFamily: 'Inter',
+ fontSize: 18,
+ lineHeight: null,
+ textAutoResize: 'HEIGHT',
+ ...props,
+ styleRuns: [...props.styleRuns],
+ textParagraphs: 'textParagraphs' in props ? [...props.textParagraphs] : []
+ })
+ }
+ store.requestRender()
+ })
+ await editor.page.waitForFunction(() => {
+ const store = window.openPencil?.getStore?.()
+ return (
+ store?.graph.getChildren(store.state.currentPageId).filter((node) => node.type === 'TEXT')
+ .length === 6
+ )
+ })
+ await editor.page.evaluate(
+ () =>
+ new Promise<void>((resolve) => {
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()))
+ })
+ )
+ expect(await editor.canvas.screenshotCanvasRegion()).toMatchSnapshot('text-lines.png')
+})
diff --git a/tests/e2e/canvas/text/lines-visual.spec.ts-snapshots/text-lines-openpencil-darwin.png b/tests/e2e/canvas/text/lines-visual.spec.ts-snapshots/text-lines-openpencil-darwin.png
new file mode 100644
index 000000000..a7e636b3d
Binary files /dev/null and b/tests/e2e/canvas/text/lines-visual.spec.ts-snapshots/text-lines-openpencil-darwin.png differ
diff --git a/tests/e2e/canvas/text/visual.spec.ts b/tests/e2e/canvas/text/visual.spec.ts
index 2f8e50051..684c10022 100644
--- a/tests/e2e/canvas/text/visual.spec.ts
+++ b/tests/e2e/canvas/text/visual.spec.ts
@@ -166,3 +166,58 @@ test('text decoration styles and OpenType features', async () => {
await editor.canvas.waitForRender()
await expectCanvas('text-decoration-styles-and-opentype-features')
})
+
+test('text case by character range', async () => {
+ await editor.page.evaluate(async () => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const pageId = store.state.currentPageId
+ const fills = [
+ {
+ type: 'SOLID' as const,
+ color: { r: 0.08, g: 0.1, b: 0.18, a: 1 },
+ visible: true,
+ opacity: 1
+ }
+ ]
+ const rows = [
+ {
+ text: 'upper words in a lower line',
+ styleRuns: [{ start: 0, length: 11, style: { textCase: 'UPPER' as const } }]
+ },
+ {
+ text: 'Title case midword stays put',
+ styleRuns: [
+ { start: 0, length: 10, style: { textCase: 'TITLE' as const } },
+ { start: 13, length: 6, style: { textCase: 'TITLE' as const } }
+ ]
+ },
+ {
+ text: 'ALL CAPS TEXT WITH A QUIET END',
+ textCase: 'UPPER' as const,
+ styleRuns: [{ start: 19, length: 11, style: { textCase: 'LOWER' as const } }]
+ }
+ ]
+ for (const [index, row] of rows.entries()) {
+ store.graph.createNode('TEXT', pageId, {
+ name: row.text,
+ x: 100,
+ y: 80 + index * 50,
+ width: 560,
+ height: 34,
+ text: row.text,
+ fontSize: 24,
+ fontWeight: 500,
+ textAutoResize: 'HEIGHT',
+ textCase: row.textCase ?? 'ORIGINAL',
+ styleRuns: row.styleRuns,
+ fills
+ })
+ }
+ store.clearSelection()
+ await store.loadFontsForNodes(store.graph.getPages().flatMap((page) => page.childIds))
+ store.requestRender()
+ })
+ await editor.canvas.waitForRender()
+ await expectCanvas('text-case-by-range')
+})
diff --git a/tests/e2e/canvas/text/visual.spec.ts-snapshots/text-case-by-range-openpencil-darwin.png b/tests/e2e/canvas/text/visual.spec.ts-snapshots/text-case-by-range-openpencil-darwin.png
new file mode 100644
index 000000000..b4a59cd19
Binary files /dev/null and b/tests/e2e/canvas/text/visual.spec.ts-snapshots/text-case-by-range-openpencil-darwin.png differ
diff --git a/tests/e2e/properties/typography-panel.spec.ts-snapshots/typography-groups-dark-openpencil-darwin.png b/tests/e2e/properties/typography-panel.spec.ts-snapshots/typography-groups-dark-openpencil-darwin.png
index a9e639756..e430814f9 100644
Binary files a/tests/e2e/properties/typography-panel.spec.ts-snapshots/typography-groups-dark-openpencil-darwin.png and b/tests/e2e/properties/typography-panel.spec.ts-snapshots/typography-groups-dark-openpencil-darwin.png differ
diff --git a/tests/e2e/properties/typography-panel.spec.ts-snapshots/typography-groups-light-openpencil-darwin.png b/tests/e2e/properties/typography-panel.spec.ts-snapshots/typography-groups-light-openpencil-darwin.png
index 064536d4a..d35c5988a 100644
Binary files a/tests/e2e/properties/typography-panel.spec.ts-snapshots/typography-groups-light-openpencil-darwin.png and b/tests/e2e/properties/typography-panel.spec.ts-snapshots/typography-groups-light-openpencil-darwin.png differ
diff --git a/tests/e2e/text/formatting.spec.ts-snapshots/typography-panel-openpencil-darwin.png b/tests/e2e/text/formatting.spec.ts-snapshots/typography-panel-openpencil-darwin.png
index a21542f01..88675c05f 100644
Binary files a/tests/e2e/text/formatting.spec.ts-snapshots/typography-panel-openpencil-darwin.png and b/tests/e2e/text/formatting.spec.ts-snapshots/typography-panel-openpencil-darwin.png differ
diff --git a/tests/engine/io/fig/import/legacy/text.test.ts b/tests/engine/io/fig/import/legacy/text.test.ts
index 6246dd4ca..33c6e9090 100644
--- a/tests/engine/io/fig/import/legacy/text.test.ts
+++ b/tests/engine/io/fig/import/legacy/text.test.ts
@@ -99,6 +99,33 @@ describe('fig-import: text properties', () => {
expect(n.lineHeight).toBe(16.94)
})
+ test('keeps a pixel line height shorter than the font, which Figma saves lines taller than', () => {
+ // Figma saves each line at the larger of its line height and its font's height.
+ const graph = materializeDocument([
+ doc(),
+ canvas(),
+ node('TEXT', 10, 1, {
+ textData: { characters: 'Tight\nlines' },
+ fontSize: 24,
+ lineHeight: { value: 10, units: 'PIXELS' },
+ derivedTextData: {
+ baselines: [
+ {
+ firstCharacter: 0,
+ endCharacter: 6,
+ position: { x: 0, y: 13.73 },
+ width: 60,
+ lineY: 0,
+ lineHeight: 29.05,
+ lineAscent: 23
+ }
+ ]
+ }
+ } as Partial<NodeChange>)
+ ]).graph
+ expect(graph.getChildren(graph.getPages()[0].id)[0]?.lineHeight).toBe(10)
+ })
+
test('reads line heights as Figma writes them: auto as 100 percent, a percent as a multiplier', () => {
// A 40px word on the first line: its height must not fix every line of an auto text.
const derivedTextData = {
@@ -128,8 +155,8 @@ describe('fig-import: text properties', () => {
text({ value: 1.5, units: 'RAW' }, 11)
]).graph
const [auto, raw] = graph.getChildren(graph.getPages()[0].id)
- expect(auto?.lineHeight).toBeNull()
- expect(raw?.lineHeight).toBe(36)
+ expect(auto.lineHeight).toBeNull()
+ expect(raw.lineHeight).toBe(36)
})
test('applies shared text style refs', () => {
@@ -163,6 +190,40 @@ describe('fig-import: text properties', () => {
expect(style).toMatchObject({ name: 'Body style', sharedStyleType: 'TEXT', internalOnly: true })
})
+ test('points ranges at the styles and layers imported with them', () => {
+ const graph = materializeDocument([
+ doc(),
+ canvas(),
+ node('TEXT', 20, 1, {
+ name: 'Heading style',
+ styleType: 'TEXT',
+ fontSize: 24,
+ fontName: { family: 'Inter', style: 'Regular' }
+ } as Partial<NodeChange>),
+ node('FRAME', 30, 1, { name: 'Target' } as Partial<NodeChange>),
+ node('TEXT', 10, 1, {
+ name: 'Linked',
+ fontSize: 16,
+ textData: {
+ characters: 'styled link',
+ characterStyleIDs: [1, 1, 1, 1, 1, 1, 0, 2, 2, 2, 2],
+ styleOverrideTable: [
+ { styleID: 1, styleIdForText: { guid: { sessionID: 1, localID: 20 } } },
+ { styleID: 2, hyperlink: { guid: { sessionID: 1, localID: 30 } } }
+ ]
+ }
+ } as Partial<NodeChange>)
+ ]).graph
+ const nodes = graph.getChildren(graph.getPages()[0].id)
+ const text = nodes.find((child) => child.name === 'Linked')
+ const target = nodes.find((child) => child.name === 'Target')
+ const style = [...graph.getAllNodes()].find((child) => child.name === 'Heading style')
+ expect(text?.styleRuns.map((run) => run.style)).toEqual([
+ expect.objectContaining({ textStyleId: style?.id }),
+ { hyperlink: { type: 'NODE', value: target?.id } }
+ ])
+ })
+
test('applies shared fill style refs', () => {
const graph = materializeDocument([
doc(),