Skip to content

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

feat(text): lay out bulleted and numbered lists as Figma does (#1036)

Danila Poyarkov8e8873b7a95a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2969394db..0b899282d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,7 @@
### Breaking changes
+- `SceneNode` from `@open-pencil/scene-graph` has `textParagraphs`, `listSpacing`, `paragraphSpacing`, `paragraphIndent`, and `hangingList`, so code that builds `SceneNode` objects itself must include them. `SkiaRenderer.buildParagraph` returns a `TextLayout`, which answers the `Paragraph` queries the renderer and text editor use for the whole text and draws with `draw(canvas, x, y)`, instead of a CanvasKit `Paragraph`.
- `AUTO_LAYOUT_BREAK_THRESHOLD` is removed from `@open-pencil/core/constants`: a layer dragged out of auto layout now leaves by how far its own edge is past the frame, not by a cursor margin.
- `SceneNode` from `@open-pencil/scene-graph` has `targetAspectRatio`, the size whose proportions a locked layer keeps, so code that builds `SceneNode` objects itself must include it.
- `useFlatReorderDrag` from `@open-pencil/vue` takes `operations`, which drops each target accepts, and `onCombine`, for dropping onto an item, and `FlatReorderInstruction` is now any list-item `Instruction`, so it can be `'combine'` when a list opts in; code that switches on its `operation` needs that case.
@@ -50,6 +51,7 @@
### Added
+- Bulleted and numbered lists in text, as in Figma: `.fig` files and the Figma clipboard keep each paragraph's list type, nesting, list and paragraph spacing, and first-line indent, and the text's hanging markers, and the canvas lays lists out as Figma does, with markers centred or ending a third of an em before the item, numbers counting 1, a, i as they nest, and wrapped lines hanging at the indent. Set a list's style, list and paragraph spacing, paragraph indent, and hanging markers in the Typography section, for the paragraphs being edited or the whole text; while editing, <kbd>⇧</kbd><kbd>⌘</kbd><kbd>8</kbd> and <kbd>⇧</kbd><kbd>⌘</kbd><kbd>7</kbd> make bulleted and numbered lists, <kbd>Tab</kbd> and <kbd>⇧</kbd><kbd>Tab</kbd> nest and unnest items, and text you type into a list continues it. Flattening or outlining text keeps its markers. Scripts read and set lists with `getRangeListOptions`, `setRangeListOptions`, `getRangeIndentation`, `setRangeIndentation`, `listSpacing`, `paragraphSpacing`, `paragraphIndent`, their `getRange` and `setRange` methods, and `hangingList`.
- Drag several layers along an auto layout row or column together, as in Figma: they move as one block in their order, wherever you grab them, and layers selected in different rows each move along their own row. A layer dragged along a flow takes the next slot once its leading edge reaches the next layer's centre, as Figma reorders, instead of once the cursor does.
- Move a layer in an auto layout row or column with the arrow keys, as in Figma: Right and Left move it one slot along a row, Down and Up along a column, Shift too, and the arrows across the flow do nothing. With several layers selected, each moves one slot and one at the end stays; a run of keys is one undo step.
- Lock a layer's aspect ratio with the button beside its width and height, as in Figma: typing either side changes the other, handles keep the ratio (<kbd>Ctrl</kbd> frees it for one drag, which then keeps the new size), a Fill layer in auto layout takes its other side from the ratio, and a constraint keeps it when exactly one axis follows the frame. The lock reads from and writes to `.fig` files and the clipboard, and the plugin API has `lockAspectRatio()`, `unlockAspectRatio()`, `targetAspectRatio`, and `constrainProportions`.
@@ -173,6 +175,9 @@
### Fixed
+- Dragging a number field in the properties panel moves its value in whole steps instead of fractions on high-density screens.
+- While text is being edited, its caret and selection follow a property dragged in the panel instead of catching up when the mouse is released.
+- Outline text, flatten, and boolean operations on text place glyphs where the canvas draws them; lines sat lower by about a quarter of the font size.
- Tailwind exports keep corner radius: Tailwind JSX and HTML with Tailwind classes write radius from Tailwind's radius scale, such as `rounded-xl` for 12px, instead of classes like `rounded-3` that Tailwind v4 does not generate, and other values as `rounded-[20px]`.
- ⌘Z right after arrow-key nudges undoes the nudges instead of the edit before them.
- <kbd>⇧</kbd>-dragging a corner handle follows the side the pointer stretched most relative to the layer's size, as Figma does, instead of the side it moved more pixels along.
@@ -323,6 +328,7 @@
### Performance
+- Selecting text and moving the caret while editing repaint only the selection instead of redrawing the whole canvas and properties panel, and text drawn from glyphs saved in a `.fig` file decodes each glyph once instead of on every redraw, so drag-selecting and dragging a property no longer stutter on pages with many text layers.
- Open large `.fig` files with a fraction of the memory: records stay in the file's bytes except for the few fields indexing needs, and are decoded whole when read, kept only for the pages being read and the components they use. Opening the Nuxt UI design kit takes 0.7 GB instead of 2.2 GB, and its first twelve pages 1.2 GB instead of 2.6 GB.
- Save an edited `.fig` file by rewriting only the layers that changed and copying the rest from the file it was opened from, as it is stored, without decoding it; in the browser that work runs off the main thread. Saving the 109 MB Preline UI kit after an edit takes about 3 seconds instead of over two minutes, and crash recovery no longer freezes Safari after the first edit to a large file. Editing a component also rewrites its instances on pages that were not opened yet.
- Open `.fig` design kits with less memory: layers inside instances hold their component layers' paints, glyphs, and other unchanged values instead of a copy each, about a third fewer objects and an eighth less memory per loaded page.
diff --git a/packages/core/AGENTS.md b/packages/core/AGENTS.md
index 87bea547f..df35fc654 100644
--- a/packages/core/AGENTS.md
+++ b/packages/core/AGENTS.md
@@ -78,7 +78,8 @@ Canvas is CanvasKit (Skia WASM) on a WebGL surface, not DOM.
- Bounded rendering caches share `packages/core/src/cache/resource.ts` for recency, count/weight accounting, and removal disposal. Domain adapters own keys, font/page/dependency invalidation, and sizing units; use non-touching `peek()` for FIFO or planning reads. Rejected insertions leave ownership with the caller.
- Keep weak memos, async request registries, pools, and dependency-owned picture/path maps on their distinct lifetime policies.
-- Paragraph construction is typed against `packages/core/src/canvas/text/paragraph-inputs.ts`; the same inputs drive preparation-cache invalidation. Add a mutation case when extending that contract. Drawing borrows native paragraphs; the renderer owns their bounded cache and destruction.
+- Paragraph construction is typed against `packages/core/src/canvas/text/paragraph/inputs.ts`; the same inputs drive preparation-cache invalidation. Add a mutation case when extending that contract. Drawing borrows native paragraphs; the renderer owns their bounded cache and destruction.
+- Text lays out through `buildParagraph` into a `TextLayout` (`packages/core/src/canvas/text/layout/`): one native paragraph for plain text, or one per paragraph with its list indent, marker, and spacing, since Skia has no hanging indent. Drawing, measurement, the text editor, saved glyphs (`shapeText`), and text outlines all read that layout rather than laying text out again (`packages/core/tests/canvas/text/lists.test.ts`).
### Geometry and overlays
diff --git a/packages/core/src/canvas/renderer.ts b/packages/core/src/canvas/renderer.ts
index 1f5dba919..035aa3644 100644
--- a/packages/core/src/canvas/renderer.ts
+++ b/packages/core/src/canvas/renderer.ts
@@ -39,8 +39,8 @@ import * as RenderPipeline from './renderer/pipeline'
import type { SceneBacking, SceneBackingBuild } from './renderer/retained-backing/types'
import * as RendererState from './renderer/state'
import * as RenderText from './text'
-import { createGlyphSilhouetteCache } from './text/derived'
-import { TextPreparationCache } from './text/preparation-cache'
+import { createDerivedGlyphPathCache, createGlyphSilhouetteCache } from './text/derived'
+import { TextPreparationCache } from './text/preparation/cache'
export type {
MeasurementMode,
PresenceCursor,
@@ -61,7 +61,6 @@ import type {
ImageFilter,
MaskFilter,
RuntimeEffect,
- Paragraph,
Image,
TextureSource
} from 'canvaskit-wasm'
@@ -147,6 +146,7 @@ export class SkiaRenderer {
strokeGeometryCache = new Map<string, Path[]>()
/** Path-text glyph silhouettes (stroke-and-union, font units) keyed by blob hash + relative weight. */
glyphSilhouetteCache = createGlyphSilhouetteCache()
+ derivedGlyphPathCache = createDerivedGlyphPathCache()
renderingSceneBacking = false
scenePicture: SkPicture | null = null
scenePictureVersion = -1
@@ -787,7 +787,7 @@ export class SkiaRenderer {
node: SceneNode,
color?: Float32Array,
opts?: RenderText.ParagraphBuildOptions
- ): Paragraph {
+ ): RenderText.TextLayout {
return RenderText.buildParagraph(this, node, color, opts)
}
diff --git a/packages/core/src/canvas/renderer/lifecycle.ts b/packages/core/src/canvas/renderer/lifecycle.ts
index 820b862ad..d6d15db76 100644
--- a/packages/core/src/canvas/renderer/lifecycle.ts
+++ b/packages/core/src/canvas/renderer/lifecycle.ts
@@ -24,6 +24,7 @@ function disposePathCaches(r: SkiaRenderer): void {
cache.clear()
}
r.glyphSilhouetteCache.clear()
+ r.derivedGlyphPathCache.clear()
}
/** Frees every live image `r`'s surface holds and forgets those an earlier surface held. */
diff --git a/packages/core/src/canvas/renderer/state.ts b/packages/core/src/canvas/renderer/state.ts
index 15909be98..8f4bc2851 100644
--- a/packages/core/src/canvas/renderer/state.ts
+++ b/packages/core/src/canvas/renderer/state.ts
@@ -1,7 +1,7 @@
import type { SceneNode } from '@open-pencil/scene-graph'
import type { SkiaRenderer } from '#core/canvas/renderer'
-import { changesShaping } from '#core/canvas/text/paragraph-inputs'
+import { changesShaping } from '#core/canvas/text/paragraph/inputs'
export function invalidateScenePicture(r: SkiaRenderer): void {
r.scenePicture?.delete()
diff --git a/packages/core/src/canvas/scene.ts b/packages/core/src/canvas/scene.ts
index 5bf53d5b8..29715e7f8 100644
--- a/packages/core/src/canvas/scene.ts
+++ b/packages/core/src/canvas/scene.ts
@@ -922,7 +922,7 @@ function drawPaintedText(r: SkiaRenderer, canvas: Canvas, node: SceneNode): bool
foregroundPaint: r.fillPaint
},
(paragraph) => {
- canvas.drawParagraph(paragraph, 0, textVerticalOffset(node, paragraph.getHeight()))
+ paragraph.draw(canvas, 0, textVerticalOffset(node, paragraph.getHeight()))
return true
}
)
@@ -997,7 +997,7 @@ export function renderText(r: SkiaRenderer, canvas: Canvas, node: SceneNode, fil
if (r.fontsLoaded && r.fontProvider) {
withTextParagraph(r, node, r.fillPaint.getColor(), { halfLeading: true }, (paragraph) => {
const paragraphY = textVerticalOffset(node, paragraph.getHeight())
- canvas.drawParagraph(paragraph, 0, paragraphY)
+ paragraph.draw(canvas, 0, paragraphY)
})
} else if (r.textFont) {
const fontSize = node.fontSize || r.DEFAULT_FONT_SIZE
diff --git a/packages/core/src/canvas/text/derived.ts b/packages/core/src/canvas/text/derived.ts
index 5788cb61b..777a801c9 100644
--- a/packages/core/src/canvas/text/derived.ts
+++ b/packages/core/src/canvas/text/derived.ts
@@ -1,14 +1,18 @@
import type { Canvas, Paint, Path } from 'canvaskit-wasm'
import { fromUint8Array } from 'js-base64'
-import type {
- Color,
- Fill,
- DerivedTextGlyph,
- SceneNode,
- Stroke,
- StyleRun,
- TextDecorationStyle
+import {
+ hasTextList,
+ textListItems,
+ textParagraphRanges,
+ type Color,
+ type Fill,
+ type DerivedTextGlyph,
+ type SceneNode,
+ type Stroke,
+ type StyleRun,
+ type TextDecorationStyle,
+ type TextParagraphRange
} from '@open-pencil/scene-graph'
import { ResourceCache } from '#core/cache/resource'
@@ -16,6 +20,25 @@ import type { SkiaRenderer } from '#core/canvas/renderer'
import { geometryBlobToPath } from '#core/vector'
const MAX_GLYPH_SILHOUETTES = 512
+/** Saved glyphs a renderer keeps decoded: every text on a page of saved text redraws at once. */
+const MAX_DERIVED_GLYPH_PATHS = 16384
+
+/** Decoded saved glyph outlines, by the glyph's command bytes, which a node keeps until it changes. */
+export function createDerivedGlyphPathCache(): ResourceCache<Uint8Array, Path> {
+ return new ResourceCache({
+ maxEntries: MAX_DERIVED_GLYPH_PATHS,
+ dispose: (path) => path.delete()
+ })
+}
+
+/** A saved glyph's outline, decoded once and borrowed from the renderer's cache. */
+function derivedGlyphPath(r: SkiaRenderer, blob: Uint8Array): Path {
+ const cached = r.derivedGlyphPathCache.get(blob)
+ if (cached) return cached
+ const path = geometryBlobToPath(r.ck, blob, 'NONZERO')
+ r.derivedGlyphPathCache.set(blob, path)
+ return path
+}
export function createGlyphSilhouetteCache(): ResourceCache<string, Path> {
return new ResourceCache({ maxEntries: MAX_GLYPH_SILHOUETTES, dispose: (path) => path.delete() })
@@ -395,11 +418,54 @@ export function drawReflowedPathTextSilhouettes(
* black fills vs white strokeGeometry
* 4. scale(fontSize,-fs) — font units → px; Y flip (font space is up-positive)
*/
+/** The paragraph holding text index `index`, found by bisection: saved glyphs can be many. */
+function rangeIndexAt(ranges: readonly TextParagraphRange[], index: number): number {
+ let lo = 0
+ let hi = ranges.length - 1
+ while (lo < hi) {
+ const mid = (lo + hi + 1) >> 1
+ if (ranges[mid].start <= index) lo = mid
+ else hi = mid - 1
+ }
+ return lo
+}
+
+/**
+ * The character whose style each saved list marker takes: the first of its list, as Figma
+ * draws markers. Figma saves a marker, with no character of its own, before its item's glyphs.
+ */
+function markerStyleCharacters(node: SceneNode): Map<number, number> {
+ const characters = new Map<number, number>()
+ if (!hasTextList(node)) return characters
+ const ranges = textParagraphRanges(node.text)
+ const listStarts = new Map(
+ textListItems(node.text, node.textParagraphs).map((item) => [
+ item.paragraph,
+ ranges[item.groupStart].start
+ ])
+ )
+ let markers: number[] = []
+ for (const [index, glyph] of (node.derivedTextGlyphs ?? []).entries()) {
+ if (glyph.firstCharacter === undefined) {
+ markers.push(index)
+ continue
+ }
+ const start = listStarts.get(rangeIndexAt(ranges, glyph.firstCharacter))
+ if (start !== undefined) for (const marker of markers) characters.set(marker, start)
+ markers = []
+ }
+ return characters
+}
+
function savedTextEligibility(node: SceneNode): boolean {
+ // Glyphs without a character are list markers in a list, and unknown text otherwise.
+ const charactersKnown = hasTextList(node)
+ ? !!node.derivedTextGlyphs?.some((glyph) => glyph.firstCharacter !== undefined)
+ : !!node.derivedTextGlyphs?.every((glyph) => glyph.firstCharacter !== undefined)
return (
node.styleRuns.length === 0 ||
(node.fills.filter((paint) => paint.visible).length === 1 &&
- !!node.derivedTextGlyphs?.every((glyph) => glyph.firstCharacter !== undefined) &&
+ charactersKnown &&
node.styleRuns.every(
(run) =>
!run.style.fills ||
@@ -422,24 +488,21 @@ export function drawDerivedText(r: SkiaRenderer, canvas: Canvas, node: SceneNode
// letter positions and breaks registration with strokeGeometry.
const snapBaselines = !hasRotatedDerivedGlyphs(node)
const savedTextEligible = savedTextEligibility(node)
+ const markerCharacters = markerStyleCharacters(node)
let underlineBaselineY = 0
- for (const glyph of node.derivedTextGlyphs) {
+ for (const [index, glyph] of node.derivedTextGlyphs.entries()) {
const glyphY = snapBaselines ? snapDerivedGlyphBaseline(glyph.y) : glyph.y
underlineBaselineY = Math.max(underlineBaselineY, glyphY)
- const path = geometryBlobToPath(r.ck, glyph.commandsBlob, 'NONZERO')
+ const path = derivedGlyphPath(r, glyph.commandsBlob)
canvas.save()
applyGlyphEmTransform(canvas, glyph, glyphY)
const shouldUseHardCoverage = shouldUseHardDerivedGlyphCoverage(node)
if (shouldUseHardCoverage) r.fillPaint.setAntiAlias(false)
+ const character = glyph.firstCharacter ?? markerCharacters.get(index)
const run =
- glyph.firstCharacter === undefined
+ character === undefined
? undefined
- : node.styleRuns.find(
- (run) =>
- glyph.firstCharacter !== undefined &&
- glyph.firstCharacter >= run.start &&
- glyph.firstCharacter < run.start + run.length
- )
+ : node.styleRuns.find((run) => character >= run.start && character < run.start + run.length)
const fills = run?.style.fills
if (fills && savedTextEligible) {
const paint = r.fillPaint.copy()
@@ -456,7 +519,6 @@ export function drawDerivedText(r: SkiaRenderer, canvas: Canvas, node: SceneNode
} else canvas.drawPath(path, r.fillPaint)
if (shouldUseHardCoverage) r.fillPaint.setAntiAlias(true)
canvas.restore()
- path.delete()
}
// Underline math assumes a single horizontal baseline — skip for path text.
diff --git a/packages/core/src/canvas/text/index.ts b/packages/core/src/canvas/text/index.ts
index f4818ef78..0525d9a92 100644
--- a/packages/core/src/canvas/text/index.ts
+++ b/packages/core/src/canvas/text/index.ts
@@ -1,18 +1,6 @@
-import type {
- CanvasKit,
- FontWeight,
- Paint,
- Paragraph,
- TextFontFeatures,
- TextFontVariations,
- TypefaceFontProvider
-} from 'canvaskit-wasm'
-
import type { SceneNode } from '@open-pencil/scene-graph'
-import { resolveRGBAForPreview } from '@open-pencil/scene-graph/color'
-import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text-direction'
-import { DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE } from '#core/constants'
+import { DEFAULT_FONT_FAMILY } from '#core/constants'
import { transformTextCase } from '#core/text/case'
import { fontManager, weightToStyle } from '#core/text/fonts'
import {
@@ -21,32 +9,24 @@ import {
fontRemoteCoverageDemand,
fontResolver,
missingGlyphOccurrences,
- missingGlyphsByScript,
- type FontResolutionSettled
+ missingGlyphsByScript
} from '#core/text/resolver'
-import { resolveParagraphFontFamilies } from './font-families'
-import { pushParagraphStyle, type ParagraphPaintStyle, type ParagraphBuildOptions } from './paint'
-import { withPreparedText } from './prepared'
-export { withTextParagraph } from './prepared'
-export type { ParagraphBuildOptions } from './paint'
-import type { ParagraphNode } from './paragraph-inputs'
-import type { TextPreparationCache } from './preparation-cache'
+import { buildParagraph } from './layout/build'
+import { resolveParagraphLayoutWidth } from './paragraph'
+import { withPreparedText } from './preparation'
+import type { FontReadinessRenderer, TextRenderer } from './renderer'
-interface FontReadinessRenderer {
- textPreparationCache?: TextPreparationCache
- ck?: CanvasKit
- fontProvider?: TypefaceFontProvider | null
- fontsLoaded?: boolean
- onFontResolutionSettled?: FontResolutionSettled
- trackFontDemand?: (node: SceneNode, key: string) => void
-}
-
-interface TextRenderer extends FontReadinessRenderer {
- ck: CanvasKit
- fontProvider: TypefaceFontProvider | null
- fontsLoaded: boolean
-}
+export { buildParagraph } from './layout/build'
+export type { TextLayout } from './layout'
+export type { ParagraphBuildOptions } from './paint'
+export {
+ textDecorationStyleValue,
+ textFontFeatures,
+ textFontVariations,
+ textHeightBehaviorValue
+} from './paragraph'
+export { withTextParagraph } from './preparation'
function demandFace(
r: FontReadinessRenderer,
@@ -255,9 +235,12 @@ export function buildTextPicture(r: TextRenderer, node: SceneNode): Uint8Array |
const bounds = ck.LTRBRect(0, 0, node.width || 1e6, node.height || 1e6)
const recCanvas = recorder.beginRecording(bounds)
- const paragraph = buildParagraph(r, node)
- recCanvas.drawParagraph(paragraph, 0, 0)
- paragraph.delete()
+ const layout = buildParagraph(r, node)
+ try {
+ layout.draw(recCanvas, 0, 0)
+ } finally {
+ layout.delete()
+ }
const picture = recorder.finishRecordingAsPicture()
recorder.delete()
@@ -274,326 +257,3 @@ export function textVerticalOffset(node: SceneNode, contentHeight: number): numb
if (node.textAlignVertical === 'BOTTOM') return available
return 0
}
-
-function resolveParagraphLayoutWidth(node: ParagraphNode, maxWidth?: number): number {
- if (maxWidth !== undefined) return maxWidth
- if (node.textAutoResize === 'WIDTH_AND_HEIGHT') return 1e6
- return node.width || 1e6
-}
-
-function buildTruncateOpts(
- node: ParagraphNode,
- baseFontSize: number
-): { maxLines?: number; ellipsis?: string } {
- if (node.textTruncation !== 'ENDING') return {}
-
- const opts: { maxLines?: number; ellipsis: string } = { ellipsis: '…' }
- if (node.maxLines != null && node.maxLines > 0) {
- opts.maxLines = node.maxLines
- } else if (node.height > 0) {
- const lineH = node.lineHeight || baseFontSize * 1.2
- opts.maxLines = Math.max(1, Math.floor(node.height / lineH))
- }
- return opts
-}
-
-function getParagraphTextAlign(
- ck: CanvasKit,
- node: Pick<SceneNode, 'textAlignHorizontal' | 'textDirection' | 'text'>
-) {
- const direction = resolveNodeTextDirection(node)
- switch (node.textAlignHorizontal) {
- case 'CENTER':
- return ck.TextAlign.Center
- case 'RIGHT':
- return direction === 'RTL' ? ck.TextAlign.Left : ck.TextAlign.Right
- case 'JUSTIFIED':
- return ck.TextAlign.Justify
- default:
- return direction === 'RTL' ? ck.TextAlign.Right : ck.TextAlign.Left
- }
-}
-
-/** Explicit axes win over the named-instance axes of a variable face (`implicit`). */
-export function textFontVariations(
- variations: SceneNode['fontVariations'] | undefined,
- implicit: SceneNode['fontVariations'] | null = null
-): TextFontVariations[] | undefined {
- const explicitAxes = new Set(variations?.map((variation) => variation.axis))
- const merged = [
- ...(implicit ?? []).filter((variation) => !explicitAxes.has(variation.axis)),
- ...(variations ?? [])
- ]
- if (merged.length === 0) return undefined
- return merged.map((variation) => ({ axis: variation.axis, value: variation.value }))
-}
-
-export function textFontFeatures(
- features: SceneNode['fontFeatures'] | undefined
-): TextFontFeatures[] | undefined {
- if (!features || features.length === 0) return undefined
- return features.map((feature) => ({
- name: feature.tag.toLowerCase(),
- value: feature.enabled ? 1 : 0
- }))
-}
-
-function textDecorationValue(ck: CanvasKit, decoration: string): number {
- switch (decoration) {
- case 'UNDERLINE':
- return ck.UnderlineDecoration
- case 'STRIKETHROUGH':
- return ck.LineThroughDecoration
- default:
- return ck.NoDecoration
- }
-}
-
-export function textDecorationStyleValue<T>(
- ck: { DecorationStyle: { Solid: T; Dotted: T; Wavy: T } },
- style: SceneNode['textDecorationStyle'] | undefined
-): T {
- switch (style) {
- case 'DOTTED':
- return ck.DecorationStyle.Dotted
- case 'WAVY':
- return ck.DecorationStyle.Wavy
- default:
- return ck.DecorationStyle.Solid
- }
-}
-
-export function textHeightBehaviorValue<T>(
- ck: { TextHeightBehavior: { DisableAll: T } },
- leadingTrim: SceneNode['leadingTrim']
-): T | undefined {
- return leadingTrim === 'CAP_HEIGHT' ? ck.TextHeightBehavior.DisableAll : undefined
-}
-
-function textDecorationColor(
- ck: CanvasKit,
- fills: SceneNode['textDecorationFills'] | undefined,
- fallback: Float32Array
-): Float32Array {
- const fill = fills?.find((item) => item.visible && item.type === 'SOLID')
- if (!fill) return fallback
- const color = resolveRGBAForPreview(fill.color).color
- return ck.Color4f(color.r, color.g, color.b, color.a * fill.opacity)
-}
-
-function styleRunColor(
- ck: CanvasKit,
- style: SceneNode['styleRuns'][number]['style'],
- baseColor: Float32Array
-): Float32Array {
- const visibleFill = style.fills?.find((fill) => fill.visible && fill.type === 'SOLID')
- if (!visibleFill) return baseColor
- const color = resolveRGBAForPreview(visibleFill.color).color
- return ck.Color4f(color.r, color.g, color.b, color.a * visibleFill.opacity)
-}
-
-function styleRunLanguage(
- style: SceneNode['styleRuns'][number]['style'],
- node: Pick<ParagraphNode, 'textLanguage'>
-): string | undefined {
- return style.textLanguage ?? node.textLanguage ?? undefined
-}
-
-function pushStyleRun(
- r: TextRenderer,
- builder: ReturnType<CanvasKit['ParagraphBuilder']['MakeFromFontProvider']>,
- node: ParagraphNode,
- run: SceneNode['styleRuns'][number],
- baseColor: Float32Array,
- baseFontSize: number,
- fontFamilies: (primary: string, weight: number, italic?: boolean) => string[],
- halfLeading: boolean,
- paintStyle?: ParagraphPaintStyle
-): void {
- const ck = r.ck
- const style = run.style
- const runLineHeight = style.lineHeight !== undefined ? style.lineHeight : node.lineHeight
- const runFontSize = style.fontSize ?? baseFontSize
- const runFamily = style.fontFamily ?? (node.fontFamily || DEFAULT_FONT_FAMILY)
- const runWeight = style.fontWeight ?? node.fontWeight
- const runItalic = style.italic ?? node.italic
-
- const textStyle = new ck.TextStyle({
- color: styleRunColor(ck, style, baseColor),
- fontFamilies: fontFamilies(runFamily, runWeight, runItalic),
- fontSize: runFontSize,
- locale: styleRunLanguage(style, node),
- fontStyle: {
- weight: { value: runWeight } as FontWeight,
- slant: runItalic ? ck.FontSlant.Italic : ck.FontSlant.Upright
- },
- fontVariations: textFontVariations(
- style.fontVariations ?? node.fontVariations,
- fontManager.namedInstanceVariations(runFamily, weightToStyle(runWeight, runItalic))
- ),
- fontFeatures: textFontFeatures(style.fontFeatures ?? node.fontFeatures),
- letterSpacing: style.letterSpacing ?? (node.letterSpacing || 0),
- decoration: textDecorationValue(ck, style.textDecoration ?? node.textDecoration),
- decorationStyle: textDecorationStyleValue(
- ck,
- style.textDecorationStyle ?? node.textDecorationStyle
- ),
- decorationThickness: style.textDecorationThickness ?? node.textDecorationThickness ?? undefined,
- decorationColor: textDecorationColor(
- ck,
- style.textDecorationFills ?? node.textDecorationFills,
- baseColor
- ),
- heightMultiplier: runLineHeight ? runLineHeight / runFontSize : undefined,
- halfLeading
- })
- pushParagraphStyle(builder, textStyle, paintStyle)
-}
-
-function addParagraphText(
- builder: ReturnType<CanvasKit['ParagraphBuilder']['MakeFromFontProvider']>,
- node: Pick<ParagraphNode, 'textCase'>,
- text: string
-): void {
- builder.addText(transformTextCase(text, node.textCase))
-}
-
-function addStyledRuns(
- r: TextRenderer,
- builder: ReturnType<CanvasKit['ParagraphBuilder']['MakeFromFontProvider']>,
- node: ParagraphNode,
- baseColor: Float32Array,
- baseFontSize: number,
- fontFamilies: (primary: string, weight: number, italic?: boolean) => string[],
- halfLeading: boolean,
- paintStyle?: ParagraphPaintStyle
-): void {
- const text = node.text
- let pos = 0
-
- for (const run of node.styleRuns) {
- if (pos < run.start) addParagraphText(builder, node, text.slice(pos, run.start))
- pushStyleRun(
- r,
- builder,
- node,
- run,
- baseColor,
- baseFontSize,
- fontFamilies,
- halfLeading,
- paintStyle
- )
- addParagraphText(builder, node, text.slice(run.start, run.start + run.length))
- builder.pop()
- pos = run.start + run.length
- }
-
- if (pos < text.length) addParagraphText(builder, node, text.slice(pos))
-}
-
-export function buildParagraph(
- r: TextRenderer,
- node: ParagraphNode,
- color?: Float32Array,
- { halfLeading = false, foregroundPaint }: ParagraphBuildOptions = {}
-): Paragraph {
- const ck = r.ck
- const baseColor = color ?? ck.BLACK
- const baseFontSize = node.fontSize || DEFAULT_FONT_SIZE
- const cjkFallbacks = fontManager.getCJKFallbackFamilies()
- const arabicFallbacks = fontManager.getArabicFallbackFamilies()
- const textDirection = resolveNodeTextDirection(node)
-
- const truncateOpts = buildTruncateOpts(node, baseFontSize)
-
- const fontFamilies = (primary: string, weight: number, italic = false) =>
- resolveParagraphFontFamilies(
- primary,
- weightToStyle(weight, italic),
- arabicFallbacks,
- cjkFallbacks
- )
-
- const baseTextStyle = {
- color: baseColor,
- fontFamilies: fontFamilies(
- node.fontFamily || DEFAULT_FONT_FAMILY,
- node.fontWeight,
- node.italic
- ),
- fontSize: baseFontSize,
- locale: node.textLanguage ?? undefined,
- fontStyle: {
- weight: { value: node.fontWeight } as FontWeight,
- slant: node.italic ? ck.FontSlant.Italic : ck.FontSlant.Upright
- },
- fontVariations: textFontVariations(
- node.fontVariations,
- fontManager.namedInstanceVariations(
- node.fontFamily || DEFAULT_FONT_FAMILY,
- weightToStyle(node.fontWeight, node.italic)
- )
- ),
- fontFeatures: textFontFeatures(node.fontFeatures),
- letterSpacing: node.letterSpacing || 0,
- decoration: textDecorationValue(ck, node.textDecoration),
- decorationStyle: textDecorationStyleValue(ck, node.textDecorationStyle),
- decorationThickness: node.textDecorationThickness ?? undefined,
- decorationColor: textDecorationColor(ck, node.textDecorationFills, baseColor),
- heightMultiplier: node.lineHeight ? node.lineHeight / baseFontSize : undefined,
- halfLeading
- }
- const paraStyle = new ck.ParagraphStyle({
- textAlign: getParagraphTextAlign(ck, node),
- textDirection: textDirection === 'RTL' ? ck.TextDirection.RTL : ck.TextDirection.LTR,
- textHeightBehavior: textHeightBehaviorValue(ck, node.leadingTrim),
- ...truncateOpts,
- textStyle: baseTextStyle
- })
-
- if (!r.fontProvider) throw new Error('Font provider not initialized')
- const builder = ck.ParagraphBuilder.MakeFromFontProvider(paraStyle, r.fontProvider)
-
- let background: Paint | undefined
- try {
- let paintStyle: ParagraphPaintStyle | undefined
- if (foregroundPaint) {
- background = new ck.Paint()
- background.setColor(ck.TRANSPARENT)
- paintStyle = { foreground: foregroundPaint, background }
- builder.pushPaintStyle(new ck.TextStyle(baseTextStyle), foregroundPaint, background)
- }
- if (node.styleRuns.length === 0) {
- addParagraphText(builder, node, node.text)
- } else {
- addStyledRuns(
- r,
- builder,
- node,
- baseColor,
- baseFontSize,
- fontFamilies,
- halfLeading,
- paintStyle
- )
- }
-
- const paragraph = builder.build()
- try {
- if (node.textAutoResize === 'WIDTH_AND_HEIGHT') {
- paragraph.layout(1e6)
- paragraph.layout(Math.max(node.width || 1, Math.ceil(paragraph.getLongestLine())))
- } else {
- paragraph.layout(resolveParagraphLayoutWidth(node))
- }
- return paragraph
- } catch (error) {
- paragraph.delete()
- throw error
- }
- } finally {
- builder.delete()
- background?.delete()
- }
-}
diff --git a/packages/core/src/canvas/text/layout/build.ts b/packages/core/src/canvas/text/layout/build.ts
new file mode 100644
index 000000000..5f6316ef7
--- /dev/null
+++ b/packages/core/src/canvas/text/layout/build.ts
@@ -0,0 +1,295 @@
+import type { Paragraph } from 'canvaskit-wasm'
+
+import {
+ hasParagraphSpacing,
+ hasTextList,
+ paragraphSpacingAt,
+ paragraphStyleAt,
+ textListItems,
+ textParagraphRanges,
+ topLevelNumberDigits,
+ type CharacterStyleOverride,
+ type StyleRun,
+ type TextListItem,
+ type TextParagraphRange
+} from '@open-pencil/scene-graph'
+import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text-direction'
+
+import { TextLayout, type TextLayoutBlock, type TextLayoutMarker } from '#core/canvas/text/layout'
+import type { ParagraphBuildOptions } from '#core/canvas/text/paint'
+import {
+ buildSkParagraph,
+ buildTruncateOpts,
+ resolveParagraphLayoutWidth,
+ type ParagraphBlockOptions
+} from '#core/canvas/text/paragraph'
+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 { weightToStyle } from '#core/text/fonts'
+import { glyphAdvanceSync } from '#core/text/opentype'
+
+/** A list item's indent per level, in ems of the list's first character. */
+const LIST_INDENT_EMS = 1.5
+/**
+ * Figma widens ordered lists by the advance of glyph 48 per extra digit: the character code of
+ * "0" read as a glyph ID. Measured in live Figma for Inter, Roboto, DM Sans, and others.
+ */
+const LIST_DIGIT_GLYPH_ID = 48
+/** A digit's width, in ems, for a font whose glyphs cannot be read. */
+const FALLBACK_DIGIT_EMS = 0.6
+/** The placeholder a first-line indent puts before the text takes one UTF-16 unit, three bytes. */
+const PLACEHOLDER_UTF8_LENGTH = 3
+
+function styleAt(runs: readonly StyleRun[], index: number): CharacterStyleOverride | undefined {
+ return runs.find((run) => index >= run.start && index < run.start + run.length)?.style
+}
+
+/** Style runs of `text[start, end)` in the slice's own indices. */
+function sliceStyleRuns(runs: readonly StyleRun[], start: number, end: number): StyleRun[] {
+ const sliced: StyleRun[] = []
+ for (const run of runs) {
+ const from = Math.max(start, run.start)
+ const to = Math.min(end, run.start + run.length)
+ if (to > from) sliced.push({ start: from - start, length: to - from, style: run.style })
+ }
+ return sliced
+}
+
+/** Whether the text lays out paragraph by paragraph rather than as one native paragraph. */
+function needsParagraphLayout(node: ParagraphNode): boolean {
+ return (
+ hasTextList(node) ||
+ node.paragraphSpacing !== 0 ||
+ node.paragraphIndent !== 0 ||
+ node.textParagraphs.some(hasParagraphSpacing)
+ )
+}
+
+function layoutForNode(layout: TextLayout, node: ParagraphNode): void {
+ if (node.textAutoResize === 'WIDTH_AND_HEIGHT') {
+ layout.layout(1e6)
+ layout.layout(Math.max(node.width || 1, Math.ceil(layout.getLongestLine())))
+ } else {
+ layout.layout(resolveParagraphLayoutWidth(node))
+ }
+}
+
+interface ListStyle {
+ em: number
+ family: string
+ style: string
+ /** The list's first character's style, which its markers take. */
+ override: CharacterStyleOverride | undefined
+}
+
+function listStyle(node: ParagraphNode, firstCharacter: number): ListStyle {
+ const override = styleAt(node.styleRuns, firstCharacter)
+ return {
+ em: override?.fontSize ?? (node.fontSize || DEFAULT_FONT_SIZE),
+ family: override?.fontFamily ?? (node.fontFamily || DEFAULT_FONT_FAMILY),
+ style: weightToStyle(override?.fontWeight ?? node.fontWeight, override?.italic ?? node.italic),
+ override
+ }
+}
+
+/** A marker in its list's style, without the text's decoration and with figures of one width. */
+function markerNode(node: ParagraphNode, item: TextListItem, style: ListStyle): ParagraphNode {
+ const override = style.override
+ const features = override?.fontFeatures ?? node.fontFeatures
+ return {
+ ...node,
+ text: item.marker,
+ fontSize: style.em,
+ fontFamily: style.family,
+ fontWeight: override?.fontWeight ?? node.fontWeight,
+ italic: override?.italic ?? node.italic,
+ letterSpacing: override?.letterSpacing ?? node.letterSpacing,
+ lineHeight: override?.lineHeight !== undefined ? override.lineHeight : node.lineHeight,
+ fontVariations: override?.fontVariations ?? node.fontVariations,
+ fontFeatures:
+ item.listType === 'ORDERED' ? [...features, { tag: 'TNUM', enabled: true }] : features,
+ textLanguage: override?.textLanguage ?? node.textLanguage,
+ styleRuns: override?.fills
+ ? [{ start: 0, length: item.marker.length, style: { fills: override.fills } }]
+ : [],
+ textCase: 'ORIGINAL',
+ textDecoration: 'NONE',
+ textDirection: 'LTR',
+ textAlignHorizontal: 'LEFT',
+ textAutoResize: 'WIDTH_AND_HEIGHT',
+ textTruncation: 'DISABLED',
+ maxLines: null
+ }
+}
+
+/**
+ * Text with lists, paragraph spacing, or a first-line indent, laid out one paragraph per
+ * native paragraph: Skia has no hanging indent, so each list item lays out at the width its
+ * indent leaves, beside a marker of its own.
+ */
+function buildBlocks(
+ r: TextRenderer,
+ node: ParagraphNode,
+ color: Float32Array | undefined,
+ options: ParagraphBuildOptions
+): TextLayout {
+ const shownText = transformTextCase(node.text, node.textCase)
+ const sources = textParagraphRanges(node.text)
+ const shown = textParagraphRanges(shownText)
+ const items = new Map(
+ textListItems(node.text, node.textParagraphs).map((item) => [item.paragraph, item])
+ )
+ const digits = topLevelNumberDigits([...items.values()])
+ const rtl = resolveNodeTextDirection(node) === 'RTL'
+ const truncation = buildTruncateOpts(node, node.fontSize || DEFAULT_FONT_SIZE)
+ const maxLines = truncation.maxLines
+ // Each paragraph starts one byte, its newline, after the one before it ends.
+ const utf8Starts: number[] = []
+ let utf8Offset = 0
+ for (const range of shown) {
+ utf8Starts.push(utf8Offset)
+ utf8Offset += utf8Length(shownText.slice(range.start, range.end)) + 1
+ }
+
+ const blocks: TextLayoutBlock[] = []
+ try {
+ for (const [index, { start, end }] of sources.entries()) {
+ blocks.push(buildBlock(index, start, end))
+ }
+ } catch (error) {
+ // Native paragraphs built before the failure are not garbage collected.
+ for (const block of blocks) {
+ block.paragraph.delete()
+ block.marker?.paragraph.delete()
+ }
+ throw error
+ }
+ return new TextLayout(r.ck, blocks, maxLines)
+
+ function buildBlock(index: number, start: number, end: number): TextLayoutBlock {
+ const shownRange: TextParagraphRange = shown[index]
+ const item = items.get(index)
+ const paragraphStyle = paragraphStyleAt(node.textParagraphs, index)
+ const empty = end === start
+ const blockNode: ParagraphNode = {
+ ...node,
+ text: empty ? ' ' : node.text.slice(start, end),
+ styleRuns: empty
+ ? sliceStyleRuns(node.styleRuns, start, start + 1)
+ : sliceStyleRuns(node.styleRuns, start, end)
+ }
+ const paragraphIndent = paragraphSpacingAt(node, index, 'paragraphIndent')
+ const firstLineIndent =
+ paragraphStyle.listType === 'NONE' && paragraphIndent > 0 ? paragraphIndent : 0
+ const blockOptions = (lines?: number): ParagraphBlockOptions => ({
+ firstLineIndent,
+ truncation: lines === undefined ? {} : { maxLines: lines, ellipsis: truncation.ellipsis },
+ edges: { first: index === 0, last: index === sources.length - 1 }
+ })
+ const betweenItems =
+ index > 0 &&
+ paragraphStyleAt(node.textParagraphs, index - 1).listType !== 'NONE' &&
+ paragraphStyle.listType !== 'NONE'
+ const list = item ? listStyle(node, sources[item.groupStart].start) : null
+ const marker = item && list ? buildMarker(r, node, item, list, color, options) : null
+ let paragraph: Paragraph
+ try {
+ paragraph = buildSkParagraph(r, blockNode, color, options, blockOptions(maxLines))
+ } catch (error) {
+ marker?.paragraph.delete()
+ throw error
+ }
+ return {
+ paragraph,
+ rebuild:
+ maxLines === undefined
+ ? undefined
+ : (lines) => buildSkParagraph(r, blockNode, color, options, blockOptions(lines)),
+ start: shownRange.start,
+ utf8Start: utf8Starts[index],
+ length: shownRange.end - shownRange.start,
+ lead: firstLineIndent > 0 ? 1 : 0,
+ utf8Lead: firstLineIndent > 0 ? PLACEHOLDER_UTF8_LENGTH : 0,
+ leadWidth: firstLineIndent,
+ empty,
+ inset: item && list ? listInset(node, item, list, digits) : 0,
+ rtl,
+ // The space after a paragraph is its own: the paragraph before sets the space before.
+ spaceBefore:
+ index === 0
+ ? 0
+ : paragraphSpacingAt(node, index - 1, betweenItems ? 'listSpacing' : 'paragraphSpacing'),
+ marker,
+ x: 0,
+ y: 0,
+ visible: true
+ }
+ }
+}
+
+/**
+ * How far a list item's text stands from the start edge: its level's indent, widened for
+ * ordered items by the digits past the first of the largest top-level number. A hanging list
+ * moves the items back by one level, so markers stand outside the text box.
+ */
+function listInset(
+ node: ParagraphNode,
+ item: TextListItem,
+ list: ListStyle,
+ digits: number
+): number {
+ const unit = list.em * LIST_INDENT_EMS
+ let inset = item.level * unit
+ if (item.listType === 'ORDERED' && digits > 1) {
+ const digit = glyphAdvanceSync(list.family, list.style, LIST_DIGIT_GLYPH_ID, list.em)
+ inset += (digits - 1) * (digit ?? list.em * FALLBACK_DIGIT_EMS)
+ }
+ return node.hangingList ? inset - unit : inset
+}
+
+function buildMarker(
+ r: TextRenderer,
+ node: ParagraphNode,
+ item: TextListItem,
+ list: ListStyle,
+ color: Float32Array | undefined,
+ options: ParagraphBuildOptions
+): TextLayoutMarker {
+ const paragraph = buildSkParagraph(r, markerNode(node, item, list), color, options)
+ paragraph.layout(1e6)
+ return {
+ paragraph,
+ kind: item.listType === 'ORDERED' ? 'number' : 'bullet',
+ em: list.em,
+ face: { family: list.family, style: list.style },
+ x: 0,
+ y: 0,
+ lineNumber: 0
+ }
+}
+
+/** Lay a text node out as the renderer draws it, at its own width. */
+export function buildParagraph(
+ r: TextRenderer,
+ node: ParagraphNode,
+ color?: Float32Array,
+ options: ParagraphBuildOptions = {}
+): TextLayout {
+ const layout = needsParagraphLayout(node)
+ ? buildBlocks(r, node, color, options)
+ : TextLayout.ofParagraph(
+ r.ck,
+ buildSkParagraph(r, node, color, options),
+ transformTextCase(node.text, node.textCase).length
+ )
+ try {
+ layoutForNode(layout, node)
+ return layout
+ } catch (error) {
+ layout.delete()
+ throw error
+ }
+}
diff --git a/packages/core/src/canvas/text/layout/index.ts b/packages/core/src/canvas/text/layout/index.ts
new file mode 100644
index 000000000..4032f2e01
--- /dev/null
+++ b/packages/core/src/canvas/text/layout/index.ts
@@ -0,0 +1,410 @@
+import type {
+ Canvas,
+ CanvasKit,
+ LineMetrics,
+ Paragraph,
+ PositionWithAffinity,
+ RectHeightStyle,
+ RectWidthStyle,
+ RectWithDirection,
+ ShapedLine
+} from 'canvaskit-wasm'
+
+/** A list item's number or bullet, laid out on its own. */
+export interface TextLayoutMarker {
+ paragraph: Paragraph
+ kind: 'bullet' | 'number'
+ /** Font size of the list's first character, which sets the marker's distance from the text. */
+ em: number
+ /** The face the marker is set in, for its glyph outlines. */
+ face: { family: string; style: string }
+ /** Where the marker is drawn and the line of the item it marks, set by layout. */
+ x: number
+ y: number
+ lineNumber: number
+}
+
+/** One paragraph of the text, or the whole text when it needs no paragraph layout of its own. */
+export interface TextLayoutBlock {
+ paragraph: Paragraph
+ /** Rebuilds the paragraph to show at most `maxLines` lines, when the text is truncated. */
+ rebuild?: (maxLines: number) => Paragraph
+ /** The first character the block holds, as an index into the text and in UTF-8 bytes. */
+ start: number
+ utf8Start: number
+ /** Characters the block holds, not counting the newline that ends it. */
+ length: number
+ /** Indices before the text, in UTF-16 and UTF-8, and its width: a first-line indent. */
+ lead: number
+ utf8Lead: number
+ leadWidth: number
+ /** Laid out from a space, standing for a paragraph with no characters. */
+ empty: boolean
+ /** Distance of the text from the start edge: a list item's indent. */
+ inset: number
+ rtl: boolean
+ /** Space above the block, from the paragraph before it. */
+ spaceBefore: number
+ marker: TextLayoutMarker | null
+ x: number
+ y: number
+ /** Whether the block is shown, as truncation hides blocks past its last line. */
+ visible: boolean
+}
+
+export interface TextCaretBox {
+ x: number
+ top: number
+ bottom: number
+}
+
+/**
+ * A laid-out text node: one native paragraph per block, stacked with paragraph and list
+ * spacing, each indented by its list level and preceded by its marker. It answers the
+ * `Paragraph` queries the renderer, measurement, and the text editor ask, in indices of the
+ * whole text and coordinates of the whole layout.
+ */
+export class TextLayout {
+ private lines: LineMetrics[] = []
+ private lineOffsets: number[] = []
+ private truncated = false
+
+ /** Text laid out as one native paragraph of `length` characters, not yet laid out. */
+ static ofParagraph(ck: CanvasKit, paragraph: Paragraph, length: number): TextLayout {
+ return new TextLayout(ck, [
+ {
+ paragraph,
+ start: 0,
+ utf8Start: 0,
+ length,
+ lead: 0,
+ utf8Lead: 0,
+ leadWidth: 0,
+ empty: false,
+ inset: 0,
+ rtl: false,
+ spaceBefore: 0,
+ marker: null,
+ x: 0,
+ y: 0,
+ visible: true
+ }
+ ])
+ }
+
+ constructor(
+ private readonly ck: CanvasKit,
+ readonly blocks: TextLayoutBlock[],
+ /** Lines the text may show in all, when it is truncated across blocks. */
+ private readonly maxLines?: number
+ ) {}
+
+ /** The line cap a block's paragraph was rebuilt with, when it differs from `maxLines`. */
+ private readonly caps = new Map<TextLayoutBlock, number>()
+
+ private visibleBlocks(): TextLayoutBlock[] {
+ return this.blocks.filter((block) => block.visible)
+ }
+
+ layout(width: number): void {
+ let y = 0
+ let lines = 0
+ this.truncated = false
+ for (const [index, block] of this.blocks.entries()) {
+ const remaining = this.maxLines === undefined ? Infinity : this.maxLines - lines
+ block.visible = remaining > 0
+ if (!block.visible) {
+ this.truncated = true
+ continue
+ }
+ block.paragraph.layout(Math.max(1, width - block.inset))
+ // A block capped for a narrower layout gets its lines back when there is room for them.
+ const cap = this.caps.get(block) ?? this.maxLines ?? Infinity
+ const overflows = block.paragraph.getLineMetrics().length > remaining
+ const clipped = cap < remaining && block.paragraph.didExceedMaxLines()
+ if ((overflows || clipped) && block.rebuild) {
+ block.paragraph.delete()
+ block.paragraph = block.rebuild(remaining)
+ this.caps.set(block, remaining)
+ block.paragraph.layout(Math.max(1, width - block.inset))
+ }
+ if (block.paragraph.didExceedMaxLines()) this.truncated = true
+ if (index > 0) y += block.spaceBefore
+ block.x = block.rtl ? 0 : block.inset
+ block.y = y
+ y += block.paragraph.getHeight()
+ lines += block.paragraph.getLineMetrics().length
+ this.placeMarker(block)
+ }
+ this.collectLines()
+ }
+
+ private placeMarker(block: TextLayoutBlock): void {
+ const marker = block.marker
+ const first = block.paragraph.getLineMetrics().at(0)
+ if (!marker || !first) return
+ const markerLine = marker.paragraph.getLineMetrics().at(0)
+ const width = marker.paragraph.getLongestLine()
+ // A bullet centres on the middle of the indent; a number ends a third of an em before the
+ // text, so numbers of any width line up on their periods.
+ if (block.rtl) {
+ const start = block.x + first.left + first.width
+ marker.x =
+ marker.kind === 'bullet' ? start + marker.em * 0.75 - width / 2 : start + marker.em / 3
+ } else {
+ const start = block.x + first.left
+ marker.x =
+ marker.kind === 'bullet'
+ ? start - marker.em * 0.75 - width / 2
+ : start - marker.em / 3 - width
+ }
+ marker.y = block.y + first.baseline - (markerLine?.baseline ?? 0)
+ }
+
+ private toTextIndex(block: TextLayoutBlock, index: number): number {
+ return block.start + Math.max(0, Math.min(block.length, index - block.lead))
+ }
+
+ private collectLines(): void {
+ this.lines = []
+ this.lineOffsets = []
+ const visible = this.visibleBlocks()
+ for (const [blockIndex, block] of visible.entries()) {
+ this.lineOffsets.push(this.lines.length)
+ if (block.marker) block.marker.lineNumber = this.lines.length
+ const metrics = block.paragraph.getLineMetrics()
+ 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
+ this.lines.push({
+ ...line,
+ startIndex: this.toTextIndex(block, line.startIndex),
+ endIndex: this.toTextIndex(block, line.endIndex),
+ endExcludingWhitespaces: this.toTextIndex(block, line.endExcludingWhitespaces),
+ endIncludingNewline: endsAtNewline
+ ? blockEnd + 1
+ : this.toTextIndex(block, line.endIncludingNewline),
+ 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,
+ lineNumber: this.lines.length
+ })
+ }
+ }
+ }
+
+ getHeight(): number {
+ const last = this.visibleBlocks().at(-1)
+ return last ? last.y + last.paragraph.getHeight() : 0
+ }
+
+ getLongestLine(): number {
+ let longest = 0
+ for (const block of this.visibleBlocks()) {
+ if (block.empty) continue
+ longest = Math.max(longest, block.inset + block.paragraph.getLongestLine())
+ }
+ return longest
+ }
+
+ didExceedMaxLines(): boolean {
+ return this.truncated
+ }
+
+ getLineMetrics(): LineMetrics[] {
+ return this.lines
+ }
+
+ getLineMetricsAt(lineNumber: number): LineMetrics | null {
+ return this.lines[lineNumber] ?? null
+ }
+
+ /** The block holding text index `index`; the newline ending a block belongs to it. */
+ private blockAt(index: number): { block: TextLayoutBlock; order: number } | null {
+ const visible = this.visibleBlocks()
+ for (const [order, block] of visible.entries()) {
+ if (index <= block.start + block.length) return { block, order }
+ }
+ const last = visible.at(-1)
+ return last ? { block: last, order: visible.length - 1 } : null
+ }
+
+ getLineNumberAt(index: number): number {
+ const found = this.blockAt(index)
+ if (!found) return -1
+ const { block, order } = found
+ const local = block.empty
+ ? 0
+ : block.paragraph.getLineNumberAt(index - block.start + block.lead)
+ const isLast = order === this.lineOffsets.length - 1
+ if (local < 0) {
+ if (isLast) return local
+ return this.lineOffsets[order] + block.paragraph.getLineMetrics().length - 1
+ }
+ return this.lineOffsets[order] + local
+ }
+
+ getGlyphPositionAtCoordinate(x: number, y: number): PositionWithAffinity {
+ const visible = this.visibleBlocks()
+ 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()
+ 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)
+ return {
+ pos: block.empty ? block.start : this.toTextIndex(block, local.pos),
+ affinity: local.affinity
+ }
+ }
+
+ getRectsForRange(
+ start: number,
+ end: number,
+ heightStyle: RectHeightStyle,
+ widthStyle: RectWidthStyle
+ ): RectWithDirection[] {
+ const rects: RectWithDirection[] = []
+ for (const block of this.visibleBlocks()) {
+ if (block.empty) continue
+ const from = Math.max(start, block.start)
+ const to = Math.min(end, block.start + block.length)
+ if (to <= from) continue
+ const local = block.paragraph.getRectsForRange(
+ from - block.start + block.lead,
+ to - block.start + block.lead,
+ heightStyle,
+ widthStyle
+ )
+ for (const { rect, dir } of local) {
+ rects.push({
+ rect: Float32Array.of(
+ rect[0] + block.x,
+ rect[1] + block.y,
+ rect[2] + block.x,
+ rect[3] + block.y
+ ),
+ dir
+ })
+ }
+ }
+ return rects
+ }
+
+ /**
+ * Where the caret stands before text index `index`: at the start edge of the character
+ * there, or after the last character of its paragraph.
+ */
+ getCaretRect(index: number, rtl: boolean): TextCaretBox | null {
+ const found = this.blockAt(index)
+ if (!found) return null
+ const { block } = found
+ const local = index - block.start
+ const first = block.paragraph.getLineMetrics().at(0)
+ if (block.empty || block.length === 0) {
+ if (!first) return null
+ const top = block.y + first.baseline - first.ascent
+ // The caret stands where typing starts: after a first-line indent.
+ return {
+ x: block.x + first.left + (rtl ? first.width - block.leadWidth : block.leadWidth),
+ top,
+ bottom: top + first.height
+ }
+ }
+ let lo = local
+ let hi = local + 1
+ let useRight = false
+ if (local <= 0) {
+ lo = 0
+ hi = 1
+ useRight = rtl
+ } else if (local >= block.length) {
+ lo = block.length - 1
+ hi = block.length
+ useRight = !rtl
+ }
+ const rects = block.paragraph.getRectsForRange(
+ lo + block.lead,
+ hi + block.lead,
+ this.ck.RectHeightStyle.Max,
+ this.ck.RectWidthStyle.Tight
+ )
+ const rect = rects.at(0)?.rect
+ if (!rect) return null
+ return {
+ x: block.x + (useRight ? rect[2] : rect[0]),
+ top: block.y + rect[1],
+ bottom: block.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.
+ */
+ getShapedLines(): ShapedLine[] {
+ const shaped: ShapedLine[] = []
+ for (const block of this.visibleBlocks()) {
+ for (const line of block.paragraph.getShapedLines()) {
+ 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,
+ runs: block.empty
+ ? []
+ : line.runs.map((run) => ({
+ ...run,
+ positions: run.positions.map(
+ (value, index) => value + (index % 2 === 0 ? block.x : block.y)
+ ),
+ offsets: run.offsets.map((offset) => this.toUtf8(block, offset))
+ }))
+ })
+ }
+ }
+ return shaped
+ }
+
+ private toUtf8(block: TextLayoutBlock, offset: number): number {
+ return block.empty ? block.utf8Start : block.utf8Start + Math.max(0, offset - block.utf8Lead)
+ }
+
+ /** Markers of the visible list items, where layout placed them. */
+ getMarkers(): TextLayoutMarker[] {
+ const markers: TextLayoutMarker[] = []
+ for (const block of this.visibleBlocks()) if (block.marker) markers.push(block.marker)
+ return markers
+ }
+
+ 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 marker = block.marker
+ if (marker) canvas.drawParagraph(marker.paragraph, x + marker.x, y + marker.y)
+ }
+ }
+
+ isDeleted(): boolean {
+ return this.blocks.every((block) => block.paragraph.isDeleted())
+ }
+
+ delete(): void {
+ for (const block of this.blocks) {
+ block.paragraph.delete()
+ block.marker?.paragraph.delete()
+ }
+ }
+}
diff --git a/packages/core/src/canvas/text/outlines.ts b/packages/core/src/canvas/text/outlines.ts
index 468936eac..601c55931 100644
--- a/packages/core/src/canvas/text/outlines.ts
+++ b/packages/core/src/canvas/text/outlines.ts
@@ -4,7 +4,13 @@ import type { SceneNode } from '@open-pencil/scene-graph'
import type { SkiaRenderer } from '#core/canvas/renderer'
import type { OutlineCommand } from '#core/text/opentype'
-import { textNodeToOutlineLayout } from '#core/text/outlines'
+import {
+ getTextOutlineSupport,
+ textNodeToOutlineLayout,
+ type TextOutlineGlyph
+} from '#core/text/outlines'
+
+import { shapeText } from './shape'
function appendOutlineCommand(
path: PathBuilder,
@@ -43,12 +49,28 @@ function appendOutlineCommand(
}
}
+/**
+ * The glyphs the canvas draws, list markers included, when every one has an outline; text set
+ * partly in a fallback or variable font has none and keeps the outline layout's own glyphs.
+ */
+function shapedOutlines(r: SkiaRenderer, node: SceneNode): TextOutlineGlyph[] | null {
+ if (!r.fontProvider || !getTextOutlineSupport(node).supported) return null
+ const shaped = shapeText(r.ck, r.fontProvider, node, { decorations: false })
+ if (!shaped) return null
+ const outlines: TextOutlineGlyph[] = []
+ for (const glyph of shaped.glyphs) {
+ if (!glyph.commands) return null
+ outlines.push({ commands: glyph.commands, x: glyph.x, y: glyph.y })
+ }
+ return outlines
+}
+
export function textNodeToOutlinePath(r: SkiaRenderer, node: SceneNode): Path | null {
- const layout = textNodeToOutlineLayout(node)
- if (!layout) return null
+ const glyphs = shapedOutlines(r, node) ?? textNodeToOutlineLayout(node)?.glyphs
+ if (!glyphs) return null
const path = new r.ck.PathBuilder()
- for (const glyph of layout.glyphs) {
+ for (const glyph of glyphs) {
for (const command of glyph.commands) appendOutlineCommand(path, command, glyph.x, glyph.y)
}
return path.detachAndDelete()
diff --git a/packages/core/src/canvas/text/paragraph/index.ts b/packages/core/src/canvas/text/paragraph/index.ts
new file mode 100644
index 000000000..cfa15bff9
--- /dev/null
+++ b/packages/core/src/canvas/text/paragraph/index.ts
@@ -0,0 +1,378 @@
+import type {
+ CanvasKit,
+ FontWeight,
+ Paint,
+ Paragraph,
+ ParagraphBuilder,
+ TextFontFeatures,
+ TextFontVariations,
+ TextHeightBehavior
+} from 'canvaskit-wasm'
+
+import type { SceneNode } from '@open-pencil/scene-graph'
+import { resolveRGBAForPreview } from '@open-pencil/scene-graph/color'
+import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text-direction'
+
+import { resolveParagraphFontFamilies } from '#core/canvas/text/font-families'
+import {
+ pushParagraphStyle,
+ type ParagraphPaintStyle,
+ type ParagraphBuildOptions
+} 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 { fontManager, weightToStyle } from '#core/text/fonts'
+
+import type { ParagraphNode } from './inputs'
+
+export function resolveParagraphLayoutWidth(node: ParagraphNode, maxWidth?: number): number {
+ if (maxWidth !== undefined) return maxWidth
+ if (node.textAutoResize === 'WIDTH_AND_HEIGHT') return 1e6
+ return node.width || 1e6
+}
+
+export function buildTruncateOpts(
+ node: ParagraphNode,
+ baseFontSize: number
+): { maxLines?: number; ellipsis?: string } {
+ if (node.textTruncation !== 'ENDING') return {}
+
+ const opts: { maxLines?: number; ellipsis: string } = { ellipsis: '…' }
+ if (node.maxLines != null && node.maxLines > 0) {
+ opts.maxLines = node.maxLines
+ } else if (node.height > 0) {
+ const lineH = node.lineHeight || baseFontSize * 1.2
+ opts.maxLines = Math.max(1, Math.floor(node.height / lineH))
+ }
+ return opts
+}
+
+function getParagraphTextAlign(
+ ck: CanvasKit,
+ node: Pick<SceneNode, 'textAlignHorizontal' | 'textDirection' | 'text'>
+) {
+ const direction = resolveNodeTextDirection(node)
+ switch (node.textAlignHorizontal) {
+ case 'CENTER':
+ return ck.TextAlign.Center
+ case 'RIGHT':
+ return direction === 'RTL' ? ck.TextAlign.Left : ck.TextAlign.Right
+ case 'JUSTIFIED':
+ return ck.TextAlign.Justify
+ default:
+ return direction === 'RTL' ? ck.TextAlign.Right : ck.TextAlign.Left
+ }
+}
+
+/** Explicit axes win over the named-instance axes of a variable face (`implicit`). */
+export function textFontVariations(
+ variations: SceneNode['fontVariations'] | undefined,
+ implicit: SceneNode['fontVariations'] | null = null
+): TextFontVariations[] | undefined {
+ const explicitAxes = new Set(variations?.map((variation) => variation.axis))
+ const merged = [
+ ...(implicit ?? []).filter((variation) => !explicitAxes.has(variation.axis)),
+ ...(variations ?? [])
+ ]
+ if (merged.length === 0) return undefined
+ return merged.map((variation) => ({ axis: variation.axis, value: variation.value }))
+}
+
+export function textFontFeatures(
+ features: SceneNode['fontFeatures'] | undefined
+): TextFontFeatures[] | undefined {
+ if (!features || features.length === 0) return undefined
+ return features.map((feature) => ({
+ name: feature.tag.toLowerCase(),
+ value: feature.enabled ? 1 : 0
+ }))
+}
+
+function textDecorationValue(ck: CanvasKit, decoration: string): number {
+ switch (decoration) {
+ case 'UNDERLINE':
+ return ck.UnderlineDecoration
+ case 'STRIKETHROUGH':
+ return ck.LineThroughDecoration
+ default:
+ return ck.NoDecoration
+ }
+}
+
+export function textDecorationStyleValue<T>(
+ ck: { DecorationStyle: { Solid: T; Dotted: T; Wavy: T } },
+ style: SceneNode['textDecorationStyle'] | undefined
+): T {
+ switch (style) {
+ case 'DOTTED':
+ return ck.DecorationStyle.Dotted
+ case 'WAVY':
+ return ck.DecorationStyle.Wavy
+ default:
+ return ck.DecorationStyle.Solid
+ }
+}
+
+export function textHeightBehaviorValue<T>(
+ ck: { TextHeightBehavior: { DisableAll: T } },
+ leadingTrim: SceneNode['leadingTrim']
+): T | undefined {
+ return leadingTrim === 'CAP_HEIGHT' ? ck.TextHeightBehavior.DisableAll : undefined
+}
+
+/** Which edges of the text a paragraph is: leading trim only trims the text's own edges. */
+export interface ParagraphEdges {
+ first: boolean
+ last: boolean
+}
+
+function blockHeightBehavior(
+ ck: CanvasKit,
+ leadingTrim: SceneNode['leadingTrim'],
+ edges: ParagraphEdges | undefined
+): TextHeightBehavior | undefined {
+ if (!edges) return textHeightBehaviorValue(ck, leadingTrim)
+ const { first, last } = edges
+ if (leadingTrim !== 'CAP_HEIGHT') return undefined
+ if (first && last) return ck.TextHeightBehavior.DisableAll
+ if (first) return ck.TextHeightBehavior.DisableFirstAscent
+ if (last) return ck.TextHeightBehavior.DisableLastDescent
+ return ck.TextHeightBehavior.All
+}
+
+function textDecorationColor(
+ ck: CanvasKit,
+ fills: SceneNode['textDecorationFills'] | undefined,
+ fallback: Float32Array
+): Float32Array {
+ const fill = fills?.find((item) => item.visible && item.type === 'SOLID')
+ if (!fill) return fallback
+ const color = resolveRGBAForPreview(fill.color).color
+ return ck.Color4f(color.r, color.g, color.b, color.a * fill.opacity)
+}
+
+function styleRunColor(
+ ck: CanvasKit,
+ style: SceneNode['styleRuns'][number]['style'],
+ baseColor: Float32Array
+): Float32Array {
+ const visibleFill = style.fills?.find((fill) => fill.visible && fill.type === 'SOLID')
+ if (!visibleFill) return baseColor
+ const color = resolveRGBAForPreview(visibleFill.color).color
+ return ck.Color4f(color.r, color.g, color.b, color.a * visibleFill.opacity)
+}
+
+function styleRunLanguage(
+ style: SceneNode['styleRuns'][number]['style'],
+ node: Pick<ParagraphNode, 'textLanguage'>
+): string | undefined {
+ return style.textLanguage ?? node.textLanguage ?? undefined
+}
+
+function pushStyleRun(
+ r: TextRenderer,
+ builder: ParagraphBuilder,
+ node: ParagraphNode,
+ run: SceneNode['styleRuns'][number],
+ baseColor: Float32Array,
+ baseFontSize: number,
+ fontFamilies: (primary: string, weight: number, italic?: boolean) => string[],
+ halfLeading: boolean,
+ paintStyle?: ParagraphPaintStyle
+): void {
+ const ck = r.ck
+ const style = run.style
+ const runLineHeight = style.lineHeight !== undefined ? style.lineHeight : node.lineHeight
+ const runFontSize = style.fontSize ?? baseFontSize
+ const runFamily = style.fontFamily ?? (node.fontFamily || DEFAULT_FONT_FAMILY)
+ const runWeight = style.fontWeight ?? node.fontWeight
+ const runItalic = style.italic ?? node.italic
+
+ const textStyle = new ck.TextStyle({
+ color: styleRunColor(ck, style, baseColor),
+ fontFamilies: fontFamilies(runFamily, runWeight, runItalic),
+ fontSize: runFontSize,
+ locale: styleRunLanguage(style, node),
+ fontStyle: {
+ weight: { value: runWeight } as FontWeight,
+ slant: runItalic ? ck.FontSlant.Italic : ck.FontSlant.Upright
+ },
+ fontVariations: textFontVariations(
+ style.fontVariations ?? node.fontVariations,
+ fontManager.namedInstanceVariations(runFamily, weightToStyle(runWeight, runItalic))
+ ),
+ fontFeatures: textFontFeatures(style.fontFeatures ?? node.fontFeatures),
+ letterSpacing: style.letterSpacing ?? (node.letterSpacing || 0),
+ decoration: textDecorationValue(ck, style.textDecoration ?? node.textDecoration),
+ decorationStyle: textDecorationStyleValue(
+ ck,
+ style.textDecorationStyle ?? node.textDecorationStyle
+ ),
+ decorationThickness: style.textDecorationThickness ?? node.textDecorationThickness ?? undefined,
+ decorationColor: textDecorationColor(
+ ck,
+ style.textDecorationFills ?? node.textDecorationFills,
+ baseColor
+ ),
+ heightMultiplier: runLineHeight ? runLineHeight / runFontSize : undefined,
+ halfLeading
+ })
+ pushParagraphStyle(builder, textStyle, paintStyle)
+}
+
+function addParagraphText(
+ builder: ParagraphBuilder,
+ node: Pick<ParagraphNode, 'textCase'>,
+ text: string
+): void {
+ builder.addText(transformTextCase(text, node.textCase))
+}
+
+function addStyledRuns(
+ r: TextRenderer,
+ builder: ParagraphBuilder,
+ node: ParagraphNode,
+ baseColor: Float32Array,
+ baseFontSize: number,
+ fontFamilies: (primary: string, weight: number, italic?: boolean) => string[],
+ halfLeading: boolean,
+ paintStyle?: ParagraphPaintStyle
+): void {
+ const text = node.text
+ let pos = 0
+
+ for (const run of node.styleRuns) {
+ if (pos < run.start) addParagraphText(builder, node, text.slice(pos, run.start))
+ pushStyleRun(
+ r,
+ builder,
+ node,
+ run,
+ baseColor,
+ baseFontSize,
+ fontFamilies,
+ halfLeading,
+ paintStyle
+ )
+ addParagraphText(builder, node, text.slice(run.start, run.start + run.length))
+ builder.pop()
+ pos = run.start + run.length
+ }
+
+ if (pos < text.length) addParagraphText(builder, node, text.slice(pos))
+}
+
+/** What a paragraph that is one block of a longer text needs beyond its node's own style. */
+export interface ParagraphBlockOptions {
+ /** Room before the first line, as a plain paragraph's first-line indent. */
+ firstLineIndent?: number
+ /** Truncation for this block in place of the node's. */
+ truncation?: { maxLines?: number; ellipsis?: string }
+ edges?: ParagraphEdges
+}
+
+/** Room before a paragraph's first line, as an empty placeholder on its baseline. */
+function addFirstLineIndent(ck: CanvasKit, builder: ParagraphBuilder, width: number): void {
+ builder.addPlaceholder(width, 0, ck.PlaceholderAlignment.Baseline, ck.TextBaseline.Alphabetic, 0)
+}
+
+/**
+ * A native paragraph for `node`'s text in its style runs, not yet laid out. A first-line
+ * indent is a placeholder before the text, which takes the first character index.
+ */
+export function buildSkParagraph(
+ r: TextRenderer,
+ node: ParagraphNode,
+ color?: Float32Array,
+ { halfLeading = false, foregroundPaint }: ParagraphBuildOptions = {},
+ block: ParagraphBlockOptions = {}
+): Paragraph {
+ const ck = r.ck
+ const baseColor = color ?? ck.BLACK
+ const baseFontSize = node.fontSize || DEFAULT_FONT_SIZE
+ const cjkFallbacks = fontManager.getCJKFallbackFamilies()
+ const arabicFallbacks = fontManager.getArabicFallbackFamilies()
+ const textDirection = resolveNodeTextDirection(node)
+
+ const truncateOpts = block.truncation ?? buildTruncateOpts(node, baseFontSize)
+
+ const fontFamilies = (primary: string, weight: number, italic = false) =>
+ resolveParagraphFontFamilies(
+ primary,
+ weightToStyle(weight, italic),
+ arabicFallbacks,
+ cjkFallbacks
+ )
+
+ const baseTextStyle = {
+ color: baseColor,
+ fontFamilies: fontFamilies(
+ node.fontFamily || DEFAULT_FONT_FAMILY,
+ node.fontWeight,
+ node.italic
+ ),
+ fontSize: baseFontSize,
+ locale: node.textLanguage ?? undefined,
+ fontStyle: {
+ weight: { value: node.fontWeight } as FontWeight,
+ slant: node.italic ? ck.FontSlant.Italic : ck.FontSlant.Upright
+ },
+ fontVariations: textFontVariations(
+ node.fontVariations,
+ fontManager.namedInstanceVariations(
+ node.fontFamily || DEFAULT_FONT_FAMILY,
+ weightToStyle(node.fontWeight, node.italic)
+ )
+ ),
+ fontFeatures: textFontFeatures(node.fontFeatures),
+ letterSpacing: node.letterSpacing || 0,
+ decoration: textDecorationValue(ck, node.textDecoration),
+ decorationStyle: textDecorationStyleValue(ck, node.textDecorationStyle),
+ decorationThickness: node.textDecorationThickness ?? undefined,
+ decorationColor: textDecorationColor(ck, node.textDecorationFills, baseColor),
+ heightMultiplier: node.lineHeight ? node.lineHeight / baseFontSize : undefined,
+ halfLeading
+ }
+ const paraStyle = new ck.ParagraphStyle({
+ textAlign: getParagraphTextAlign(ck, node),
+ textDirection: textDirection === 'RTL' ? ck.TextDirection.RTL : ck.TextDirection.LTR,
+ textHeightBehavior: blockHeightBehavior(ck, node.leadingTrim, block.edges),
+ ...truncateOpts,
+ textStyle: baseTextStyle
+ })
+
+ if (!r.fontProvider) throw new Error('Font provider not initialized')
+ const builder = ck.ParagraphBuilder.MakeFromFontProvider(paraStyle, r.fontProvider)
+
+ let background: Paint | undefined
+ try {
+ let paintStyle: ParagraphPaintStyle | undefined
+ if (foregroundPaint) {
+ background = new ck.Paint()
+ background.setColor(ck.TRANSPARENT)
+ paintStyle = { foreground: foregroundPaint, background }
+ builder.pushPaintStyle(new ck.TextStyle(baseTextStyle), foregroundPaint, background)
+ }
+ if (block.firstLineIndent) addFirstLineIndent(ck, builder, block.firstLineIndent)
+ if (node.styleRuns.length === 0) {
+ addParagraphText(builder, node, node.text)
+ } else {
+ addStyledRuns(
+ r,
+ builder,
+ node,
+ baseColor,
+ baseFontSize,
+ fontFamilies,
+ halfLeading,
+ paintStyle
+ )
+ }
+
+ return builder.build()
+ } finally {
+ builder.delete()
+ background?.delete()
+ }
+}
diff --git a/packages/core/src/canvas/text/paragraph-inputs.ts b/packages/core/src/canvas/text/paragraph/inputs.ts
similarity index 94%
rename from packages/core/src/canvas/text/paragraph-inputs.ts
rename to packages/core/src/canvas/text/paragraph/inputs.ts
index bd4f644e8..d24154672 100644
--- a/packages/core/src/canvas/text/paragraph-inputs.ts
+++ b/packages/core/src/canvas/text/paragraph/inputs.ts
@@ -23,6 +23,11 @@ export const PARAGRAPH_INPUT_KEYS = [
'textDecorationFills',
'textTruncation',
'maxLines',
+ 'textParagraphs',
+ 'listSpacing',
+ 'paragraphSpacing',
+ 'paragraphIndent',
+ 'hangingList',
'textAutoResize',
'width',
'height'
diff --git a/packages/core/src/canvas/text/preparation-cache.ts b/packages/core/src/canvas/text/preparation/cache.ts
similarity index 95%
rename from packages/core/src/canvas/text/preparation-cache.ts
rename to packages/core/src/canvas/text/preparation/cache.ts
index 527e4f121..43605f50a 100644
--- a/packages/core/src/canvas/text/preparation-cache.ts
+++ b/packages/core/src/canvas/text/preparation/cache.ts
@@ -1,4 +1,4 @@
-import type { Paragraph, TypefaceFontProvider } from 'canvaskit-wasm'
+import type { TypefaceFontProvider } from 'canvaskit-wasm'
import type { SceneNode } from '@open-pencil/scene-graph'
import type { Size } from '@open-pencil/scene-graph/primitives'
@@ -13,12 +13,13 @@ const MAX_PREPARED_TEXT_UNITS = 262_144
// Layout measures a text at a few widths; more than this means the widths are not repeating.
const MAX_MEASURED_WIDTHS = 16
-import { PARAGRAPH_INPUT_KEYS, shapingInputs } from './paragraph-inputs'
+import type { TextLayout } from '#core/canvas/text/layout'
+import { PARAGRAPH_INPUT_KEYS, shapingInputs } from '#core/canvas/text/paragraph/inputs'
type PreparationInput = SceneNode[(typeof PARAGRAPH_INPUT_KEYS)[number]]
export interface PreparedText {
- paragraph: Paragraph
+ paragraph: TextLayout
missingGlyphs?: ReturnType<typeof missingGlyphOccurrences>
}
@@ -68,7 +69,7 @@ export class TextPreparationCache {
variant: string,
generation: number,
provider: TypefaceFontProvider,
- build: () => Paragraph,
+ build: () => TextLayout,
consume: (prepared: PreparedText) => T
): T {
this.useScope(generation, provider)
diff --git a/packages/core/src/canvas/text/prepared.ts b/packages/core/src/canvas/text/preparation/index.ts
similarity index 80%
rename from packages/core/src/canvas/text/prepared.ts
rename to packages/core/src/canvas/text/preparation/index.ts
index 7d4238b7d..1c88c2b15 100644
--- a/packages/core/src/canvas/text/prepared.ts
+++ b/packages/core/src/canvas/text/preparation/index.ts
@@ -1,11 +1,12 @@
-import type { Paragraph, TypefaceFontProvider } from 'canvaskit-wasm'
+import type { TypefaceFontProvider } from 'canvaskit-wasm'
import type { SceneNode } from '@open-pencil/scene-graph'
+import type { TextLayout } from '#core/canvas/text/layout'
+import type { ParagraphBuildOptions } from '#core/canvas/text/paint'
import { fontManager } from '#core/text/fonts'
-import type { ParagraphBuildOptions } from './paint'
-import type { PreparedText, TextPreparationCache } from './preparation-cache'
+import type { PreparedText, TextPreparationCache } from './cache'
interface PreparationRenderer {
textPreparationCache?: TextPreparationCache
@@ -16,7 +17,7 @@ export function withPreparedText<T>(
r: PreparationRenderer,
node: SceneNode,
variant: string,
- build: () => Paragraph,
+ build: () => TextLayout,
consume: (prepared: PreparedText) => T,
cacheAllowed = true
): T {
@@ -45,12 +46,12 @@ export function withTextParagraph<T>(
node: SceneNode,
color: Float32Array,
options: ParagraphBuildOptions
- ) => Paragraph
+ ) => TextLayout
},
node: SceneNode,
color: Float32Array,
options: ParagraphBuildOptions,
- draw: (paragraph: Paragraph) => T
+ draw: (paragraph: TextLayout) => T
): T {
return withPreparedText(
r,
diff --git a/packages/core/src/canvas/text/renderer.ts b/packages/core/src/canvas/text/renderer.ts
new file mode 100644
index 000000000..d0ef202e7
--- /dev/null
+++ b/packages/core/src/canvas/text/renderer.ts
@@ -0,0 +1,22 @@
+import type { CanvasKit, TypefaceFontProvider } from 'canvaskit-wasm'
+
+import type { SceneNode } from '@open-pencil/scene-graph'
+
+import type { FontResolutionSettled } from '#core/text/resolver'
+
+import type { TextPreparationCache } from './preparation/cache'
+
+export interface FontReadinessRenderer {
+ textPreparationCache?: TextPreparationCache
+ ck?: CanvasKit
+ fontProvider?: TypefaceFontProvider | null
+ fontsLoaded?: boolean
+ onFontResolutionSettled?: FontResolutionSettled
+ trackFontDemand?: (node: SceneNode, key: string) => void
+}
+
+export interface TextRenderer extends FontReadinessRenderer {
+ ck: CanvasKit
+ fontProvider: TypefaceFontProvider | null
+ fontsLoaded: boolean
+}
diff --git a/packages/core/src/canvas/text/shape.ts b/packages/core/src/canvas/text/shape.ts
index 01bb89b2e..6e643005d 100644
--- a/packages/core/src/canvas/text/shape.ts
+++ b/packages/core/src/canvas/text/shape.ts
@@ -9,6 +9,8 @@ import {
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { buildParagraph, textVerticalOffset } from '#core/canvas/text'
+import type { TextLayoutMarker } from '#core/canvas/text/layout'
+import { utf16IndicesByUtf8 } from '#core/canvas/text/utf8'
import { getCanvasKit } from '#core/canvaskit'
import { transformTextCase } from '#core/text/case'
import { fontManager, weightToStyle } from '#core/text/fonts'
@@ -29,9 +31,14 @@ function fontStyleAt(node: SceneNode, index: number): { family: string; style: s
* glyph IDs are trusted only when the style's own font covers every character of the run and
* so the paragraph had no reason to fall back to another font.
*/
-function runOutlineSource(node: SceneNode, text: string, run: GlyphRun): GlyphOutlineSource | null {
+function runOutlineSource(
+ node: SceneNode,
+ text: string,
+ run: GlyphRun,
+ characterAt: (offset: number) => number
+): GlyphOutlineSource | null {
if (run.fakeBold || run.fakeItalic || run.glyphs.length === 0) return null
- const offsets = Array.from(run.offsets)
+ const offsets = Array.from(run.offsets, characterAt)
const start = Math.min(...offsets)
const end = Math.max(...offsets)
const { family, style } = fontStyleAt(node, start)
@@ -64,14 +71,15 @@ function shapedRunGlyphs(
run: GlyphRun,
source: GlyphOutlineSource | null,
line: { left: number; baseline: number },
- characterOffsets: Array<number | undefined>
+ characterOffsets: Array<number | undefined>,
+ characterAt: (offset: number) => number
): ShapedTextGlyph[] {
const glyphs: ShapedTextGlyph[] = []
for (let index = 0; index < run.glyphs.length; index++) {
const commands = source?.outline(run.glyphs[index], run.size) ?? null
const x = run.positions[index * 2]
const nextX = run.positions[(index + 1) * 2]
- const firstCharacter = run.offsets[index]
+ const firstCharacter = characterAt(run.offsets[index])
glyphs.push({
commands,
x,
@@ -86,6 +94,32 @@ function shapedRunGlyphs(
return glyphs
}
+/**
+ * A list marker's glyphs as Figma saves them: placed beside their item and drawing no
+ * character of the text.
+ */
+function markerGlyphs(marker: TextLayoutMarker, offsetY: number): ShapedTextGlyph[] {
+ const source = glyphOutlineSourceSync(marker.face.family, marker.face.style)
+ const baseline = marker.paragraph.getLineMetrics().at(0)?.baseline ?? 0
+ const glyphs: ShapedTextGlyph[] = []
+ for (const line of marker.paragraph.getShapedLines()) {
+ for (const run of line.runs) {
+ const trusted = !run.fakeBold && !run.fakeItalic
+ for (let index = 0; index < run.glyphs.length; index++) {
+ const x = run.positions[index * 2]
+ glyphs.push({
+ commands: trusted ? (source?.outline(run.glyphs[index], run.size) ?? null) : null,
+ x: marker.x + x,
+ y: marker.y + baseline + offsetY,
+ fontSize: run.size,
+ advance: run.positions[(index + 1) * 2] - x
+ })
+ }
+ }
+ }
+ return glyphs
+}
+
/** Characters inside a glyph cluster or without a glyph take the offset of the one before. */
function completeCharacterOffsets(offsets: Array<number | undefined>): number[] {
let previous = 0
@@ -100,12 +134,14 @@ function completeCharacterOffsets(offsets: Array<number | undefined>): number[]
* the glyph ID CanvasKit chose, so ligatures and contextual forms keep their shapes. When a run's
* font is missing, variable, or a fallback, or the glyphs could not draw the text's decorations,
* no glyph gets an outline: the layout still stands, and readers draw the text themselves.
+ * Outlines that carry no decorations, as outlined text has none, set `decorations: false`.
* Returns `null` for text saved glyphs cannot represent at all.
*/
export function shapeText(
ck: CanvasKit,
fontProvider: TypefaceFontProvider,
- node: SceneNode
+ node: SceneNode,
+ { decorations = true }: { decorations?: boolean } = {}
): ShapedText | null {
const text = transformTextCase(node.text, node.textCase)
if (!canShape(node, text)) return null
@@ -119,16 +155,22 @@ export function shapeText(
if (lines.length === 0 || lines.length !== metrics.length) return null
const offsetY = textVerticalOffset(node, paragraph.getHeight())
+ const characterAt = utf16IndicesByUtf8(text)
+ const markers = new Map(paragraph.getMarkers().map((marker) => [marker.lineNumber, marker]))
const glyphs: ShapedTextGlyph[] = []
const characterOffsets: Array<number | undefined> = Array.from({ length: text.length })
for (const [lineIndex, line] of lines.entries()) {
+ // Figma saves an item's marker before the glyphs of its first line.
+ const marker = markers.get(lineIndex)
+ if (marker) glyphs.push(...markerGlyphs(marker, offsetY))
for (const run of line.runs) {
glyphs.push(
...shapedRunGlyphs(
run,
- runOutlineSource(node, text, run),
+ runOutlineSource(node, text, run, characterAt),
{ left: metrics[lineIndex].left, baseline: metrics[lineIndex].baseline + offsetY },
- characterOffsets
+ characterOffsets,
+ characterAt
)
)
}
@@ -136,7 +178,8 @@ export function shapeText(
// Outlines from some runs only would draw the text with characters missing, and saved
// glyphs draw decorations on one baseline.
const outlined =
- glyphs.every((glyph) => glyph.commands) && !(lines.length > 1 && hasDecoration(node))
+ glyphs.every((glyph) => glyph.commands) &&
+ !(decorations && lines.length > 1 && hasDecoration(node))
return {
glyphs: outlined ? glyphs : glyphs.map((glyph) => ({ ...glyph, commands: null })),
baselines: metrics.map((line) => ({
diff --git a/packages/core/src/canvas/text/utf8.ts b/packages/core/src/canvas/text/utf8.ts
new file mode 100644
index 000000000..3d8624f67
--- /dev/null
+++ b/packages/core/src/canvas/text/utf8.ts
@@ -0,0 +1,29 @@
+/** Bytes a code point takes in UTF-8. */
+function utf8Width(codePoint: number): number {
+ if (codePoint < 0x80) return 1
+ if (codePoint < 0x800) return 2
+ if (codePoint < 0x10000) return 3
+ return 4
+}
+
+/** The length of `text` in UTF-8 bytes, the unit of CanvasKit's glyph run offsets. */
+export function utf8Length(text: string): number {
+ let length = 0
+ for (const character of text) length += utf8Width(character.codePointAt(0) ?? 0)
+ return length
+}
+
+/**
+ * UTF-16 indices of the text by UTF-8 byte offset: CanvasKit reports glyph runs in bytes.
+ * Offsets inside a character map to its start.
+ */
+export function utf16IndicesByUtf8(text: string): (offset: number) => number {
+ const indices: number[] = []
+ let utf16 = 0
+ for (const character of text) {
+ const bytes = utf8Width(character.codePointAt(0) ?? 0)
+ for (let byte = 0; byte < bytes; byte++) indices.push(utf16)
+ utf16 += character.length
+ }
+ return (offset) => indices[offset] ?? text.length
+}
diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.ts
index a8cca61c7..77af3fbdf 100644
--- a/packages/core/src/editor/create.ts
+++ b/packages/core/src/editor/create.ts
@@ -115,6 +115,15 @@ export function createEditor(options?: EditorOptions) {
})
}
+ /**
+ * The caret or selection of the edited text moved: the canvas repaints its overlay and the
+ * views that follow the selection update, without the document counting as changed.
+ */
+ function textSelectionChanged() {
+ state.textSelectionVersion++
+ requestRepaint()
+ }
+
function requestRefresh() {
state.sceneVersion++
}
@@ -270,6 +279,16 @@ export function createEditor(options?: EditorOptions) {
const undoBridge = createUndoBridge(undoActions, selection, nodes.flushNudge)
const lintFixBridge = createLintFixBridge(ctx, nodes, structure, clipboard)
+ // The edited text follows changes made outside the editor, such as a panel field being
+ // dragged, so its caret and selection move with the text instead of after the change.
+ const invalidateEditedText = (id: string) => {
+ if (id !== state.editingTextId) return
+ const node = _graph.getNode(id)
+ if (node) _textEditor?.invalidateParagraph(node)
+ }
+ onEditorEvent('node:updated', invalidateEditedText)
+ onEditorEvent('node:previewUpdated', invalidateEditedText)
+
function setCanvasKit(ck: CanvasKit, renderer: SkiaRenderer) {
_ck = ck
_renderer = renderer
@@ -358,6 +377,7 @@ export function createEditor(options?: EditorOptions) {
isInteractiveEditing: () => interactiveEdits.size > 0,
requestRender,
requestRefresh,
+ textSelectionChanged,
requestRepaint,
onEditorEvent,
setCanvasKit,
@@ -411,6 +431,9 @@ export function createEditor(options?: EditorOptions) {
// Undo — bridge functions that need cross-module refs
...undoBridge,
+ // While text is edited, what was typed undoes first and the editor keeps the result.
+ undoAction: () => text.runTextEditStep(undoBridge.undoAction),
+ redoAction: () => text.runTextEditStep(undoBridge.redoAction),
setDocumentColorSpace: colorSpace.setDocumentColorSpace,
diff --git a/packages/core/src/editor/state/view.ts b/packages/core/src/editor/state/view.ts
index dc61aea95..670f87f23 100644
--- a/packages/core/src/editor/state/view.ts
+++ b/packages/core/src/editor/state/view.ts
@@ -27,6 +27,7 @@ export function createDefaultEditorViewState(pageId: string): EditorViewState {
zoom: 1,
navigation: { phase: 'idle', generation: 0, lastInputAt: 0 },
renderVersion: 0,
+ textSelectionVersion: 0,
enteredContainerId: null,
nodeEditState: null,
cursorCanvasX: null,
diff --git a/packages/core/src/editor/text.ts b/packages/core/src/editor/text.ts
index ca82200a3..562279544 100644
--- a/packages/core/src/editor/text.ts
+++ b/packages/core/src/editor/text.ts
@@ -7,6 +7,7 @@ import {
import { copyDerivedGlyphs, copyGeometryPaths } from '@open-pencil/scene-graph/copy'
import { textAutoResizeChanges } from '#core/layout/text-auto-resize'
+import type { TextEditorState } from '#core/text/editor'
import { weightToStyle } from '#core/text/fonts'
import { hasGlyphOutlines } from '#core/text/opentype'
@@ -139,23 +140,15 @@ export function createTextActions(ctx: EditorContext) {
ctx.requestRender()
}
- function commitTextEdit() {
- const te = ctx.getTextEditor()
- if (!te?.isActive) {
- ctx.state.editingTextId = null
- activeSession = null
- return
- }
- const textState = te.state
- if (!textState) {
- te.stop()
- ctx.state.editingTextId = null
- activeSession = null
- ctx.requestRender()
- return
- }
+ /** Records what the edit changed since its session began, as one undo step. */
+ function recordTextEdit(textState: TextEditorState) {
const result = { nodeId: textState.nodeId, text: textState.text }
- const before = activeSession?.before ?? { text: '', styleRuns: [], size: {} }
+ const before = activeSession?.before ?? {
+ text: '',
+ styleRuns: [],
+ textParagraphs: [],
+ size: {}
+ }
const beforePathText = activeSession?.beforePathText ?? null
const node = ctx.graph.getNode(result.nodeId)
const after = snapshotTextNode(node, result.text)
@@ -167,18 +160,12 @@ export function createTextActions(ctx: EditorContext) {
const containingInstances = containingInstanceIds(ctx, result.nodeId)
const instanceOverridesBefore = snapshotInstanceOverrides(ctx, containingInstances)
- te.stop()
-
- if (!changed) {
- ctx.state.editingTextId = null
- activeSession = null
- ctx.requestRender()
- return
- }
+ if (!changed) return
updateTextEditNode(result.nodeId, {
text: after.text,
styleRuns: after.styleRuns,
+ textParagraphs: after.textParagraphs,
...sizeChanges
})
const afterPathText = snapshotPathText(
@@ -189,8 +176,6 @@ export function createTextActions(ctx: EditorContext) {
applyTextInstanceOverride(ctx, containingInstances, result.nodeId, after.text)
}
const instanceOverridesAfter = snapshotInstanceOverrides(ctx, containingInstances)
- ctx.state.editingTextId = null
- activeSession = null
// Text a property drives becomes the property's value too, in the same undo step.
ctx.undo.runBatch('Edit text', () => {
@@ -200,6 +185,7 @@ export function createTextActions(ctx: EditorContext) {
ctx.graph.updateNode(result.nodeId, {
text: after.text,
styleRuns: after.styleRuns,
+ textParagraphs: after.textParagraphs,
...after.size,
...afterPathText
})
@@ -210,6 +196,7 @@ export function createTextActions(ctx: EditorContext) {
ctx.graph.updateNode(result.nodeId, {
text: before.text,
styleRuns: before.styleRuns,
+ textParagraphs: before.textParagraphs,
...before.size,
...beforePathText
})
@@ -221,5 +208,41 @@ export function createTextActions(ctx: EditorContext) {
})
}
- return { startTextEditing, updateTextEditNode, commitTextEdit }
+ function commitTextEdit() {
+ const te = ctx.getTextEditor()
+ if (!te?.isActive) {
+ ctx.state.editingTextId = null
+ activeSession = null
+ return
+ }
+ const textState = te.state
+ if (textState) recordTextEdit(textState)
+ te.stop()
+ ctx.state.editingTextId = null
+ activeSession = null
+ ctx.requestRender()
+ }
+
+ /**
+ * Runs a change to the text being edited as an undo step of its own: what was typed before it
+ * becomes a step first, and the edit then goes on from the text the change leaves, which an
+ * undo or redo can also be.
+ */
+ function runTextEditStep(change: () => void) {
+ const te = ctx.getTextEditor()
+ const textState = te?.isActive ? te.state : null
+ if (!te || !textState) {
+ change()
+ return
+ }
+ recordTextEdit(textState)
+ change()
+ const node = ctx.graph.getNode(textState.nodeId)
+ if (!node) return
+ activeSession = createTextEditSession(node)
+ te.syncToNode(node)
+ ctx.requestRender()
+ }
+
+ return { startTextEditing, updateTextEditNode, commitTextEdit, runTextEditStep }
}
diff --git a/packages/core/src/editor/text/session.ts b/packages/core/src/editor/text/session.ts
index 911caebf6..16be762e0 100644
--- a/packages/core/src/editor/text/session.ts
+++ b/packages/core/src/editor/text/session.ts
@@ -1,14 +1,16 @@
-import type { Paragraph } from 'canvaskit-wasm'
import { isEqual } from 'es-toolkit/predicate'
-import type { SceneNode, StyleRun } from '@open-pencil/scene-graph'
+import type { SceneNode, StyleRun, TextParagraphStyle } from '@open-pencil/scene-graph'
import { copyDerivedGlyphs, copyGeometryPaths, copyStyleRuns } from '@open-pencil/scene-graph/copy'
+import type { TextLayout } from '#core/canvas/text/layout'
+
export type TextEditSizeSnapshot = Partial<Pick<SceneNode, 'width' | 'height'>>
export type TextEditSnapshot = {
text: string
styleRuns: StyleRun[]
+ textParagraphs: TextParagraphStyle[]
size?: TextEditSizeSnapshot
}
@@ -27,6 +29,7 @@ export function createTextEditSession(node: SceneNode): TextEditSession {
before: {
text: node.text,
styleRuns: copyStyleRuns(node.styleRuns),
+ textParagraphs: structuredClone(node.textParagraphs),
size: { width: node.width, height: node.height }
},
beforePathText: node.textPathData
@@ -44,13 +47,14 @@ export function snapshotTextNode(node: SceneNode | undefined, fallbackText = '')
return {
text: node?.text ?? fallbackText,
styleRuns: node ? copyStyleRuns(node.styleRuns) : [],
+ textParagraphs: node ? structuredClone(node.textParagraphs) : [],
size: node ? { width: node.width, height: node.height } : undefined
}
}
export function resizeTextNodeForEdit(
node: SceneNode | undefined,
- paragraph: Paragraph | null
+ paragraph: TextLayout | null
): TextEditSizeSnapshot {
if (!node || !paragraph) return {}
const changes: TextEditSizeSnapshot = {}
@@ -69,6 +73,7 @@ export function textSnapshotChanged(before: TextEditSnapshot, after: TextEditSna
return (
before.text !== after.text ||
!styleRunsEqual(before.styleRuns, after.styleRuns) ||
+ !isEqual(before.textParagraphs, after.textParagraphs) ||
(after.size !== undefined && !sizeEqual(before.size ?? {}, after.size))
)
}
diff --git a/packages/core/src/editor/types.ts b/packages/core/src/editor/types.ts
index 486b9f5e1..29a6732bb 100644
--- a/packages/core/src/editor/types.ts
+++ b/packages/core/src/editor/types.ts
@@ -141,6 +141,8 @@ export interface EditorViewState {
zoom: number
navigation: NavigationState
renderVersion: number
+ /** Bumped when the caret or selection of the text being edited moves, which changes nothing else. */
+ textSelectionVersion: number
enteredContainerId: string | null
nodeEditState?: RenderOverlays['nodeEditState'] | null
cursorCanvasX?: number | null
diff --git a/packages/core/src/figma-api/accessors/text.ts b/packages/core/src/figma-api/accessors/text.ts
index 9c917078f..fea1dbef1 100644
--- a/packages/core/src/figma-api/accessors/text.ts
+++ b/packages/core/src/figma-api/accessors/text.ts
@@ -1,4 +1,4 @@
-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import type { SceneGraph, SceneNode, TextParagraphSpacingField } from '@open-pencil/scene-graph'
import {
nodeId,
@@ -12,9 +12,12 @@ import {
getFontName,
getLetterSpacing,
getLineHeight,
+ getParagraphSpacing,
letterSpacingValue,
lineHeightValue,
+ paragraphStylesForCharacters,
setFontName,
+ spacingProblem,
type FigmaLetterSpacing,
type FigmaLineHeight
} from '#core/figma-api/text'
@@ -23,6 +26,25 @@ function graph(target: ProxyThis, internals: NodeProxyInternals): SceneGraph {
return target[internals.graph] as SceneGraph
}
+/**
+ * Getter/setter pair for a spacing Figma keeps at zero or more. It reads `mixed` while paragraphs
+ * differ, and setting it changes the text's own value, which paragraphs with theirs keep.
+ */
+function spacing(internals: NodeProxyInternals, name: TextParagraphSpacingField, mixed: symbol) {
+ return {
+ get(this: ProxyThis): number | symbol {
+ return getParagraphSpacing(raw(this, internals), name, mixed)
+ },
+ set(this: ProxyThis, value: number) {
+ const invalid = spacingProblem(value)
+ if (invalid) {
+ throw new Error(`in set_${name}: Property "${name}" failed validation: ${invalid}`)
+ }
+ updateNode(this, internals, { [name]: value })
+ }
+ }
+}
+
/** Getter/setter pair for a text property stored verbatim on the node. */
function field<Field extends keyof SceneNode>(internals: NodeProxyInternals, name: Field) {
return {
@@ -37,7 +59,8 @@ function field<Field extends keyof SceneNode>(internals: NodeProxyInternals, nam
export function installTextNodeProxyAccessors(
prototype: object,
- internals: NodeProxyInternals
+ internals: NodeProxyInternals,
+ mixed: symbol
): void {
Object.defineProperties(prototype, {
characters: {
@@ -45,7 +68,8 @@ export function installTextNodeProxyAccessors(
return raw(this, internals).text
},
set(this: ProxyThis, value: string) {
- updateNode(this, internals, { text: value })
+ const textParagraphs = paragraphStylesForCharacters(raw(this, internals), value)
+ updateNode(this, internals, { text: value, textParagraphs })
}
},
fontName: {
@@ -93,6 +117,10 @@ export function installTextNodeProxyAccessors(
textCase: field(internals, 'textCase'),
textDecoration: field(internals, 'textDecoration'),
maxLines: field(internals, 'maxLines'),
+ listSpacing: spacing(internals, 'listSpacing', mixed),
+ paragraphSpacing: spacing(internals, 'paragraphSpacing', mixed),
+ paragraphIndent: spacing(internals, 'paragraphIndent', mixed),
+ hangingList: field(internals, 'hangingList'),
textTruncation: field(internals, 'textTruncation'),
autoRename: field(internals, 'autoRename')
})
diff --git a/packages/core/src/figma-api/compatibility.ts b/packages/core/src/figma-api/compatibility.ts
index 01d8fec59..50e6c9c04 100644
--- a/packages/core/src/figma-api/compatibility.ts
+++ b/packages/core/src/figma-api/compatibility.ts
@@ -108,3 +108,36 @@ const _slotSurfaceMatch: SlotSurfaceMatch = true
// `Effect` here is Figma's plugin-typings union; OpenPencil reads and writes a subset of it.
type EffectShapeMatch = Expect<Extends<FigmaNodeProxy['effects'][number], Effect>>
const _effectShapeMatch: EffectShapeMatch = true
+
+type TextListKeys =
+ | 'setRangeListOptions'
+ | 'setRangeIndentation'
+ | 'setRangeListSpacing'
+ | 'setRangeParagraphSpacing'
+ | 'setRangeParagraphIndent'
+ | 'hangingList'
+type TextListSurfaceMatch = Expect<
+ Extends<Pick<FigmaNodeProxy, TextListKeys>, Pick<TextNode, TextListKeys>>
+>
+const _textListSurfaceMatch: TextListSurfaceMatch = true
+
+// Figma's mixed values are its own `figma.mixed` unique symbol; ours are a plain symbol.
+type WithoutMixed<T> = T extends (...args: infer A) => infer R
+ ? (...args: A) => Exclude<R, symbol>
+ : Exclude<T, symbol>
+type TextMixedKeys =
+ | 'getRangeListOptions'
+ | 'getRangeIndentation'
+ | 'getRangeListSpacing'
+ | 'getRangeParagraphSpacing'
+ | 'getRangeParagraphIndent'
+ | 'listSpacing'
+ | 'paragraphSpacing'
+ | 'paragraphIndent'
+type TextMixedMatch = Expect<
+ Extends<
+ { [K in TextMixedKeys]: WithoutMixed<FigmaNodeProxy[K]> },
+ { [K in TextMixedKeys]: WithoutMixed<TextNode[K]> }
+ >
+>
+const _textMixedMatch: TextMixedMatch = true
diff --git a/packages/core/src/figma-api/proxy.ts b/packages/core/src/figma-api/proxy.ts
index f315239a3..384ffa8a2 100644
--- a/packages/core/src/figma-api/proxy.ts
+++ b/packages/core/src/figma-api/proxy.ts
@@ -166,6 +166,10 @@ export class FigmaNodeProxy {
declare textCase: string
declare textDecoration: string
declare maxLines: number | null
+ declare listSpacing: number | symbol
+ declare paragraphSpacing: number | symbol
+ declare paragraphIndent: number | symbol
+ declare hangingList: boolean
declare textTruncation: string
declare autoRename: boolean
@@ -204,6 +208,72 @@ export class FigmaNodeProxy {
TextProxy.deleteCharacters(this[INTERNAL_GRAPH], this._raw(), start, end)
}
+ getRangeListOptions(start: number, end: number): TextListOptions | symbol {
+ return TextProxy.getRangeListOptions(this._raw(), start, end, MIXED)
+ }
+
+ setRangeListOptions(start: number, end: number, value: TextListOptions): void {
+ assertNodeEditable(this[INTERNAL_GRAPH], this[INTERNAL_ID])
+ TextProxy.setRangeListOptions(this[INTERNAL_GRAPH], this._raw(), start, end, value)
+ }
+
+ getRangeIndentation(start: number, end: number): number | symbol {
+ return TextProxy.getRangeIndentation(this._raw(), start, end, MIXED)
+ }
+
+ setRangeIndentation(start: number, end: number, value: number): void {
+ assertNodeEditable(this[INTERNAL_GRAPH], this[INTERNAL_ID])
+ TextProxy.setRangeIndentation(this[INTERNAL_GRAPH], this._raw(), start, end, value)
+ }
+
+ getRangeListSpacing(start: number, end: number): number | symbol {
+ return TextProxy.getRangeParagraphSpacing(this._raw(), 'listSpacing', start, end, MIXED)
+ }
+
+ setRangeListSpacing(start: number, end: number, value: number): void {
+ assertNodeEditable(this[INTERNAL_GRAPH], this[INTERNAL_ID])
+ TextProxy.setRangeParagraphSpacing(
+ this[INTERNAL_GRAPH],
+ this._raw(),
+ 'listSpacing',
+ start,
+ end,
+ value
+ )
+ }
+
+ getRangeParagraphSpacing(start: number, end: number): number | symbol {
+ return TextProxy.getRangeParagraphSpacing(this._raw(), 'paragraphSpacing', start, end, MIXED)
+ }
+
+ setRangeParagraphSpacing(start: number, end: number, value: number): void {
+ assertNodeEditable(this[INTERNAL_GRAPH], this[INTERNAL_ID])
+ TextProxy.setRangeParagraphSpacing(
+ this[INTERNAL_GRAPH],
+ this._raw(),
+ 'paragraphSpacing',
+ start,
+ end,
+ value
+ )
+ }
+
+ getRangeParagraphIndent(start: number, end: number): number | symbol {
+ return TextProxy.getRangeParagraphSpacing(this._raw(), 'paragraphIndent', start, end, MIXED)
+ }
+
+ setRangeParagraphIndent(start: number, end: number, value: number): void {
+ assertNodeEditable(this[INTERNAL_GRAPH], this[INTERNAL_ID])
+ TextProxy.setRangeParagraphSpacing(
+ this[INTERNAL_GRAPH],
+ this._raw(),
+ 'paragraphIndent',
+ start,
+ end,
+ value
+ )
+ }
+
get isMask(): boolean {
return this._raw().isMask
}
@@ -477,7 +547,7 @@ const proxyInternals = {
}
installStrokeNodeProxyAccessors(FigmaNodeProxy.prototype, proxyInternals)
-installTextNodeProxyAccessors(FigmaNodeProxy.prototype, proxyInternals)
+installTextNodeProxyAccessors(FigmaNodeProxy.prototype, proxyInternals, MIXED)
installLayoutNodeProxyAccessors(FigmaNodeProxy.prototype, proxyInternals)
installVariableModeNodeProxyAccessors(FigmaNodeProxy.prototype, proxyInternals)
installComponentPropertyAccessors(FigmaNodeProxy.prototype, proxyInternals)
diff --git a/packages/core/src/figma-api/text.ts b/packages/core/src/figma-api/text.ts
index 50785751a..6025b8478 100644
--- a/packages/core/src/figma-api/text.ts
+++ b/packages/core/src/figma-api/text.ts
@@ -1,5 +1,25 @@
-import { recordInstanceOverride } from '@open-pencil/scene-graph'
-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import { upperFirst } from 'es-toolkit/string'
+
+import {
+ MAX_LIST_INDENTATION,
+ paragraphIndexAt,
+ paragraphStyleAt,
+ paragraphStylesAfterEdit,
+ paragraphStylesInRange,
+ recordInstanceOverride,
+ sharedParagraphSpacing,
+ textParagraphRanges,
+ trimParagraphStyles,
+ withIndentation,
+ withListType,
+ withParagraphSpacing
+} from '@open-pencil/scene-graph'
+import type {
+ SceneGraph,
+ SceneNode,
+ TextParagraphSpacingField,
+ TextParagraphStyle
+} from '@open-pencil/scene-graph'
import { styleNameToWeight, weightToStyleName, type FigmaFontName } from './fonts'
@@ -62,8 +82,15 @@ export function insertCharacters(
characters: string
): void {
const text = node.text.slice(0, start) + characters + node.text.slice(start)
- graph.updateNode(node.id, { text })
- recordInstanceOverride(graph, node.id, ['text'])
+ const textParagraphs = paragraphStylesAfterEdit(
+ node.textParagraphs,
+ node.text,
+ start,
+ start,
+ characters
+ )
+ graph.updateNode(node.id, { text, textParagraphs })
+ recordInstanceOverride(graph, node.id, ['text', 'textParagraphs'])
}
export function deleteCharacters(
@@ -73,6 +100,176 @@ export function deleteCharacters(
end: number
): void {
const text = node.text.slice(0, start) + node.text.slice(end)
- graph.updateNode(node.id, { text })
- recordInstanceOverride(graph, node.id, ['text'])
+ const textParagraphs = paragraphStylesAfterEdit(node.textParagraphs, node.text, start, end, '')
+ graph.updateNode(node.id, { text, textParagraphs })
+ recordInstanceOverride(graph, node.id, ['text', 'textParagraphs'])
+}
+
+type ListType = TextListOptions['type']
+const LIST_TYPES: ReadonlySet<string> = new Set<ListType>(['NONE', 'ORDERED', 'UNORDERED'])
+
+/** Figma's checks on a character range, with its messages. */
+function assertTextRange(method: string, node: SceneNode, start: number, end: number): void {
+ if (start < 0) {
+ throw new Error(
+ `in ${method}: Property "start" failed validation: Number must be greater than or equal to 0`
+ )
+ }
+ if (end <= start) {
+ throw new Error(`in ${method}: Empty range selected. 'end' must be greater than 'start'`)
+ }
+ if (start >= node.text.length || end > node.text.length) {
+ throw new Error(
+ `in ${method}: Range outside of available characters. 'start' must be less than ` +
+ `node.characters.length and 'end' must be less than or equal to node.characters.length`
+ )
+ }
+}
+
+/** The styles of the paragraphs a range touches: a newline belongs to the paragraph it ends. */
+function rangeParagraphStyles(node: SceneNode, start: number, end: number): TextParagraphStyle[] {
+ const first = paragraphIndexAt(node.text, start)
+ const last = paragraphIndexAt(node.text, end - 1)
+ return Array.from({ length: last - first + 1 }, (_, index) =>
+ paragraphStyleAt(node.textParagraphs, first + index)
+ )
+}
+
+function updateParagraphs(
+ graph: SceneGraph,
+ node: SceneNode,
+ start: number,
+ end: number,
+ change: (style: TextParagraphStyle) => TextParagraphStyle
+): void {
+ const textParagraphs = paragraphStylesInRange(node.textParagraphs, node.text, start, end, change)
+ graph.updateNode(node.id, { textParagraphs })
+ recordInstanceOverride(graph, node.id, ['textParagraphs'])
+}
+
+export function getRangeListOptions(
+ node: SceneNode,
+ start: number,
+ end: number,
+ mixed: symbol
+): TextListOptions | symbol {
+ assertTextRange('getRangeListOptions', node, start, end)
+ const types = new Set(rangeParagraphStyles(node, start, end).map((style) => style.listType))
+ const [type] = types
+ return types.size === 1 ? { type } : mixed
+}
+
+export function setRangeListOptions(
+ graph: SceneGraph,
+ node: SceneNode,
+ start: number,
+ end: number,
+ options: TextListOptions
+): void {
+ if (!LIST_TYPES.has(options.type)) {
+ throw new Error(
+ `in setRangeListOptions: Property "options" failed validation: Invalid enum value. ` +
+ `Expected 'NONE' | 'ORDERED' | 'UNORDERED', received '${String(options.type)}' at .type`
+ )
+ }
+ assertTextRange('setRangeListOptions', node, start, end)
+ updateParagraphs(graph, node, start, end, (style) => withListType(style, options.type))
+}
+
+export function getRangeIndentation(
+ node: SceneNode,
+ start: number,
+ end: number,
+ mixed: symbol
+): number | symbol {
+ assertTextRange('getRangeIndentation', node, start, end)
+ const levels = new Set(rangeParagraphStyles(node, start, end).map((style) => style.indentation))
+ const [level] = levels
+ return levels.size === 1 ? level : mixed
+}
+
+/** What Figma reports about an indentation it rejects, or `null`. */
+function indentationProblem(level: number): string | null {
+ if (!Number.isInteger(level)) return 'Expected integer, received float'
+ if (level < 0) return 'Number must be greater than or equal to 0'
+ if (level > MAX_LIST_INDENTATION)
+ return `Number must be less than or equal to ${MAX_LIST_INDENTATION}`
+ return null
+}
+
+export function setRangeIndentation(
+ graph: SceneGraph,
+ node: SceneNode,
+ start: number,
+ end: number,
+ level: number
+): void {
+ const invalid = indentationProblem(level)
+ if (invalid) {
+ throw new Error(`in setRangeIndentation: Property "indentation" failed validation: ${invalid}`)
+ }
+ assertTextRange('setRangeIndentation', node, start, end)
+ updateParagraphs(graph, node, start, end, (style) => withIndentation(style, level))
+}
+
+/**
+ * The paragraphs a spacing range reaches. Unlike list options, Figma counts the paragraph at the
+ * range's end position too, so a range ending where a paragraph starts reaches it.
+ */
+function spacingParagraphs(node: SceneNode, start: number, end: number): [number, number] {
+ return [paragraphIndexAt(node.text, start), paragraphIndexAt(node.text, end)]
+}
+
+/** What Figma reports about a spacing it rejects, or `null`. */
+export function spacingProblem(value: number): string | null {
+ return value >= 0 ? null : 'Number must be greater than or equal to 0'
+}
+
+export function getRangeParagraphSpacing(
+ node: SceneNode,
+ field: TextParagraphSpacingField,
+ start: number,
+ end: number,
+ mixed: symbol
+): number | symbol {
+ assertTextRange(`getRange${upperFirst(field)}`, node, start, end)
+ return sharedParagraphSpacing(node, field, ...spacingParagraphs(node, start, end)) ?? mixed
+}
+
+export function setRangeParagraphSpacing(
+ graph: SceneGraph,
+ node: SceneNode,
+ field: TextParagraphSpacingField,
+ start: number,
+ end: number,
+ value: number
+): void {
+ const method = `setRange${upperFirst(field)}`
+ const invalid = spacingProblem(value)
+ if (invalid) throw new Error(`in ${method}: Property "value" failed validation: ${invalid}`)
+ assertTextRange(method, node, start, end)
+ // Ranges change the paragraphs of their characters; one more reaches the end position's.
+ updateParagraphs(graph, node, start, end + 1, (style) =>
+ withParagraphSpacing(style, field, value)
+ )
+}
+
+/** A text's spacing: one value when every paragraph has it, `mixed` otherwise. */
+export function getParagraphSpacing(
+ node: SceneNode,
+ field: TextParagraphSpacingField,
+ mixed: symbol
+): number | symbol {
+ return sharedParagraphSpacing(node, field) ?? mixed
+}
+
+/** Text replaced whole takes the first paragraph's list style throughout, as in Figma. */
+export function paragraphStylesForCharacters(node: SceneNode, text: string): TextParagraphStyle[] {
+ if (node.textParagraphs.length === 0) return []
+ const first = paragraphStyleAt(node.textParagraphs, 0)
+ const count = textParagraphRanges(text).length
+ return trimParagraphStyles(
+ Array.from({ length: count }, () => first),
+ count
+ )
}
diff --git a/packages/core/src/text/editor.ts b/packages/core/src/text/editor.ts
index 67cb70c48..72064d360 100644
--- a/packages/core/src/text/editor.ts
+++ b/packages/core/src/text/editor.ts
@@ -1,10 +1,11 @@
-import type { CanvasKit, Paragraph } from 'canvaskit-wasm'
+import type { CanvasKit } from 'canvaskit-wasm'
import type { SceneNode } from '@open-pencil/scene-graph'
import type { Rect } from '@open-pencil/scene-graph/primitives'
import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text-direction'
import type { SkiaRenderer } from '#core/canvas'
+import type { TextLayout } from '#core/canvas/text/layout'
export interface TextCaret {
x: number
@@ -17,7 +18,7 @@ export interface TextEditorState {
text: string
cursor: number
selectionAnchor: number | null
- paragraph: Paragraph | null
+ paragraph: TextLayout | null
paragraphFontGeneration: number
textDirection: 'LTR' | 'RTL'
}
@@ -27,6 +28,8 @@ export class TextEditor {
private renderer: SkiaRenderer | null = null
private _state: TextEditorState | null = null
private paragraphNode: SceneNode | null = null
+ /** The edited node as it changed outside the editor, laid out again on the next read. */
+ private staleNode: SceneNode | null = null
caretVisible = true
constructor(ck: CanvasKit) {
@@ -34,7 +37,7 @@ export class TextEditor {
}
private paragraphVerticalOffset(): number {
- const s = this._state
+ const s = this.current()
const node = this.paragraphNode
if (!s?.paragraph || !node) return 0
const available = Math.max(0, node.height - s.paragraph.getHeight())
@@ -48,7 +51,7 @@ export class TextEditor {
}
private prepareMove(extend: boolean): TextEditorState | null {
- const s = this._state
+ const s = this.current()
if (!s) return null
if (extend && s.selectionAnchor === null) s.selectionAnchor = s.cursor
if (!extend) s.selectionAnchor = null
@@ -56,7 +59,7 @@ export class TextEditor {
}
private replaceRange(start: number, end: number, text: string): TextEditorState | null {
- const s = this._state
+ const s = this.current()
if (!s) return null
s.text = s.text.slice(0, start) + text + s.text.slice(end)
s.cursor = start + text.length
@@ -65,14 +68,14 @@ export class TextEditor {
}
private currentLineMetrics() {
- const s = this._state
+ const s = this.current()
if (!s?.paragraph) return null
const lineNum = s.paragraph.getLineNumberAt(s.cursor)
return lineNum < 0 ? null : s.paragraph.getLineMetricsAt(lineNum)
}
private collapseSelectionTo(edge: 0 | 1): boolean {
- const s = this._state
+ const s = this.current()
if (!s || !this.hasSelection()) return false
const range = this.getSelectionRange()
if (range) s.cursor = range[edge]
@@ -81,7 +84,13 @@ export class TextEditor {
}
get state(): TextEditorState | null {
+ return this.current()
+ }
+
+ /** The editing state with its layout brought up to date with the node and its fonts. */
+ private current(): TextEditorState | null {
const state = this._state
+ if (state && this.staleNode) this.rebuildParagraph(this.staleNode)
if (
state &&
this.renderer &&
@@ -124,11 +133,21 @@ export class TextEditor {
this._state.paragraph?.delete()
this._state = null
this.paragraphNode = null
+ this.staleNode = null
return result
}
+ /**
+ * Marks the layout out of date after the edited node changed outside the editor, as a panel
+ * field does while it is dragged; the caret and selection follow on the next read.
+ */
+ invalidateParagraph(node: SceneNode): void {
+ if (this._state?.nodeId === node.id) this.staleNode = node
+ }
+
rebuildParagraph(node: SceneNode): void {
const s = this._state
+ this.staleNode = null
if (!s || !this.renderer) return
s.paragraph?.delete()
this.paragraphNode = node
@@ -137,8 +156,20 @@ export class TextEditor {
s.paragraphFontGeneration = this.renderer.fontGeneration
}
+ /** Takes the node's text back after it changed outside the editor, as an undo does. */
+ syncToNode(node: SceneNode): void {
+ const s = this.current()
+ if (!s) return
+ if (s.text !== node.text) {
+ s.text = node.text
+ s.cursor = Math.min(s.cursor, node.text.length)
+ s.selectionAnchor = null
+ }
+ this.rebuildParagraph(node)
+ }
+
hasSelection(): boolean {
- const s = this._state
+ const s = this.current()
return s !== null && s.selectionAnchor !== null && s.selectionAnchor !== s.cursor
}
@@ -148,7 +179,7 @@ export class TextEditor {
}
getSelectionRange(): [number, number] | null {
- const s = this._state
+ const s = this.current()
if (!s || s.selectionAnchor === null || s.selectionAnchor === s.cursor) return null
const lo = Math.min(s.cursor, s.selectionAnchor)
const hi = Math.max(s.cursor, s.selectionAnchor)
@@ -162,14 +193,14 @@ export class TextEditor {
}
selectAll(): void {
- const s = this._state
+ const s = this.current()
if (!s) return
s.selectionAnchor = 0
s.cursor = s.text.length
}
selectWord(pos: number): void {
- const s = this._state
+ const s = this.current()
if (!s) return
const text = s.text
let start = pos
@@ -181,7 +212,7 @@ export class TextEditor {
}
setCursorAt(x: number, y: number, extend = false): void {
- const s = this._state
+ const s = this.current()
if (!s?.paragraph) return
const pos = s.paragraph.getGlyphPositionAtCoordinate(x, this.paragraphY(y)).pos
if (extend) {
@@ -193,7 +224,7 @@ export class TextEditor {
}
selectLine(pos: number): void {
- const s = this._state
+ const s = this.current()
if (!s?.paragraph) return
const lineNum = s.paragraph.getLineNumberAt(pos)
if (lineNum < 0) return
@@ -204,21 +235,21 @@ export class TextEditor {
}
selectWordAt(x: number, y: number): void {
- const s = this._state
+ const s = this.current()
if (!s?.paragraph) return
const pos = s.paragraph.getGlyphPositionAtCoordinate(x, this.paragraphY(y)).pos
this.selectWord(pos)
}
selectLineAt(x: number, y: number): void {
- const s = this._state
+ const s = this.current()
if (!s?.paragraph) return
const pos = s.paragraph.getGlyphPositionAtCoordinate(x, this.paragraphY(y)).pos
this.selectLine(pos)
}
insert(text: string, node: SceneNode): void {
- const s = this._state
+ const s = this.current()
if (!s) return
const range = this.getSelectionRange() ?? [s.cursor, s.cursor]
this.replaceRange(range[0], range[1], text)
@@ -226,7 +257,7 @@ export class TextEditor {
}
backspace(node: SceneNode): void {
- const s = this._state
+ const s = this.current()
if (!s) return
const range = this.getSelectionRange() ?? (s.cursor > 0 ? [s.cursor - 1, s.cursor] : null)
if (range) this.replaceRange(range[0], range[1], '')
@@ -234,7 +265,7 @@ export class TextEditor {
}
delete(node: SceneNode): void {
- const s = this._state
+ const s = this.current()
if (!s) return
const range =
this.getSelectionRange() ?? (s.cursor < s.text.length ? [s.cursor, s.cursor + 1] : null)
@@ -243,7 +274,7 @@ export class TextEditor {
}
private moveHorizontal(extend: boolean, visualDirection: 'left' | 'right'): void {
- const s = this._state
+ const s = this.current()
if (!s) return
if (!extend && this.collapseSelectionTo(visualDirection === 'left' ? 0 : 1)) return
this.prepareMove(extend)
@@ -262,7 +293,7 @@ export class TextEditor {
}
private moveVertical(extend: boolean, edge: 'up' | 'down'): void {
- const s = this._state
+ const s = this.current()
if (!s?.paragraph) return
this.prepareMove(extend)
const caret = this.getCaretRect()
@@ -281,7 +312,7 @@ export class TextEditor {
}
private moveToLineEdge(extend: boolean, edge: 'start' | 'end'): void {
- const s = this._state
+ const s = this.current()
if (!s?.paragraph) return
this.prepareMove(extend)
const metrics = this.currentLineMetrics()
@@ -344,7 +375,7 @@ export class TextEditor {
* The caret of empty text. CanvasKit lays out no line for an empty paragraph, so a line
* holding one space gives the caret's height, and the alignment its place.
*/
- private emptyCaret(paragraph: Paragraph): TextCaret | null {
+ private emptyCaret(paragraph: TextLayout): TextCaret | null {
const node = this.paragraphNode
const line = paragraph.getLineMetrics().at(0)
if (line) {
@@ -366,7 +397,7 @@ export class TextEditor {
}
getCaretRect(): TextCaret | null {
- const s = this._state
+ const s = this.current()
if (!s?.paragraph) return null
const text = s.text
@@ -374,41 +405,14 @@ export class TextEditor {
if (text.length === 0) return this.emptyCaret(s.paragraph)
- let lo: number
- let hi: number
- let useRight = false
-
- if (cursor === 0) {
- lo = 0
- hi = 1
- useRight = s.textDirection === 'RTL'
- } else if (cursor >= text.length) {
- lo = text.length - 1
- hi = text.length
- useRight = s.textDirection !== 'RTL'
- } else {
- lo = cursor
- hi = cursor + 1
- }
-
- const rects = s.paragraph.getRectsForRange(
- lo,
- hi,
- this.ck.RectHeightStyle.Max,
- this.ck.RectWidthStyle.Tight
- )
- if (rects.length === 0) return null
- const [left, top, right, bottom] = rects[0].rect
+ const caret = s.paragraph.getCaretRect(cursor, s.textDirection === 'RTL')
+ if (!caret) return null
const offsetY = this.paragraphVerticalOffset()
- return {
- x: useRight ? right : left,
- y0: top + offsetY,
- y1: bottom + offsetY
- }
+ return { x: caret.x, y0: caret.top + offsetY, y1: caret.bottom + offsetY }
}
getSelectionRects(): Rect[] {
- const s = this._state
+ const s = this.current()
if (!s?.paragraph) return []
const range = this.getSelectionRange()
if (!range) return []
diff --git a/packages/core/src/text/opentype.ts b/packages/core/src/text/opentype.ts
index cd70e371e..d9487fc9f 100644
--- a/packages/core/src/text/opentype.ts
+++ b/packages/core/src/text/opentype.ts
@@ -204,6 +204,18 @@ export function glyphOutlineSourceSync(family: string, style: string): GlyphOutl
}
}
+/** The advance of glyph `glyphId` of a loaded font at `fontSize`, or `null` when it has none. */
+export function glyphAdvanceSync(
+ family: string,
+ style: string,
+ glyphId: number,
+ fontSize: number
+): number | null {
+ const font = getParsedFont(family, style)
+ const glyph = font?.glyphs.get(glyphId)
+ return font && glyph ? glyphAdvanceWidth(font, glyph, fontSize) : null
+}
+
export async function probeGlyphOutlineCommands(
family: string,
style: string,
diff --git a/packages/core/tests/canvas/text/derived-glyphs.test.ts b/packages/core/tests/canvas/text/derived-glyphs.test.ts
new file mode 100644
index 000000000..96f8853a4
--- /dev/null
+++ b/packages/core/tests/canvas/text/derived-glyphs.test.ts
@@ -0,0 +1,59 @@
+import { expect, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { SkiaRenderer } from '#core/canvas/renderer'
+import { drawDerivedText } from '#core/canvas/text/derived'
+import { getCanvasKit } from '#core/canvaskit'
+
+/** A unit square in the saved glyph command format: move, three lines, and the end. */
+function squareCommandsBlob(): Uint8Array {
+ const blob = new Uint8Array(1 + 4 * 9 + 1)
+ const view = new DataView(blob.buffer)
+ const corners = [
+ [1, 0, 0],
+ [2, 1, 0],
+ [2, 1, 1],
+ [2, 0, 1]
+ ]
+ for (const [index, [command, x, y]] of corners.entries()) {
+ blob[index * 9] = command
+ view.setFloat32(index * 9 + 1, x, true)
+ view.setFloat32(index * 9 + 5, y, true)
+ }
+ return blob
+}
+
+test('decodes each saved glyph once, however often its text is recorded', async () => {
+ const ck = await getCanvasKit()
+ const graph = new SceneGraph()
+ const text = graph.createNode('TEXT', graph.getPages()[0].id, {
+ text: 'AB',
+ width: 40,
+ height: 20,
+ fontSize: 10,
+ derivedTextGlyphs: [
+ { commandsBlob: squareCommandsBlob(), x: 0, y: 10, fontSize: 10, firstCharacter: 0 },
+ { commandsBlob: squareCommandsBlob(), x: 20, y: 10, fontSize: 10, firstCharacter: 1 }
+ ]
+ })
+ const renderer = new SkiaRenderer(ck, expectDefined(ck.MakeSurface(1, 1), 'surface'))
+ const recorder = new ck.PictureRecorder()
+ try {
+ const record = () => {
+ drawDerivedText(renderer, recorder.beginRecording(ck.LTRBRect(0, 0, 40, 20)), text)
+ recorder.finishRecordingAsPicture().delete()
+ }
+ record()
+ const decoded = [...renderer.derivedGlyphPathCache.values()]
+ expect(decoded).toHaveLength(2)
+ record()
+ // Recording the text again draws the outlines decoded the first time.
+ expect([...renderer.derivedGlyphPathCache.values()]).toEqual(decoded)
+ } finally {
+ recorder.delete()
+ renderer.destroy()
+ }
+})
diff --git a/packages/core/tests/canvas/text/lists.test.ts b/packages/core/tests/canvas/text/lists.test.ts
new file mode 100644
index 000000000..175e35431
--- /dev/null
+++ b/packages/core/tests/canvas/text/lists.test.ts
@@ -0,0 +1,199 @@
+import { beforeAll, describe, expect, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+
+import type { ShapedText, ShapedTextGlyph } from '@open-pencil/fig/node-change'
+import { SceneGraph, type SceneNode, type TextParagraphStyle } from '@open-pencil/scene-graph'
+
+import { buildParagraph } from '#core/canvas/text/layout/build'
+import { withFigExportRuntime } from '#core/canvas/text/shape'
+import { getCanvasKit } from '#core/canvaskit'
+import { fontManager } from '#core/text/fonts'
+import { glyphAdvanceSync } from '#core/text/opentype'
+
+const ul = (indentation = 1): TextParagraphStyle => ({ listType: 'UNORDERED', indentation })
+const ol = (indentation = 1): TextParagraphStyle => ({ listType: 'ORDERED', indentation })
+const plain: TextParagraphStyle = { listType: 'NONE', indentation: 0 }
+
+async function shape(props: Partial<SceneNode>): Promise<ShapedText> {
+ const graph = new SceneGraph()
+ const node = graph.createNode('TEXT', graph.getPages()[0].id, {
+ fontFamily: 'Inter',
+ fontSize: 16,
+ width: 400,
+ height: 400,
+ textAutoResize: 'HEIGHT',
+ ...props
+ })
+ const shaped = await withFigExportRuntime(graph, await getCanvasKit(), async (runtime) =>
+ runtime.shapeText(node)
+ )
+ return expectDefined(shaped, 'shaped text')
+}
+
+/** Marker glyphs by line, from their baselines: they draw no character of the text. */
+function markersOn(shaped: ShapedText, line: number): ShapedTextGlyph[] {
+ const y = shaped.baselines[line].position.y
+ return shaped.glyphs.filter((glyph) => glyph.firstCharacter === undefined && glyph.y === y)
+}
+
+function lineStarts(shaped: ShapedText): number[] {
+ return shaped.baselines.map((baseline) => baseline.position.x)
+}
+
+// The layout rules below were measured in live Figma (2026-10-09) from the glyphs it saves.
+describe('text lists', () => {
+ beforeAll(async () => {
+ const inter = expectDefined(
+ await fontManager.fetchBundledFont('/Inter-Regular.ttf'),
+ 'bundled Inter font'
+ )
+ fontManager.markLoaded('Inter', 'Regular', inter)
+ })
+
+ test('indents items one and a half ems per level and centres bullets in the indent', async () => {
+ const shaped = await shape({
+ text: 'Intro\nOne\nTwo\nNested',
+ textParagraphs: [plain, ul(), ul(), ul(2)]
+ })
+ expect(lineStarts(shaped)).toEqual([0, 24, 24, 48])
+ expect(markersOn(shaped, 0)).toEqual([])
+ for (const [line, centre] of [
+ [1, 12],
+ [3, 36]
+ ] as const) {
+ const [bullet] = markersOn(shaped, line)
+ expect(bullet.x + bullet.advance / 2).toBeCloseTo(centre, 2)
+ expect(bullet.commands?.length).toBeGreaterThan(0)
+ }
+ })
+
+ test('ends numbers a third of an em before the text and widens them past nine', async () => {
+ const short = await shape({ text: 'a\nb', textParagraphs: [ol(), ol()] })
+ const [number, period] = markersOn(short, 0)
+ expect(short.baselines[0].position.x).toBe(24)
+ expect(period.x + period.advance).toBeCloseTo(24 - 16 / 3, 2)
+ expect(number.x).toBeLessThan(period.x)
+
+ const long = await shape({
+ text: Array.from({ length: 12 }, (_, index) => `item${index + 1}`).join('\n'),
+ textParagraphs: Array.from({ length: 12 }, () => ol())
+ })
+ const digit = expectDefined(glyphAdvanceSync('Inter', 'Regular', 48, 16), 'glyph 48')
+ const start = 24 + digit
+ expect(new Set(lineStarts(long))).toEqual(new Set([start]))
+ const ten = markersOn(long, 9)
+ expect(ten).toHaveLength(3)
+ const last = expectDefined(ten.at(-1), 'period')
+ expect(last.x + last.advance).toBeCloseTo(start - 16 / 3, 2)
+ })
+
+ test('hangs wrapped lines of an item at its indent and marks only its first line', async () => {
+ const shaped = await shape({
+ text: 'a list item that wraps over several lines\nshort',
+ width: 120,
+ textParagraphs: [ul(), ul()]
+ })
+ expect(shaped.baselines.length).toBeGreaterThan(2)
+ for (const start of lineStarts(shaped)) expect(start).toBe(24)
+ expect(markersOn(shaped, 0)).toHaveLength(1)
+ expect(markersOn(shaped, 1)).toHaveLength(0)
+ })
+
+ test('spaces list items by list spacing and other paragraphs by paragraph spacing', async () => {
+ const base = await shape({ text: 'p1\np2\nl1\nl2\np3', textParagraphs: [plain, plain, ul(), ul()] })
+ const spaced = await shape({
+ text: 'p1\np2\nl1\nl2\np3',
+ textParagraphs: [plain, plain, ul(), ul()],
+ listSpacing: 10,
+ paragraphSpacing: 7
+ })
+ const gaps = (shaped: ShapedText) =>
+ shaped.baselines.slice(1).map((line, index) => line.position.y - shaped.baselines[index].position.y)
+ expect(gaps(spaced).map((gap, index) => gap - gaps(base)[index])).toEqual([7, 7, 10, 7])
+ })
+
+ test('indents the first line of plain paragraphs, not list items', async () => {
+ const shaped = await shape({
+ text: 'first paragraph wraps here\nsecond\nitem',
+ width: 140,
+ paragraphIndent: 20,
+ textParagraphs: [plain, plain, ul()]
+ })
+ const starts = lineStarts(shaped)
+ expect(starts[0]).toBe(20)
+ expect(starts[1]).toBe(0)
+ expect(starts.at(-2)).toBe(20)
+ expect(starts.at(-1)).toBe(24)
+ })
+
+ test('spaces each paragraph by its own spacing, falling back to the text\'s', async () => {
+ const text = 'P1\nP2\nI1\nI2\nP3\nP4'
+ const gaps = (shaped: ShapedText) =>
+ shaped.baselines.slice(1).map((line, index) => {
+ return line.position.y - shaped.baselines[index].position.y
+ })
+ const flat = gaps(await shape({ text }))
+ const spaced = gaps(
+ await shape({
+ text,
+ paragraphSpacing: 10,
+ listSpacing: 4,
+ textParagraphs: [
+ plain,
+ { ...plain, paragraphSpacing: 25 },
+ ol(),
+ { ...ol(), paragraphSpacing: 40 },
+ { ...plain, listSpacing: 33 }
+ ]
+ })
+ )
+ // Live Figma (2026-10-10): the space after a paragraph is its own; list spacing applies
+ // only between two items, and a plain paragraph's list spacing does nothing.
+ expect(spaced.map((gap, index) => gap - flat[index])).toEqual([10, 25, 4, 40, 10])
+ })
+
+ test('indents the first line of each paragraph by its own indent', async () => {
+ const shaped = await shape({
+ text: 'A\nB\nC',
+ paragraphIndent: 8,
+ textParagraphs: [plain, { ...plain, paragraphIndent: 30 }]
+ })
+ expect(lineStarts(shaped)).toEqual([8, 30, 8])
+ })
+
+ test('hangs markers outside the box for a hanging list', async () => {
+ const shaped = await shape({ text: 'A\nB', textParagraphs: [ul(), ul()], hangingList: true })
+ expect(lineStarts(shaped)).toEqual([0, 0])
+ const [bullet] = markersOn(shaped, 0)
+ expect(bullet.x + bullet.advance / 2).toBeCloseTo(-12, 2)
+ })
+
+ test('gives a truncated item back its lines when a wider layout has room', async () => {
+ const ck = await getCanvasKit()
+ const fontProvider = ck.TypefaceFontProvider.Make()
+ fontManager.attachProvider(ck, fontProvider)
+ const graph = new SceneGraph()
+ const node = graph.createNode('TEXT', graph.getPages()[0].id, {
+ fontFamily: 'Inter',
+ fontSize: 16,
+ text: `Alpha beta\n${'word '.repeat(60).trim()}`,
+ textParagraphs: [ul(), ul()],
+ textTruncation: 'ENDING',
+ maxLines: 4
+ })
+ const layout = buildParagraph({ ck, fontProvider, fontsLoaded: true }, node)
+ try {
+ layout.layout(200)
+ const wide = layout.getLineMetrics().length
+ layout.layout(60)
+ layout.layout(200)
+ expect(wide).toBe(4)
+ expect(layout.getLineMetrics()).toHaveLength(wide)
+ } finally {
+ layout.delete()
+ fontManager.detachProvider(fontProvider)
+ fontProvider.delete()
+ }
+ })
+})
diff --git a/packages/core/tests/editor/structure/flatten.test.ts b/packages/core/tests/editor/structure/flatten.test.ts
index 3347ccaf2..3a75a95d6 100644
--- a/packages/core/tests/editor/structure/flatten.test.ts
+++ b/packages/core/tests/editor/structure/flatten.test.ts
@@ -27,7 +27,7 @@ async function createEditorWithRenderer() {
editor.dispose()
renderer.destroy()
})
- return { editor }
+ return { editor, renderer }
}
async function loadInterRegular() {
@@ -201,6 +201,40 @@ describe('flattenSelected', () => {
expect(editor.graph.getNode(text.id)).toBeUndefined()
})
+ // Saved glyphs draw a decoration on one baseline; outlines carry none, so lines don't matter.
+ test.each(['NONE', 'UNDERLINE'] as const)(
+ 'flattens a list with its bullets, as the canvas draws it (%s)',
+ async (textDecoration) => {
+ await loadInterRegular()
+ const { editor, renderer } = await createEditorWithRenderer()
+ await renderer.loadFonts()
+ const pageId = editor.state.currentPageId
+ const text = editor.graph.createNode('TEXT', pageId, {
+ x: 100,
+ text: 'One\nTwo',
+ fontFamily: 'Inter',
+ fontWeight: 400,
+ fontSize: 16,
+ width: 120,
+ height: 40,
+ textDecoration,
+ textParagraphs: [
+ { listType: 'UNORDERED', indentation: 1 },
+ { listType: 'UNORDERED', indentation: 1 }
+ ]
+ })
+
+ editor.select([text.id])
+ editor.flattenSelected()
+
+ const [vectorId] = [...editor.state.selectedIds]
+ const vector = editor.graph.getNode(vectorId)
+ // The bullets sit in the first 24px of indent, left of the items' text.
+ expect(vector?.x).toBeGreaterThan(106)
+ expect(vector?.x).toBeLessThan(112)
+ }
+ )
+
test('wraps loaded text style runs as outlines', async () => {
await loadInterRegular()
await loadInterBold()
diff --git a/packages/core/tests/editor/view-state.test.ts b/packages/core/tests/editor/view-state.test.ts
index 3e451fcb6..c4ce2b10c 100644
--- a/packages/core/tests/editor/view-state.test.ts
+++ b/packages/core/tests/editor/view-state.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, test } from 'bun:test'
import {
copyEditorViewState,
createDefaultEditorState,
+ createEditor,
createDefaultEditorViewState,
pickEditorViewState
} from '@open-pencil/core/editor'
@@ -34,4 +35,16 @@ describe('editor state ownership', () => {
expect(source.pageColor.r).not.toBe(0.5)
expect(source.navigation.phase).toBe('idle')
})
+
+ test('moves a text selection without counting as a document change', () => {
+ const editor = createEditor()
+ const { sceneVersion, canvasVersion, renderVersion } = editor.state
+ editor.textSelectionChanged()
+ expect(editor.state.textSelectionVersion).toBe(1)
+ expect(editor.state.renderVersion).toBe(renderVersion + 1)
+ // Saving, recovery, and the canvas's recorded pictures follow these; a caret moves none.
+ expect(editor.state.sceneVersion).toBe(sceneVersion)
+ expect(editor.state.canvasVersion).toBe(canvasVersion)
+ editor.dispose()
+ })
})
diff --git a/packages/core/tests/figma-api/text-autosize.test.ts b/packages/core/tests/figma-api/text/autosize.test.ts
similarity index 100%
rename from packages/core/tests/figma-api/text-autosize.test.ts
rename to packages/core/tests/figma-api/text/autosize.test.ts
diff --git a/packages/core/tests/figma-api/text/lists.test.ts b/packages/core/tests/figma-api/text/lists.test.ts
new file mode 100644
index 000000000..eb8491be6
--- /dev/null
+++ b/packages/core/tests/figma-api/text/lists.test.ts
@@ -0,0 +1,129 @@
+import { describe, expect, test } from 'bun:test'
+
+import { FigmaAPI, SceneGraph } from '@open-pencil/core'
+
+// Results recorded from the same scripts run in live Figma (2026-10-09).
+function listText(characters: string) {
+ const api = new FigmaAPI(new SceneGraph())
+ const text = api.createText()
+ text.characters = characters
+ return { api, text }
+}
+
+function segments(text: ReturnType<typeof listText>['text']) {
+ const lines = text.characters.split('\n')
+ let start = 0
+ return lines.map((line, index) => {
+ const end = start + line.length + (index < lines.length - 1 ? 1 : 0)
+ const options = text.getRangeListOptions(start, end)
+ const indentation = text.getRangeIndentation(start, end)
+ start = end
+ return [
+ typeof options === 'symbol' ? 'MIXED' : options.type,
+ typeof indentation === 'symbol' ? 'MIXED' : indentation
+ ]
+ })
+}
+
+describe('text lists', () => {
+ test('reads a range by the paragraphs it touches, and mixed across them', () => {
+ const { api, text } = listText('ab\ncd\nef')
+ text.setRangeListOptions(3, 5, { type: 'ORDERED' })
+
+ expect(text.getRangeListOptions(0, 3)).toEqual({ type: 'NONE' })
+ // A newline belongs to the paragraph it ends.
+ expect(text.getRangeListOptions(2, 3)).toEqual({ type: 'NONE' })
+ expect(text.getRangeListOptions(2, 4)).toBe(api.mixed)
+ expect(text.getRangeListOptions(3, 4)).toEqual({ type: 'ORDERED' })
+ expect(text.getRangeIndentation(0, 2)).toBe(0)
+ expect(text.getRangeIndentation(3, 5)).toBe(1)
+ expect(text.getRangeIndentation(0, 8)).toBe(api.mixed)
+ })
+
+ test('nests list items one to five levels and leaves a list at level zero', () => {
+ const { text } = listText('a\nb\nc')
+ text.setRangeListOptions(0, 5, { type: 'UNORDERED' })
+ text.setRangeIndentation(2, 3, 3)
+ text.setRangeIndentation(4, 5, 0)
+ expect(segments(text)).toEqual([
+ ['UNORDERED', 1],
+ ['UNORDERED', 3],
+ ['UNORDERED', 1]
+ ])
+ text.setRangeListOptions(2, 3, { type: 'NONE' })
+ expect(segments(text)[1]).toEqual(['NONE', 0])
+ // A plain paragraph keeps an indentation, though it draws none.
+ text.setRangeIndentation(2, 3, 2)
+ expect(segments(text)[1]).toEqual(['NONE', 2])
+ })
+
+ test('continues a list into inserted paragraphs and gives replaced text the first style', () => {
+ const { text } = listText('a\nb')
+ text.setRangeListOptions(0, 3, { type: 'UNORDERED' })
+ text.insertCharacters(1, '\nnew')
+ text.insertCharacters(text.characters.length, '\nend')
+ expect(segments(text)).toEqual([
+ ['UNORDERED', 1],
+ ['UNORDERED', 1],
+ ['UNORDERED', 1],
+ ['UNORDERED', 1]
+ ])
+
+ text.setRangeListOptions(0, 1, { type: 'ORDERED' })
+ text.setRangeIndentation(2, 3, 2)
+ text.characters = 'x\ny\nz'
+ expect(segments(text)).toEqual([
+ ['ORDERED', 1],
+ ['ORDERED', 1],
+ ['ORDERED', 1]
+ ])
+ })
+
+ test('rejects ranges, list types, and levels as Figma does', () => {
+ const { text } = listText('ab\ncd\nef')
+ expect(() => text.getRangeListOptions(0, 0)).toThrow(
+ "in getRangeListOptions: Empty range selected. 'end' must be greater than 'start'"
+ )
+ expect(() => text.getRangeListOptions(-1, 2)).toThrow(
+ 'in getRangeListOptions: Property "start" failed validation: Number must be greater than or equal to 0'
+ )
+ expect(() => text.getRangeListOptions(0, 99)).toThrow(
+ 'in getRangeListOptions: Range outside of available characters.'
+ )
+ expect(() =>
+ text.setRangeListOptions(0, 1, { type: 'BULLET' as TextListOptions['type'] })
+ ).toThrow("Expected 'NONE' | 'ORDERED' | 'UNORDERED', received 'BULLET' at .type")
+ expect(() => text.setRangeIndentation(6, 8, -1)).toThrow(
+ 'Number must be greater than or equal to 0'
+ )
+ expect(() => text.setRangeIndentation(3, 5, 2.5)).toThrow('Expected integer, received float')
+ expect(() => text.setRangeIndentation(0, 2, 9)).toThrow(
+ 'Number must be less than or equal to 5'
+ )
+ })
+
+ test('sets list and paragraph spacing, indent, and hanging markers', () => {
+ const { text } = listText('a\nb')
+ expect([
+ text.listSpacing,
+ text.paragraphSpacing,
+ text.paragraphIndent,
+ text.hangingList
+ ]).toEqual([0, 0, 0, false])
+ text.listSpacing = 10
+ text.paragraphSpacing = 4.5
+ text.paragraphIndent = 20
+ text.hangingList = true
+ expect([
+ text.listSpacing,
+ text.paragraphSpacing,
+ text.paragraphIndent,
+ text.hangingList
+ ]).toEqual([10, 4.5, 20, true])
+ expect(() => {
+ text.listSpacing = -3
+ }).toThrow(
+ 'in set_listSpacing: Property "listSpacing" failed validation: Number must be greater than or equal to 0'
+ )
+ })
+})
diff --git a/packages/core/tests/figma-api/text/paragraph-spacing.test.ts b/packages/core/tests/figma-api/text/paragraph-spacing.test.ts
new file mode 100644
index 000000000..b8b118ab7
--- /dev/null
+++ b/packages/core/tests/figma-api/text/paragraph-spacing.test.ts
@@ -0,0 +1,97 @@
+import { describe, expect, test } from 'bun:test'
+
+import { FigmaAPI, SceneGraph } from '@open-pencil/core'
+
+// Results recorded from the same scripts run in live Figma (2026-10-10).
+function spacedText(characters = 'A\nB\nC') {
+ const api = new FigmaAPI(new SceneGraph())
+ const text = api.createText()
+ text.characters = characters
+ return { api, text }
+}
+
+/** Each paragraph's spacing, read one paragraph at a time. */
+function perParagraph(
+ text: ReturnType<typeof spacedText>['text'],
+ read: (start: number, end: number) => number | symbol
+) {
+ let start = 0
+ return text.characters.split('\n').map((line) => {
+ const value = read(start, start + Math.max(1, line.length))
+ start += line.length + 1
+ return value
+ })
+}
+
+describe('paragraph spacing ranges', () => {
+ test('reach the paragraph at the end of the range, unlike list options', () => {
+ const cases: Array<[number, number, number[]]> = [
+ [0, 1, [9, 0, 0]],
+ [0, 2, [9, 9, 0]],
+ [1, 2, [9, 9, 0]],
+ [1, 3, [9, 9, 0]],
+ [2, 3, [0, 9, 0]],
+ [3, 4, [0, 9, 9]],
+ [0, 4, [9, 9, 9]]
+ ]
+ for (const [start, end, expected] of cases) {
+ const { text } = spacedText()
+ text.setRangeParagraphSpacing(start, end, 9)
+ text.setRangeParagraphIndent(start, end, 9)
+ expect(perParagraph(text, (s, e) => text.getRangeParagraphSpacing(s, e))).toEqual(expected)
+ expect(perParagraph(text, (s, e) => text.getRangeParagraphIndent(s, e))).toEqual(expected)
+ }
+ })
+
+ test('read mixed across differing paragraphs, on the range and the text', () => {
+ const { api, text } = spacedText()
+ text.setRangeParagraphSpacing(0, 1, 20)
+ expect(text.getRangeParagraphSpacing(0, 3)).toBe(api.mixed)
+ expect(text.getRangeParagraphSpacing(0, 1)).toBe(20)
+ expect<number | symbol>(text.paragraphSpacing).toBe(api.mixed)
+ expect(text.listSpacing).toBe(0)
+ })
+
+ test('setting the text keeps paragraphs that set their own', () => {
+ const { text } = spacedText()
+ text.setRangeParagraphSpacing(0, 1, 20)
+ text.paragraphSpacing = 5
+ expect(perParagraph(text, (s, e) => text.getRangeParagraphSpacing(s, e))).toEqual([20, 5, 5])
+ })
+
+ test('reject what Figma rejects, with its messages', () => {
+ const { text } = spacedText()
+ expect(() => text.setRangeParagraphSpacing(0, 1, -3)).toThrow(
+ 'in setRangeParagraphSpacing: Property "value" failed validation: Number must be greater than or equal to 0'
+ )
+ expect(() => text.setRangeParagraphIndent(0, 1, -3)).toThrow(
+ 'in setRangeParagraphIndent: Property "value" failed validation'
+ )
+ expect(() => text.setRangeListSpacing(0, 1, -3)).toThrow(
+ 'in setRangeListSpacing: Property "value" failed validation'
+ )
+ expect(() => text.setRangeParagraphSpacing(0, 99, 3)).toThrow(
+ "in setRangeParagraphSpacing: Range outside of available characters. 'start' must be less than node.characters.length and 'end' must be less than or equal to node.characters.length"
+ )
+ expect(() => text.setRangeParagraphSpacing(1, 1, 3)).toThrow(
+ "in setRangeParagraphSpacing: Empty range selected. 'end' must be greater than 'start'"
+ )
+ expect(() => text.getRangeParagraphSpacing(1, 1)).toThrow(
+ "in getRangeParagraphSpacing: Empty range selected. 'end' must be greater than 'start'"
+ )
+ text.setRangeParagraphSpacing(0, 1, 2.5)
+ expect(text.getRangeParagraphSpacing(0, 1)).toBe(2.5)
+ })
+
+ test('follow the paragraphs through text edits', () => {
+ const { text } = spacedText()
+ text.setRangeParagraphSpacing(1, 2, 7)
+ text.characters = 'X\nY'
+ expect(perParagraph(text, (s, e) => text.getRangeParagraphSpacing(s, e))).toEqual([7, 7])
+ text.setRangeParagraphSpacing(0, 1, 30)
+ text.insertCharacters(1, '\nZ')
+ expect(perParagraph(text, (s, e) => text.getRangeParagraphSpacing(s, e))).toEqual([
+ 30, 30, 7
+ ])
+ })
+})
diff --git a/packages/core/tests/figma-api/text-units.test.ts b/packages/core/tests/figma-api/text/units.test.ts
similarity index 100%
rename from packages/core/tests/figma-api/text-units.test.ts
rename to packages/core/tests/figma-api/text/units.test.ts
diff --git a/packages/core/tests/io/formats/fig/roundtrip/text-lists.test.ts b/packages/core/tests/io/formats/fig/roundtrip/text-lists.test.ts
new file mode 100644
index 000000000..b5f757796
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/roundtrip/text-lists.test.ts
@@ -0,0 +1,77 @@
+import { beforeAll, expect, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+
+import { exportFigFile, initCodec, parseFigFile, SceneGraph } from '@open-pencil/core'
+import { fontManager } from '@open-pencil/core/text'
+import { parseFigBuffer } from '@open-pencil/fig'
+import type { TextParagraphStyle } from '@open-pencil/scene-graph'
+
+const LIST: TextParagraphStyle[] = [
+ { listType: 'NONE', indentation: 0, paragraphSpacing: 24, paragraphIndent: 30 },
+ { listType: 'ORDERED', indentation: 1, listSpacing: 2 },
+ { listType: 'ORDERED', indentation: 2 },
+ { listType: 'UNORDERED', indentation: 1 }
+]
+
+beforeAll(async () => {
+ await initCodec()
+ const inter = expectDefined(
+ await fontManager.fetchBundledFont('/Inter-Regular.ttf'),
+ 'bundled Inter font'
+ )
+ fontManager.markLoaded('Inter', 'Regular', inter)
+})
+
+test('writes lists as Figma does and reads them back', async () => {
+ const graph = new SceneGraph()
+ graph.createNode('TEXT', graph.getPages()[0].id, {
+ text: 'Intro\nFirst\nNested\nBullet',
+ fontFamily: 'Inter',
+ fontSize: 16,
+ width: 300,
+ height: 100,
+ textParagraphs: LIST,
+ listSpacing: 6,
+ paragraphSpacing: 10,
+ paragraphIndent: 12,
+ hangingList: true
+ })
+ const bytes = await exportFigFile(graph)
+
+ const written = expectDefined(
+ parseFigBuffer(bytes.slice().buffer).nodeChanges.find((node) => node.type === 'TEXT'),
+ 'written text'
+ )
+ expect(
+ written.textData?.lines?.map((line) => [
+ line.lineType,
+ line.indentationLevel,
+ line.isFirstLineOfList
+ ])
+ ).toEqual([
+ ['PLAIN', 0, false],
+ ['ORDERED_LIST', 1, true],
+ ['ORDERED_LIST', 2, true],
+ ['UNORDERED_LIST', 1, true]
+ ])
+ expect([
+ written.listSpacing,
+ written.paragraphSpacing,
+ written.paragraphIndent,
+ written.hangingList
+ ]).toEqual([6, 10, 12, true])
+ // Figma draws pasted and opened text from these glyphs: each marker is one with no character.
+ const markers = written.derivedTextData?.glyphs?.filter((glyph) => glyph.firstCharacter === undefined)
+ expect(markers?.length).toBe(5)
+
+ const reopened = await parseFigFile(bytes.slice().buffer)
+ const text = expectDefined(
+ [...reopened.getAllNodes()].find((node) => node.type === 'TEXT'),
+ 'reopened text'
+ )
+ expect(text.textParagraphs).toEqual(LIST)
+ expect([text.listSpacing, text.paragraphSpacing, text.paragraphIndent, text.hangingList]).toEqual([
+ 6, 10, 12, true
+ ])
+})
diff --git a/packages/docs/development/testing.md b/packages/docs/development/testing.md
index 86f1a0b8a..92cb4879c 100644
--- a/packages/docs/development/testing.md
+++ b/packages/docs/development/testing.md
@@ -14,7 +14,7 @@ Place a test with the source that owns its contract. Choose the runtime separate
| Figma compatibility acceptance | `tests/figma/**/*.spec.ts` |
| Private tool contracts | `tools/<owner>/tests/` |
-For example, `packages/core/src/canvas/text/prepared.ts` maps to `packages/core/tests/canvas/text/prepared.test.ts`; `src/app/demo/viewport.ts` maps to `tests/app/demo/viewport.test.ts`. A substantial module may have a matching test directory rather than one large test file. Application E2E, external-system acceptance and large contract suites are intentional exceptions to file-for-file mirroring.
+For example, `packages/core/src/canvas/text/shape.ts` maps to `packages/core/tests/canvas/text/shape.test.ts`; `src/app/demo/viewport.ts` maps to `tests/app/demo/viewport.test.ts`. A substantial module may have a matching test directory rather than one large test file. Application E2E, external-system acceptance and large contract suites are intentional exceptions to file-for-file mirroring.
Core tests using SceneGraph still belong to Core. Central integration is for contracts without a single owning implementation, such as interoperability between published packages. Name that contract explicitly; do not use integration as a miscellaneous bucket.
diff --git a/packages/docs/programmable/cli/scripting.md b/packages/docs/programmable/cli/scripting.md
index 516382dca..5a6327b0b 100644
--- a/packages/docs/programmable/cli/scripting.md
+++ b/packages/docs/programmable/cli/scripting.md
@@ -195,6 +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`, alignment, line height, letter spacing, style-run helpers
+- 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/programmable/sdk/api/composables/use-typography.md b/packages/docs/programmable/sdk/api/composables/use-typography.md
index fd599e007..938bb5876 100644
--- a/packages/docs/programmable/sdk/api/composables/use-typography.md
+++ b/packages/docs/programmable/sdk/api/composables/use-typography.md
@@ -20,6 +20,7 @@ It exposes:
- text case and direction
- ending truncation and maximum lines
- OpenType feature toggles
+- list style (`listType`, `null` when the paragraphs differ) and hanging lists
- helpers for changing family, weight, alignment, and decorations
- `merged(key)` and `fontFeature(tag)`, which return the shared value or `MIXED`
@@ -75,6 +76,16 @@ typography.setTruncation('ENDING')
typography.setFontFeature('LIGA', false)
```
+### Make a list
+
+While the text is being edited, `setListType` and `setParagraphSpacing` change the paragraphs under the caret or selection; otherwise they change the whole text. `paragraphSpacing(field)` reads `listSpacing`, `paragraphSpacing`, or `paragraphIndent` for those paragraphs, `MIXED` when they differ, and `previewParagraphSpacing` shows a value while a field is dragged without an undo step.
+
+```ts
+typography.setListType('UNORDERED')
+typography.setHangingList(true)
+typography.setParagraphSpacing('listSpacing', 8)
+```
+
## Related APIs
- [useTextEdit](./use-text-edit)
diff --git a/packages/fig/docs/materialization.md b/packages/fig/docs/materialization.md
index 68ae3c4c3..bd95ae743 100644
--- a/packages/fig/docs/materialization.md
+++ b/packages/fig/docs/materialization.md
@@ -191,7 +191,7 @@ No coordinate factor is inferred from current dimensions or numeric variable val
- [Owner-scoped correspondence](../src/instance-overrides/source-children.ts)
- [Live component edits](../src/instance-overrides/live-component-edits.ts)
- [Component-property domain](../../scene-graph/src/components/properties.ts)
-- [Text cache invalidation](../../scene-graph/src/text-picture.ts)
+- [Text cache invalidation](../../scene-graph/src/text/picture.ts)
- [Full-document editing test](../tests/document/gold-edit.test.ts)
- [Occurrence conversion/isolation tests](../tests/document/occurrence-conversion.test.ts)
- [Saved-glyph visual test](../../../tests/e2e/canvas/saved-glyph-visual.spec.ts)
diff --git a/packages/fig/src/node-change/convert.ts b/packages/fig/src/node-change/convert.ts
index 734772503..dd8000075 100644
--- a/packages/fig/src/node-change/convert.ts
+++ b/packages/fig/src/node-change/convert.ts
@@ -29,6 +29,7 @@ import {
readNodeChangePluginData
} from './plugin-data'
import { importStyleRuns } from './style/runs'
+import { importParagraphStyles } from './text/lines'
import { convertLetterSpacing, convertLineHeight, mapTextDecoration } from './text/values'
import {
alignGeometryWindingRules,
@@ -335,6 +336,11 @@ type TextProps = Pick<
| 'lineHeight'
| 'letterSpacing'
| 'maxLines'
+ | 'textParagraphs'
+ | 'listSpacing'
+ | 'paragraphSpacing'
+ | 'paragraphIndent'
+ | 'hangingList'
| 'styleRuns'
| 'fontVariations'
| 'fontFeatures'
@@ -365,6 +371,21 @@ function convertTextDecorationProps(
}
}
+function convertParagraphProps(
+ nc: NodeChange
+): Pick<
+ SceneNode,
+ 'textParagraphs' | 'listSpacing' | 'paragraphSpacing' | 'paragraphIndent' | 'hangingList'
+> {
+ return {
+ textParagraphs: importParagraphStyles(nc.textData?.lines, nc.textData?.styleOverrideTable),
+ listSpacing: nc.listSpacing ?? 0,
+ paragraphSpacing: nc.paragraphSpacing ?? 0,
+ paragraphIndent: nc.paragraphIndent ?? 0,
+ hangingList: nc.hangingList ?? false
+ }
+}
+
function convertTextProps(nc: NodeChange, blobs: Uint8Array[]): TextProps {
return {
text: nc.textData?.characters ?? '',
@@ -385,6 +406,7 @@ function convertTextProps(nc: NodeChange, blobs: Uint8Array[]): TextProps {
lineHeight: importedTextLineHeight(nc),
letterSpacing: convertLetterSpacing(nc.letterSpacing, nc.fontSize),
maxLines: (nc.maxLines ?? null) as number | null,
+ ...convertParagraphProps(nc),
styleRuns: importStyleRuns(nc),
fontVariations: convertFontVariations(nc),
fontFeatures: convertFontFeatures(nc),
diff --git a/packages/fig/src/node-change/derived-text/build.ts b/packages/fig/src/node-change/derived-text/build.ts
index 6261742ac..41b8f9af5 100644
--- a/packages/fig/src/node-change/derived-text/build.ts
+++ b/packages/fig/src/node-change/derived-text/build.ts
@@ -1,7 +1,13 @@
import { groupBy } from 'es-toolkit/array'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
-import { normalizeFontFamily, weightToStyle } from '@open-pencil/scene-graph'
+import {
+ hasTextList,
+ normalizeFontFamily,
+ paragraphIndexAt,
+ textParagraphRanges,
+ weightToStyle
+} from '@open-pencil/scene-graph'
import type { DerivedTextGlyph, SceneNode } from '@open-pencil/scene-graph'
import { bytesToHex } from '../bytes'
@@ -22,7 +28,8 @@ export interface ShapedTextGlyph {
x: number
y: number
fontSize: number
- firstCharacter: number
+ /** The character the glyph draws, left out for a list marker. */
+ firstCharacter?: number
/** Horizontal advance in pixels. */
advance: number
}
@@ -108,7 +115,8 @@ function shapedGlyphRecords(
interface SavedGlyph {
glyph: DerivedTextGlyph
- character: number
+ /** The character the glyph draws; a list marker draws none. */
+ character: number | undefined
}
/**
@@ -122,23 +130,65 @@ function savedGlyphLines(glyphs: SavedGlyph[]): SavedGlyph[][] {
)
}
+/**
+ * The character each saved glyph draws. Glyphs from shapers that record no characters stand
+ * one for one for the text; in a list, or among glyphs that record them, a glyph without a
+ * character is a list marker.
+ */
+function savedGlyphCharacters(
+ node: SceneNode,
+ glyphs: DerivedTextGlyph[]
+): Array<number | undefined> {
+ const indexed = hasTextList(node) || glyphs.some((glyph) => glyph.firstCharacter !== undefined)
+ return glyphs.map((glyph, index) => glyph.firstCharacter ?? (indexed ? undefined : index))
+}
+
+/**
+ * Where a line starts: at its first character, or, for an empty list item that shows only its
+ * marker, at the paragraph after the last character of the lines before.
+ */
+function lineStart(node: SceneNode, line: SavedGlyph[], previousEnd: number | undefined): number {
+ const characters = line.flatMap(({ character }) => (character === undefined ? [] : [character]))
+ if (characters.length > 0) return Math.min(...characters)
+ if (previousEnd === undefined) return 0
+ const ranges = textParagraphRanges(node.text)
+ return ranges[paragraphIndexAt(node.text, previousEnd) + 1]?.start ?? node.text.length
+}
+
function savedGlyphLayout(
node: SceneNode,
glyphs: DerivedTextGlyph[]
): Pick<ShapedText, 'baselines' | 'logicalIndexToCharacterOffsetMap'> {
const lineHeight = node.lineHeight ?? Math.ceil(node.fontSize * 1.2)
const offsets = Array.from({ length: node.text.length }, () => 0)
+ const characters = savedGlyphCharacters(node, glyphs)
const lines = savedGlyphLines(
- glyphs.map((glyph, index) => ({ glyph, character: glyph.firstCharacter ?? index }))
+ glyphs.map((glyph, index) => ({ glyph, character: characters[index] }))
)
+ const starts: number[] = []
+ let previousEnd: number | undefined
+ for (const line of lines) {
+ starts.push(lineStart(node, line, previousEnd))
+ for (const { character } of line) {
+ if (character !== undefined) previousEnd = Math.max(previousEnd ?? 0, character)
+ }
+ // An empty item ends at its own newline.
+ if (line.every(({ character }) => character === undefined)) previousEnd = starts.at(-1)
+ }
const baselines = lines.map((line, lineIndex) => {
- const startX = Math.min(...line.map(({ glyph }) => glyph.x))
- for (const { glyph, character } of line) {
- if (character < offsets.length) offsets[character] = glyph.x - startX
+ // Markers stand before their item's text; a line starts where its characters do.
+ const text = line.filter(({ character }) => character !== undefined)
+ const startX = text.length
+ ? Math.min(...text.map(({ glyph }) => glyph.x))
+ : Math.max(...line.map(({ glyph }) => glyph.x + (glyph.advance ?? 0)))
+ for (const { glyph, character } of text) {
+ if (character !== undefined && character < offsets.length) {
+ offsets[character] = glyph.x - startX
+ }
}
return {
- firstCharacter: line[0].character,
- endCharacter: lines[lineIndex + 1]?.[0].character ?? node.text.length,
+ firstCharacter: starts[lineIndex],
+ endCharacter: starts[lineIndex + 1] ?? node.text.length,
position: { x: startX, y: line[0].glyph.y },
width: node.width,
lineY: lineIndex * lineHeight,
@@ -160,9 +210,11 @@ function savedAdvance(glyph: DerivedTextGlyph, next: DerivedTextGlyph | undefine
}
function savedGlyphRecords(
+ node: SceneNode,
glyphs: DerivedTextGlyph[],
context: DerivedTextBuildContext
): DerivedTextGlyphRecord[] {
+ const characters = savedGlyphCharacters(node, glyphs)
return glyphs.map((glyph, index) => {
const next = glyphs[index + 1]
const sameLine =
@@ -181,7 +233,7 @@ function savedGlyphRecords(
),
position: { x: glyph.x, y: glyph.y },
fontSize: glyph.fontSize,
- firstCharacter: glyph.firstCharacter ?? index,
+ firstCharacter: characters[index],
advance: savedAdvance(glyph, sameLine ? next : undefined),
// Preserve path-text radians; hardcoding 0 used to flatten circular text on re-export.
rotation: glyph.rotation ?? 0
@@ -213,7 +265,7 @@ export function buildNodeDerivedTextData(
if (saved.length > 0) {
return buildDerivedTextData({
node,
- glyphs: savedGlyphRecords(saved, context),
+ glyphs: savedGlyphRecords(node, saved, context),
fontMetaData: fonts,
...savedGlyphLayout(node, saved)
})
diff --git a/packages/fig/src/node-change/serialize.ts b/packages/fig/src/node-change/serialize.ts
index a56b88dca..a146128e0 100644
--- a/packages/fig/src/node-change/serialize.ts
+++ b/packages/fig/src/node-change/serialize.ts
@@ -49,11 +49,6 @@ import {
import { exportTextData, fontVariationToKiwi } from './text/data-export'
import { toKiwiWindingRule } from './vector/geometry'
-function textLines(text: string): NonNullable<NodeChange['textData']>['lines'] {
- const lineCount = Math.max(1, text.split('\n').length)
- return Array.from({ length: lineCount }, () => ({ lineType: 'PLAIN' }))
-}
-
function serializeCornerRadii(node: SceneNode, nc: KiwiNodeChange): void {
const anyIndividual =
node.topLeftRadius > 0 ||
@@ -84,6 +79,14 @@ function serializeCornerRadii(node: SceneNode, nc: KiwiNodeChange): void {
}
}
+/** Paragraph spacing and list layout, which `.fig` keeps beside the lines in `textData`. */
+function serializeParagraphProps(node: SceneNode, nc: KiwiNodeChange): void {
+ if (node.paragraphSpacing !== 0) nc.paragraphSpacing = node.paragraphSpacing
+ if (node.paragraphIndent !== 0) nc.paragraphIndent = node.paragraphIndent
+ if (node.listSpacing !== 0) nc.listSpacing = node.listSpacing
+ if (node.hangingList) nc.hangingList = true
+}
+
function serializeTextProps(
node: SceneNode,
nc: KiwiNodeChange,
@@ -104,7 +107,7 @@ function serializeTextProps(
style: weightToFigmaStyle(node.fontWeight, node.italic),
postscript: ''
}
- nc.textData = exportTextData(node, textLines, fillToKiwiPaint)
+ nc.textData = exportTextData(node, fillToKiwiPaint)
if (node.fontVariations.length > 0) {
nc.fontVariations = node.fontVariations.map(fontVariationToKiwi)
}
@@ -127,6 +130,7 @@ function serializeTextProps(
if (node.textCase !== 'ORIGINAL') nc.textCase = node.textCase
if (node.textTruncation === 'ENDING') nc.textTruncation = 'ENDING'
if (node.maxLines != null) nc.maxLines = node.maxLines
+ serializeParagraphProps(node, nc)
if (fontDigestMap) {
nc.derivedTextData = buildNodeDerivedTextData(node, {
digestMap: fontDigestMap,
diff --git a/packages/fig/src/node-change/text/data-export.ts b/packages/fig/src/node-change/text/data-export.ts
index 77934dccb..c4282eddd 100644
--- a/packages/fig/src/node-change/text/data-export.ts
+++ b/packages/fig/src/node-change/text/data-export.ts
@@ -5,6 +5,7 @@ import type { CharacterStyleOverride, SceneNode } from '@open-pencil/scene-graph
import { applyFontFeaturesToKiwi } from '../font/features'
import { weightToFigmaStyle } from '../font/style'
import { stringToFigmaAxisTag } from '../font/variations'
+import { exportTextLines } from './lines'
export function fontVariationToKiwi(variation: SceneNode['fontVariations'][number]) {
const axisTag = stringToFigmaAxisTag(variation.axis)
@@ -92,22 +93,20 @@ function collectTextStyleOverrides(node: SceneNode): {
export function exportTextData(
node: SceneNode,
- textLines: (text: string) => NonNullable<NodeChange['textData']>['lines'],
fillToKiwiPaint: (fill: SceneNode['fills'][number]) => Paint
): NodeChange['textData'] {
- if (node.styleRuns.length === 0) {
- return { characters: node.text, lines: textLines(node.text) }
- }
-
const { charIds, styleMap } = collectTextStyleOverrides(node)
- const overrideTable = [...styleMap.values()].map(({ id, style }) =>
+ const characterOverrides = [...styleMap.values()].map(({ id, style }) =>
textStyleOverrideToKiwi(id, style, node, fillToKiwiPaint)
)
-
- return {
+ // Paragraph spacing shares the override table, numbered after the character styles.
+ const paragraphs = exportTextLines(node, styleMap.size + 1)
+ const overrideTable = [...characterOverrides, ...paragraphs.overrides]
+ const data: NonNullable<NodeChange['textData']> = {
characters: node.text,
- lines: textLines(node.text),
- characterStyleIDs: charIds,
- styleOverrideTable: overrideTable
+ lines: paragraphs.lines
}
+ if (node.styleRuns.length > 0) data.characterStyleIDs = charIds
+ if (overrideTable.length > 0) data.styleOverrideTable = overrideTable
+ return data
}
diff --git a/packages/fig/src/node-change/text/lines.ts b/packages/fig/src/node-change/text/lines.ts
new file mode 100644
index 000000000..ea5d8996a
--- /dev/null
+++ b/packages/fig/src/node-change/text/lines.ts
@@ -0,0 +1,101 @@
+import { isEmptyObject } from 'es-toolkit/predicate'
+
+import type { NodeChange, TextLineData } from '@open-pencil/kiwi/fig/codec'
+import {
+ TEXT_PARAGRAPH_SPACING_FIELDS,
+ paragraphStyleAt,
+ textListItems,
+ textParagraphRanges,
+ trimParagraphStyles,
+ withIndentation,
+ withParagraphSpacing,
+ type SceneNode,
+ type TextListType,
+ type TextParagraphSpacingField,
+ type TextParagraphStyle
+} from '@open-pencil/scene-graph'
+
+const LINE_TYPES: Record<TextListType, NonNullable<TextLineData['lineType']>> = {
+ NONE: 'PLAIN',
+ ORDERED: 'ORDERED_LIST',
+ UNORDERED: 'UNORDERED_LIST'
+}
+
+function listTypeOf(line: TextLineData): TextListType {
+ if (line.lineType === 'ORDERED_LIST') return 'ORDERED'
+ if (line.lineType === 'UNORDERED_LIST') return 'UNORDERED'
+ return 'NONE'
+}
+
+/**
+ * The paragraph styles a `.fig` text stores in `textData.lines`, one line per paragraph. A line's
+ * `styleId` names an entry of the style override table that holds the paragraph's own spacing.
+ */
+export function importParagraphStyles(
+ lines: readonly TextLineData[] | undefined,
+ overrides: readonly NodeChange[] = []
+): TextParagraphStyle[] {
+ if (!lines) return []
+ const byId = new Map(overrides.map((override) => [override.styleID, override]))
+ const styles = lines.map((line) => {
+ let style: TextParagraphStyle = {
+ listType: listTypeOf(line),
+ indentation: line.indentationLevel ?? 0
+ }
+ // A list item nests 1–5 deep; plain paragraphs keep the level the file stores.
+ if (style.listType !== 'NONE') style = withIndentation(style, style.indentation)
+ const override = line.styleId ? byId.get(line.styleId) : undefined
+ for (const field of TEXT_PARAGRAPH_SPACING_FIELDS) {
+ const value = override?.[field]
+ if (value !== undefined) style = withParagraphSpacing(style, field, value)
+ }
+ return style
+ })
+ return trimParagraphStyles(styles, styles.length)
+}
+
+/**
+ * `textData.lines` for a text: one per paragraph, marking list items, how deeply they nest,
+ * and which item starts each list, as Figma writes them. Paragraphs with spacing of their own
+ * name style override entries numbered from `firstStyleId`, returned in `overrides`.
+ */
+export function exportTextLines(
+ node: Pick<SceneNode, 'text' | 'textParagraphs'>,
+ firstStyleId = 1
+): { lines: TextLineData[]; overrides: NodeChange[] } {
+ const starts = new Set(
+ textListItems(node.text, node.textParagraphs)
+ .filter((item) => item.startsList)
+ .map((item) => item.paragraph)
+ )
+ const overrides: NodeChange[] = []
+ const ids = new Map<string, number>()
+ const styleIdOf = (style: TextParagraphStyle): number => {
+ const fields: Partial<Record<TextParagraphSpacingField, number>> = {}
+ for (const field of TEXT_PARAGRAPH_SPACING_FIELDS) {
+ const value = style[field]
+ if (value !== undefined) fields[field] = value
+ }
+ if (isEmptyObject(fields)) return 0
+ const key = JSON.stringify(fields)
+ let id = ids.get(key)
+ if (id === undefined) {
+ id = firstStyleId + overrides.length
+ ids.set(key, id)
+ overrides.push({ styleID: id, ...fields })
+ }
+ return id
+ }
+ const lines = textParagraphRanges(node.text).map((_, paragraph): TextLineData => {
+ const style = paragraphStyleAt(node.textParagraphs, paragraph)
+ return {
+ lineType: LINE_TYPES[style.listType],
+ styleId: styleIdOf(style),
+ indentationLevel: style.indentation,
+ sourceDirectionality: 'AUTO',
+ listStartOffset: 0,
+ isFirstLineOfList: starts.has(paragraph)
+ }
+ })
+ return { lines, overrides }
+}
diff --git a/packages/fig/src/source-metadata.ts b/packages/fig/src/source-metadata.ts
index 643dcb26d..c1ee6e358 100644
--- a/packages/fig/src/source-metadata.ts
+++ b/packages/fig/src/source-metadata.ts
@@ -71,6 +71,11 @@ const EDITED_RAW_FIELDS: Partial<Record<string, readonly string[]>> = {
textUnderlineOffset: ['textUnderlineOffset', ...TEXT_DERIVED_RAW_FIELDS],
leadingTrim: ['leadingTrim', ...TEXT_DERIVED_RAW_FIELDS],
maxLines: ['maxLines', ...TEXT_DERIVED_RAW_FIELDS],
+ textParagraphs: [...TEXT_DERIVED_RAW_FIELDS],
+ listSpacing: ['listSpacing', ...TEXT_DERIVED_RAW_FIELDS],
+ paragraphSpacing: ['paragraphSpacing', ...TEXT_DERIVED_RAW_FIELDS],
+ paragraphIndent: ['paragraphIndent', ...TEXT_DERIVED_RAW_FIELDS],
+ hangingList: ['hangingList', ...TEXT_DERIVED_RAW_FIELDS],
fontVariations: ['fontVariations', ...TEXT_DERIVED_RAW_FIELDS],
fontFeatures: [
'fontVariantCommonLigatures',
diff --git a/packages/fig/tests/node-change/derived-text.test.ts b/packages/fig/tests/node-change/derived-text.test.ts
index 215cca191..d5593250f 100644
--- a/packages/fig/tests/node-change/derived-text.test.ts
+++ b/packages/fig/tests/node-change/derived-text.test.ts
@@ -140,6 +140,47 @@ describe('derived text writer', () => {
expect(data.glyphs?.map((glyph) => glyph.advance)).toEqual([0.5, 0, 0])
})
+ test('keeps list markers without characters, also for empty items', () => {
+ const blob = new Uint8Array([0])
+ const item = { listType: 'UNORDERED' as const, indentation: 1 }
+ const marker = (y: number) => ({ commandsBlob: blob, x: 7.5, y, fontSize: 16, advance: 9 })
+ // "A", an empty item, then "B": the empty item shows only its marker.
+ const node = textNode({
+ text: 'A\n\nB',
+ textParagraphs: [item, item, item],
+ derivedTextGlyphs: [
+ marker(12),
+ { commandsBlob: blob, x: 24, y: 12, fontSize: 16, firstCharacter: 0 },
+ marker(28),
+ marker(44),
+ { commandsBlob: blob, x: 24, y: 44, fontSize: 16, firstCharacter: 3 }
+ ]
+ })
+ const data = expectDefined(buildNodeDerivedTextData(node, context(null)), 'derived text')
+
+ expect(data.glyphs?.map((glyph) => glyph.firstCharacter)).toEqual([
+ undefined,
+ 0,
+ undefined,
+ undefined,
+ 3
+ ])
+ expect(data.baselines?.map((line) => [line.firstCharacter, line.endCharacter])).toEqual([
+ [0, 2],
+ [2, 3],
+ [3, 4]
+ ])
+ expect(data.baselines?.[0].position.x).toBe(24)
+
+ const onlyMarkers = textNode({
+ text: '\n',
+ textParagraphs: [item, item],
+ derivedTextGlyphs: [marker(12), marker(28)]
+ })
+ const markers = expectDefined(buildNodeDerivedTextData(onlyMarkers, context(null)), 'markers')
+ expect(markers.glyphs?.map((glyph) => glyph.firstCharacter)).toEqual([undefined, undefined])
+ })
+
test('names font styles as Figma does', () => {
const data = buildNodeDerivedTextData(
textNode({ fontFamily: 'Inter', fontWeight: 600 }),
diff --git a/packages/fig/tests/node-change/text/lines.test.ts b/packages/fig/tests/node-change/text/lines.test.ts
new file mode 100644
index 000000000..eaa74c3f8
--- /dev/null
+++ b/packages/fig/tests/node-change/text/lines.test.ts
@@ -0,0 +1,88 @@
+import { describe, expect, test } from 'bun:test'
+
+import { exportTextData } from '#fig/node-change/text/data-export'
+import { exportTextLines, importParagraphStyles } from '#fig/node-change/text/lines'
+
+import { SceneGraph, type TextParagraphStyle } from '@open-pencil/scene-graph'
+
+describe('importParagraphStyles', () => {
+ test('nests a list line with no stored level at the first level', () => {
+ expect(
+ importParagraphStyles([
+ { lineType: 'UNORDERED_LIST' },
+ { lineType: 'ORDERED_LIST', indentationLevel: 9 },
+ { lineType: 'PLAIN', indentationLevel: 2 }
+ ])
+ ).toEqual([
+ { listType: 'UNORDERED', indentation: 1 },
+ { listType: 'ORDERED', indentation: 5 },
+ { listType: 'NONE', indentation: 2 }
+ ])
+ })
+})
+
+// Lines and overrides as live Figma (2026-10-10) writes a text with spacing of its own on some
+// paragraphs and a bold run: paragraphs and characters share the table with distinct ids.
+const FIGMA_LINES = [
+ { lineType: 'PLAIN', styleId: 0 },
+ { lineType: 'PLAIN', styleId: 1 },
+ { lineType: 'ORDERED_LIST', styleId: 0, indentationLevel: 1 },
+ { lineType: 'ORDERED_LIST', styleId: 4, indentationLevel: 1 },
+ { lineType: 'PLAIN', styleId: 5 },
+ { lineType: 'PLAIN', styleId: 0 }
+] as const
+const FIGMA_OVERRIDES = [
+ { styleID: 1, paragraphSpacing: 25 },
+ { styleID: 3, fontName: { family: 'Inter', style: 'Bold', postscript: '' } },
+ { styleID: 4, paragraphSpacing: 40 },
+ { styleID: 5, listSpacing: 33 }
+]
+const plain: TextParagraphStyle = { listType: 'NONE', indentation: 0 }
+const item: TextParagraphStyle = { listType: 'ORDERED', indentation: 1 }
+
+describe('paragraph spacing in lines', () => {
+ test("reads each paragraph's own spacing from the override its line names", () => {
+ expect(importParagraphStyles([...FIGMA_LINES], FIGMA_OVERRIDES)).toEqual([
+ plain,
+ { ...plain, paragraphSpacing: 25 },
+ item,
+ { ...item, paragraphSpacing: 40 },
+ { ...plain, listSpacing: 33 }
+ ])
+ })
+
+ test('writes overrides after the character styles, one per distinct spacing', () => {
+ const graph = new SceneGraph()
+ const node = graph.createNode('TEXT', graph.getPages()[0].id, {
+ text: 'P1\nP2\nI1',
+ styleRuns: [{ start: 3, length: 2, style: { fontWeight: 700 } }],
+ textParagraphs: [
+ { ...plain, paragraphSpacing: 25 },
+ { ...plain, paragraphSpacing: 25 },
+ { ...item, listSpacing: 4 }
+ ]
+ })
+ const data = exportTextData(node, () => ({ type: 'SOLID' }))
+ expect(data?.lines?.map((line) => line.styleId)).toEqual([2, 2, 3])
+ expect(
+ data?.styleOverrideTable?.map(({ styleID, paragraphSpacing, listSpacing }) => ({
+ styleID,
+ paragraphSpacing,
+ listSpacing
+ }))
+ ).toEqual([
+ { styleID: 1, paragraphSpacing: undefined, listSpacing: undefined },
+ { styleID: 2, paragraphSpacing: 25, listSpacing: undefined },
+ { styleID: 3, paragraphSpacing: undefined, listSpacing: 4 }
+ ])
+ expect(importParagraphStyles(data?.lines, data?.styleOverrideTable)).toEqual(
+ node.textParagraphs
+ )
+ })
+
+ test('writes no override table for text without spacing of its own', () => {
+ const { lines, overrides } = exportTextLines({ text: 'A\nB', textParagraphs: [item] })
+ expect(lines.map((line) => line.styleId)).toEqual([0, 0])
+ expect(overrides).toEqual([])
+ })
+})
diff --git a/packages/kiwi/src/fig/codec.ts b/packages/kiwi/src/fig/codec.ts
index 59cc0121a..8ed411efd 100644
--- a/packages/kiwi/src/fig/codec.ts
+++ b/packages/kiwi/src/fig/codec.ts
@@ -221,6 +221,16 @@ export interface AssetRef {
export type StyleReference = { guid: GUID; assetRef?: never } | { guid?: never; assetRef: AssetRef }
+/** One paragraph of a text: whether it is a list item, and how deeply it nests. */
+export interface TextLineData {
+ lineType?: 'PLAIN' | 'ORDERED_LIST' | 'UNORDERED_LIST' | 'BLOCKQUOTE' | 'HEADER'
+ styleId?: number
+ indentationLevel?: number
+ sourceDirectionality?: string
+ listStartOffset?: number
+ isFirstLineOfList?: boolean
+}
+
export interface NodeChange {
[key: string]: unknown
guid?: GUID
@@ -289,7 +299,7 @@ export interface NodeChange {
textAutoResize?: string
textData?: {
characters: string
- lines?: Array<{ lineType?: string; styleId?: number; indentationLevel?: number }>
+ lines?: TextLineData[]
characterStyleIDs?: number[]
styleOverrideTable?: NodeChange[]
}
@@ -308,7 +318,8 @@ export interface NodeChange {
commandsBlob?: number
position: Vector
fontSize: number
- firstCharacter: number
+ /** The character the glyph draws; Figma leaves it out for list markers. */
+ firstCharacter?: number
advance: number
/** Radians along the text path; kiwi omits the field for axis-aligned text. */
rotation?: number
@@ -357,6 +368,10 @@ export interface NodeChange {
emojiImageSet?: string
lineHeight?: { value: number; units: string }
letterSpacing?: { value: number; units: string }
+ paragraphSpacing?: number
+ paragraphIndent?: number
+ listSpacing?: number
+ hangingList?: boolean
// Symbol/Instance
symbolData?: { symbolID: GUID }
// ComponentSet
diff --git a/packages/scene-graph/AGENTS.md b/packages/scene-graph/AGENTS.md
index 059f57db2..78f17b5ea 100644
--- a/packages/scene-graph/AGENTS.md
+++ b/packages/scene-graph/AGENTS.md
@@ -13,6 +13,7 @@ Framework-neutral document model. Owns node types, primitives, geometry, matrice
- A bound numeric field records its unit conversion in `variableBindingScales`; preserve it through clone, copy, and transfer so a binding keeps meaning in its new scope. Core reconciles bindings and layout together in `packages/core/src/layout/variables.ts`, which the editor and the Figma API both call rather than reimplementing.
- `componentScale` records an occurrence's coordinates relative to its component definition. Shared rescaling lives in `packages/scene-graph/src/scaling/`; Core's Figma API delegates there instead of scaling nodes itself.
- Shared primitives that format packages and collaboration need live here: color conversion and management under `@open-pencil/scene-graph/color`, text/layout direction under `@open-pencil/scene-graph/text-direction`, and fractional sibling order keys under `@open-pencil/scene-graph/order-keys` (`packages/scene-graph/tests/order-keys.test.ts`).
+- A text's list items, and spacing a paragraph sets for itself over the text's (`paragraphSpacingAt`), are one `TextParagraphStyle` per paragraph in `textParagraphs`; `@open-pencil/scene-graph/text` numbers them (`textListItems`) and keeps the styles aligned through edits (`paragraphStylesAfterEdit`, `paragraphStylesInRange`), so the renderer, `.fig`, the Figma API, and exporters never count markers or split paragraphs themselves (`packages/scene-graph/tests/text/lists.test.ts`).
- A node's per-axis sizing (Figma's `layoutSizingHorizontal`/`Vertical`) is read and written through `packages/scene-graph/src/layout/sizing.ts`. Fill is stored on the child as Figma stores it, `layoutGrow` along the parent's primary axis (a grid's is horizontal) and `layoutAlignSelf: 'STRETCH'` across it; `primaryAxisSizing`/`counterAxisSizing` only fix or hug. Layout, the Figma API, the properties panel, and exporters call it instead of mapping axes themselves (`tests/engine/figma/api/layout/sizing.test.ts`).
- Formats read auto layout keywords (stack direction, `justify-content`, `align-items`, `align-self`, padding shorthand) through `packages/scene-graph/src/layout/keywords.ts`, and an importer builds fill and hug for a node not yet in the graph with `fillSizingFields` and `autoLayoutSizingFields`. Design JSX and `.pen` pass their own spellings straight to it, and DOM/CSS parses CSS values first with `parseCSSJustifyContent` and its siblings in `@open-pencil/scene-graph/css` (`packages/scene-graph/tests/layout/keywords.test.ts`, `packages/scene-graph/tests/css/layout.test.ts`).
- CSS values that become scene-graph types, such as grid track lists, are parsed in `@open-pencil/scene-graph/css` on `postcss-value-parser`; design-jsx and dom-css call it instead of splitting or matching CSS by hand (`packages/scene-graph/tests/css`).
diff --git a/packages/scene-graph/package.json b/packages/scene-graph/package.json
index 1ab1dbedf..6d697dfcc 100644
--- a/packages/scene-graph/package.json
+++ b/packages/scene-graph/package.json
@@ -95,6 +95,12 @@
"import": "./dist/layout.js",
"default": "./dist/layout.js"
},
+ "./text": {
+ "types": "./dist/text.d.ts",
+ "bun": "./src/text/index.ts",
+ "import": "./dist/text.js",
+ "default": "./dist/text.js"
+ },
"./types": {
"types": "./dist/types.d.ts",
"bun": "./src/types.ts",
@@ -127,7 +133,7 @@
},
"./text-picture": {
"types": "./dist/text-picture.d.ts",
- "bun": "./src/text-picture.ts",
+ "bun": "./src/text/picture.ts",
"import": "./dist/text-picture.js",
"default": "./dist/text-picture.js"
},
@@ -211,7 +217,7 @@
},
"./text-direction": {
"types": "./dist/text-direction.d.ts",
- "bun": "./src/text-direction.ts",
+ "bun": "./src/text/direction.ts",
"import": "./dist/text-direction.js",
"default": "./dist/text-direction.js"
}
diff --git a/packages/scene-graph/src/copy.ts b/packages/scene-graph/src/copy.ts
index add036930..08207bcae 100644
--- a/packages/scene-graph/src/copy.ts
+++ b/packages/scene-graph/src/copy.ts
@@ -272,6 +272,7 @@ export function cloneNodeProps(
dashPattern: copyOpt(src.dashPattern, (a) => [...a]),
fontVariations: copyOpt(src.fontVariations, (a) => a.map((v) => ({ ...v }))),
fontFeatures: copyOpt(src.fontFeatures, (a) => a.map((v) => ({ ...v }))),
+ textParagraphs: copyOpt(src.textParagraphs, (a) => a.map((v) => ({ ...v }))),
textDecorationFills: copyOpt(src.textDecorationFills, copyFills),
fillGeometry: copyOpt(src.fillGeometry, copyGeometryPaths),
strokeGeometry: copyOpt(src.strokeGeometry, copyGeometryPaths),
diff --git a/packages/scene-graph/src/fields/text.ts b/packages/scene-graph/src/fields/text.ts
index bf83bb0a8..85250050c 100644
--- a/packages/scene-graph/src/fields/text.ts
+++ b/packages/scene-graph/src/fields/text.ts
@@ -10,7 +10,12 @@ export const TEXT_METRIC_FIELDS = [
'letterSpacing',
'styleRuns',
'fontVariations',
- 'fontFeatures'
+ 'fontFeatures',
+ 'textParagraphs',
+ 'listSpacing',
+ 'paragraphSpacing',
+ 'paragraphIndent',
+ 'hangingList'
] as const satisfies readonly (keyof SceneNode)[]
export const TEXT_SHAPING_FIELDS = [
diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.ts
index 37010577c..bbb521edb 100644
--- a/packages/scene-graph/src/index.ts
+++ b/packages/scene-graph/src/index.ts
@@ -69,6 +69,7 @@ export * from './export-format'
export * from './export-scale'
export * from './coordinate'
export * from './layout'
+export * from './text'
export * from './group-bounds'
export * from './constants'
export * from './geometry'
@@ -92,7 +93,7 @@ import { CONTAINER_TYPES, createDefaultNode } from './node-defaults'
import { updateNodePreview, type NodePreviewObserver } from './preview'
import { styleDetachmentChanges } from './shared-styles'
import { markSourceFieldsEdited } from './source-metadata'
-import { GLYPH_AFFECTING_KEYS, invalidateTextCaches, TEXT_PICTURE_KEYS } from './text-picture'
+import { GLYPH_AFFECTING_KEYS, invalidateTextCaches, TEXT_PICTURE_KEYS } from './text/picture'
import * as Variables from './variables'
import type { VariableModeFallback } from './variables'
import { normalizeVectorNetwork } from './vector-network'
diff --git a/packages/scene-graph/src/node-defaults.ts b/packages/scene-graph/src/node-defaults.ts
index 3141c8ce9..74583d8b9 100644
--- a/packages/scene-graph/src/node-defaults.ts
+++ b/packages/scene-graph/src/node-defaults.ts
@@ -135,6 +135,11 @@ export function createDefaultNode(
textDecorationSkipInk: true,
textUnderlineOffset: null,
maxLines: null,
+ textParagraphs: [],
+ listSpacing: 0,
+ paragraphSpacing: 0,
+ paragraphIndent: 0,
+ hangingList: false,
styleRuns: [],
fontVariations: [],
fontFeatures: [],
diff --git a/packages/scene-graph/src/preview.ts b/packages/scene-graph/src/preview.ts
index b908827c5..e600fa0cd 100644
--- a/packages/scene-graph/src/preview.ts
+++ b/packages/scene-graph/src/preview.ts
@@ -1,4 +1,4 @@
-import { textCacheInvalidationChanges } from './text-picture'
+import { textCacheInvalidationChanges } from './text/picture'
import type { SceneNode } from './types'
import { normalizeVectorNetwork } from './vector-network'
diff --git a/packages/scene-graph/src/scaling/node.ts b/packages/scene-graph/src/scaling/node.ts
index 8b49d1cf7..4bd429f98 100644
--- a/packages/scene-graph/src/scaling/node.ts
+++ b/packages/scene-graph/src/scaling/node.ts
@@ -1,4 +1,5 @@
import { scaleGeometryPaths } from '../copy'
+import { TEXT_PARAGRAPH_SPACING_FIELDS } from '../text/paragraphs'
import {
type Effect,
type Fill,
@@ -6,7 +7,8 @@ import {
type LayoutGrid,
type SceneNode,
type Stroke,
- type StyleRun
+ type StyleRun,
+ type TextParagraphStyle
} from '../types'
import { cloneVectorNetwork } from '../vector-network'
@@ -59,6 +61,20 @@ function scaledStyleRuns(styleRuns: readonly StyleRun[], scale: number): StyleRu
}))
}
+function scaledParagraphStyles(
+ paragraphs: readonly TextParagraphStyle[],
+ scale: number
+): TextParagraphStyle[] {
+ return paragraphs.map((style) => {
+ const scaled = { ...style }
+ for (const field of TEXT_PARAGRAPH_SPACING_FIELDS) {
+ const value = style[field]
+ if (value !== undefined) scaled[field] = value * scale
+ }
+ return scaled
+ })
+}
+
function scaledLayoutGrids(grids: readonly LayoutGrid[], scale: number): LayoutGrid[] {
return grids.map((grid) => ({
...structuredClone(grid),
@@ -116,6 +132,10 @@ export function scaleNodeChanges(
textDecorationThickness: scaledOptional(node.textDecorationThickness, scale),
textUnderlineOffset: scaledOptional(node.textUnderlineOffset, scale),
styleRuns: scaledStyleRuns(node.styleRuns, scale),
+ listSpacing: node.listSpacing * scale,
+ paragraphSpacing: node.paragraphSpacing * scale,
+ paragraphIndent: node.paragraphIndent * scale,
+ textParagraphs: scaledParagraphStyles(node.textParagraphs, scale),
itemSpacing: node.itemSpacing * scale,
counterAxisSpacing: node.counterAxisSpacing * scale,
paddingTop: node.paddingTop * scale,
diff --git a/packages/scene-graph/src/text-direction.ts b/packages/scene-graph/src/text/direction.ts
similarity index 99%
rename from packages/scene-graph/src/text-direction.ts
rename to packages/scene-graph/src/text/direction.ts
index f90f523f3..995ff294b 100644
--- a/packages/scene-graph/src/text-direction.ts
+++ b/packages/scene-graph/src/text/direction.ts
@@ -1,4 +1,4 @@
-import type { LayoutDirection, SceneNode, TextDirection } from './types'
+import type { LayoutDirection, SceneNode, TextDirection } from '../types'
const RTL_CHAR_RE =
/\p{Script=Arabic}|\p{Script=Hebrew}|\p{Script=Syriac}|\p{Script=Thaana}|\p{Script=Nko}|\p{Script=Adlam}/u
diff --git a/packages/scene-graph/src/text/index.ts b/packages/scene-graph/src/text/index.ts
new file mode 100644
index 000000000..de28f35ca
--- /dev/null
+++ b/packages/scene-graph/src/text/index.ts
@@ -0,0 +1,2 @@
+export * from './lists'
+export * from './paragraphs'
diff --git a/packages/scene-graph/src/text/lists.ts b/packages/scene-graph/src/text/lists.ts
new file mode 100644
index 000000000..a36ec72d9
--- /dev/null
+++ b/packages/scene-graph/src/text/lists.ts
@@ -0,0 +1,138 @@
+import type { TextParagraphStyle } from '../types'
+import { paragraphStyleAt, textParagraphRanges, type TextParagraphRange } from './paragraphs'
+
+/** How an ordered item's number is written at its nesting level. */
+export type ListNumberFormat = 'DECIMAL' | 'LOWER_ALPHA' | 'LOWER_ROMAN'
+
+/** A list item paragraph and what marks it. */
+export interface TextListItem extends TextParagraphRange {
+ paragraph: number
+ listType: 'ORDERED' | 'UNORDERED'
+ /** Nesting level, from 1. */
+ level: number
+ /** The item's number among the items of its list at its level, from 1. */
+ ordinal: number
+ /** The marker drawn before the item: a bullet, or its number and a period. */
+ marker: string
+ /** Whether the item starts a new count at its level. */
+ startsList: boolean
+ /**
+ * The paragraph that starts the group of list items this item belongs to. A list group runs
+ * from a list item that follows a plain paragraph, or that starts a top-level list, and its
+ * first character styles every marker and indent in it.
+ */
+ groupStart: number
+}
+
+/** The marker of an unordered item, at every level. */
+export const LIST_BULLET = '•'
+
+const NUMBER_FORMATS: readonly ListNumberFormat[] = ['DECIMAL', 'LOWER_ALPHA', 'LOWER_ROMAN']
+
+/** Ordered items count in decimal, then letters, then roman numerals, repeating as they nest. */
+export function listNumberFormat(level: number): ListNumberFormat {
+ return NUMBER_FORMATS[(Math.max(1, level) - 1) % NUMBER_FORMATS.length]
+}
+
+function alphabetic(value: number): string {
+ let letters = ''
+ for (let rest = value; rest > 0; rest = Math.floor((rest - 1) / 26)) {
+ letters = String.fromCharCode(97 + ((rest - 1) % 26)) + letters
+ }
+ return letters
+}
+
+const ROMAN_DIGITS: ReadonlyArray<readonly [number, string]> = [
+ [1000, 'm'],
+ [900, 'cm'],
+ [500, 'd'],
+ [400, 'cd'],
+ [100, 'c'],
+ [90, 'xc'],
+ [50, 'l'],
+ [40, 'xl'],
+ [10, 'x'],
+ [9, 'ix'],
+ [5, 'v'],
+ [4, 'iv'],
+ [1, 'i']
+]
+
+function roman(value: number): string {
+ let rest = value
+ let numeral = ''
+ for (const [amount, digits] of ROMAN_DIGITS) {
+ for (; rest >= amount; rest -= amount) numeral += digits
+ }
+ return numeral
+}
+
+/** An ordered item's number as its level writes it, without the period. */
+export function formatListNumber(ordinal: number, format: ListNumberFormat): string {
+ if (format === 'LOWER_ALPHA') return alphabetic(ordinal)
+ if (format === 'LOWER_ROMAN') return roman(ordinal)
+ return String(ordinal)
+}
+
+interface LevelCount {
+ listType: TextListItem['listType']
+ count: number
+}
+
+/**
+ * The list items of a text, numbered as Figma numbers them: each level counts its own items,
+ * a deeper item leaves the count above it running, a shallower one restarts the counts below
+ * it, and a plain paragraph or an item of the other list type restarts the count.
+ */
+export function textListItems(
+ text: string,
+ paragraphs: readonly TextParagraphStyle[]
+): TextListItem[] {
+ if (!paragraphs.some((paragraph) => paragraph.listType !== 'NONE')) return []
+ const items: TextListItem[] = []
+ const counts: Array<LevelCount | undefined> = []
+ let groupStart = -1
+ for (const [paragraph, range] of textParagraphRanges(text).entries()) {
+ const style = paragraphStyleAt(paragraphs, paragraph)
+ if (style.listType === 'NONE') {
+ counts.length = 0
+ groupStart = -1
+ continue
+ }
+ const level = Math.max(1, style.indentation)
+ counts.length = Math.min(counts.length, level)
+ const current = counts[level - 1]
+ const continues = current?.listType === style.listType
+ const count = continues ? current.count + 1 : 1
+ counts[level - 1] = { listType: style.listType, count }
+ const shallower = counts.slice(0, level - 1).some((entry) => entry !== undefined)
+ if (groupStart === -1 || (!continues && !shallower)) groupStart = paragraph
+ const marker =
+ style.listType === 'UNORDERED'
+ ? LIST_BULLET
+ : `${formatListNumber(count, listNumberFormat(level))}.`
+ items.push({
+ ...range,
+ paragraph,
+ listType: style.listType,
+ level,
+ ordinal: count,
+ marker,
+ startsList: !continues,
+ groupStart
+ })
+ }
+ return items
+}
+
+/**
+ * Digits in the largest number of a top-level ordered item. Figma widens the indent of every
+ * ordered item by the extra digits, so a list's numbers line up past nine.
+ */
+export function topLevelNumberDigits(items: readonly TextListItem[]): number {
+ let largest = 0
+ for (const item of items) {
+ if (item.listType === 'ORDERED' && item.level === 1) largest = Math.max(largest, item.ordinal)
+ }
+ return largest === 0 ? 0 : String(largest).length
+}
diff --git a/packages/scene-graph/src/text/paragraphs.ts b/packages/scene-graph/src/text/paragraphs.ts
new file mode 100644
index 000000000..0762f0a77
--- /dev/null
+++ b/packages/scene-graph/src/text/paragraphs.ts
@@ -0,0 +1,241 @@
+import type {
+ SceneNode,
+ TextListType,
+ TextParagraphSpacingField,
+ TextParagraphStyle
+} from '../types'
+
+/** The style of a paragraph with no entry: not in a list. */
+export const PLAIN_PARAGRAPH: Readonly<TextParagraphStyle> = Object.freeze({
+ listType: 'NONE',
+ indentation: 0
+})
+
+/** Figma nests list items at most this deep. */
+export const MAX_LIST_INDENTATION = 5
+
+/** A paragraph's characters: `start` to `end`, not counting the newline that ends it. */
+export interface TextParagraphRange {
+ start: number
+ end: number
+}
+
+/** The paragraphs of `text`: one per line ending at a newline, and one after the last. */
+export function textParagraphRanges(text: string): TextParagraphRange[] {
+ const ranges: TextParagraphRange[] = []
+ let start = 0
+ for (let index = text.indexOf('\n'); index !== -1; index = text.indexOf('\n', start)) {
+ ranges.push({ start, end: index })
+ start = index + 1
+ }
+ ranges.push({ start, end: text.length })
+ return ranges
+}
+
+/** The paragraph holding character `index`; a newline belongs to the paragraph it ends. */
+export function paragraphIndexAt(text: string, index: number): number {
+ let paragraph = 0
+ const end = Math.min(index, text.length)
+ for (let at = text.indexOf('\n'); at !== -1 && at < end; at = text.indexOf('\n', at + 1)) {
+ paragraph++
+ }
+ return paragraph
+}
+
+export function paragraphStyleAt(
+ paragraphs: readonly TextParagraphStyle[],
+ paragraph: number
+): TextParagraphStyle {
+ return paragraphs[paragraph] ?? PLAIN_PARAGRAPH
+}
+
+export const TEXT_PARAGRAPH_SPACING_FIELDS: readonly TextParagraphSpacingField[] = [
+ 'listSpacing',
+ 'paragraphSpacing',
+ 'paragraphIndent'
+]
+
+/** A paragraph's spacing: its own value, or the text's when it sets none. */
+export function paragraphSpacingAt(
+ node: Pick<SceneNode, 'textParagraphs' | TextParagraphSpacingField>,
+ paragraph: number,
+ field: TextParagraphSpacingField
+): number {
+ return paragraphStyleAt(node.textParagraphs, paragraph)[field] ?? node[field]
+}
+
+/** Whether a paragraph sets any spacing of its own. */
+export function hasParagraphSpacing(style: TextParagraphStyle): boolean {
+ return TEXT_PARAGRAPH_SPACING_FIELDS.some((field) => style[field] !== undefined)
+}
+
+/** A paragraph style with its own `field` set, or following the text again for `undefined`. */
+export function withParagraphSpacing(
+ style: TextParagraphStyle,
+ field: TextParagraphSpacingField,
+ value: number | undefined
+): TextParagraphStyle {
+ const { [field]: _previous, ...rest } = style
+ return value === undefined ? rest : { ...rest, [field]: value }
+}
+
+/** Every paragraph's `field`, or `null` when they differ. */
+export function sharedParagraphSpacing(
+ node: Pick<SceneNode, 'text' | 'textParagraphs' | TextParagraphSpacingField>,
+ field: TextParagraphSpacingField,
+ first = 0,
+ last = paragraphCount(node.text) - 1
+): number | null {
+ const value = paragraphSpacingAt(node, first, field)
+ for (let index = first + 1; index <= last; index++) {
+ if (paragraphSpacingAt(node, index, field) !== value) return null
+ }
+ return value
+}
+
+/** Paragraph styles with no paragraph setting its own `field`, as setting the text's does. */
+export function paragraphStylesWithoutSpacing(
+ paragraphs: readonly TextParagraphStyle[],
+ field: TextParagraphSpacingField
+): TextParagraphStyle[] {
+ return trimParagraphStyles(
+ paragraphs.map((style) => withParagraphSpacing(style, field, undefined)),
+ paragraphs.length
+ )
+}
+
+/** Whether any paragraph of the node is a list item. */
+export function hasTextList(node: Pick<SceneNode, 'textParagraphs'>): boolean {
+ return node.textParagraphs.some((paragraph) => paragraph.listType !== 'NONE')
+}
+
+/**
+ * Paragraph styles for `count` paragraphs, without the plain paragraphs at the end, so text
+ * without lists, indentation, or paragraph spacing of its own keeps none.
+ */
+export function trimParagraphStyles(
+ paragraphs: readonly TextParagraphStyle[],
+ count: number
+): TextParagraphStyle[] {
+ const styles = paragraphs.slice(0, count).map((paragraph) => ({ ...paragraph }))
+ while (styles.length > 0) {
+ const last = styles[styles.length - 1]
+ if (last.listType !== 'NONE' || last.indentation !== 0 || hasParagraphSpacing(last)) break
+ styles.pop()
+ }
+ return styles
+}
+
+/** How many paragraphs `text` has: one more than its newlines. */
+export function paragraphCount(text: string): number {
+ let count = 1
+ for (let at = text.indexOf('\n'); at !== -1; at = text.indexOf('\n', at + 1)) count++
+ return count
+}
+
+/**
+ * Paragraph styles after replacing `text[start, end)` with `inserted`, as Figma keeps them: the
+ * paragraph the edit starts in keeps its style, paragraphs a deleted newline joins to it are
+ * dropped, and paragraphs an inserted newline starts take its style.
+ */
+export function paragraphStylesAfterEdit(
+ paragraphs: readonly TextParagraphStyle[],
+ text: string,
+ start: number,
+ end: number,
+ inserted: string
+): TextParagraphStyle[] {
+ if (paragraphs.length === 0) return []
+ const first = paragraphIndexAt(text, start)
+ const last = paragraphIndexAt(text, end)
+ const style = paragraphStyleAt(paragraphs, first)
+ const added = paragraphCount(inserted) - 1
+ const next = [
+ ...Array.from({ length: first }, (_, index) => paragraphStyleAt(paragraphs, index)),
+ ...Array.from({ length: added + 1 }, () => style),
+ ...paragraphs.slice(last + 1)
+ ]
+ return trimParagraphStyles(next, paragraphCount(text) - (last - first) + added)
+}
+
+/**
+ * Paragraph styles with every paragraph that `text[start, end)` touches changed by `change`,
+ * as a range setter changes whole paragraphs.
+ */
+export function paragraphStylesInRange(
+ paragraphs: readonly TextParagraphStyle[],
+ text: string,
+ start: number,
+ end: number,
+ change: (style: TextParagraphStyle) => TextParagraphStyle
+): TextParagraphStyle[] {
+ const count = paragraphCount(text)
+ const first = paragraphIndexAt(text, start)
+ // An empty range still names the paragraph it sits in; a range ending right after a
+ // newline does not reach into the next paragraph.
+ const last = end > start ? paragraphIndexAt(text, end - 1) : first
+ const next = Array.from({ length: count }, (_, index) => {
+ const style = paragraphStyleAt(paragraphs, index)
+ return index >= first && index <= last ? change(style) : style
+ })
+ return trimParagraphStyles(next, count)
+}
+
+/**
+ * A paragraph style with its list type set. A list item is nested at least one level, and a
+ * paragraph leaving a list keeps no indentation.
+ */
+export function withListType(
+ style: TextParagraphStyle,
+ listType: TextListType
+): TextParagraphStyle {
+ if (listType === 'NONE') return { ...style, listType, indentation: 0 }
+ return { ...style, listType, indentation: clampListIndentation(style.indentation) }
+}
+
+/** A paragraph style with its nesting set, kept in the range a list item allows. */
+export function withIndentation(
+ style: TextParagraphStyle,
+ indentation: number
+): TextParagraphStyle {
+ if (style.listType === 'NONE') {
+ return {
+ ...style,
+ indentation: Math.max(0, Math.min(MAX_LIST_INDENTATION, Math.round(indentation)))
+ }
+ }
+ return { ...style, indentation: clampListIndentation(indentation) }
+}
+
+function clampListIndentation(indentation: number): number {
+ return Math.max(1, Math.min(MAX_LIST_INDENTATION, Math.round(indentation)))
+}
+
+/**
+ * Paragraph styles after `before` became `after` through one edit, found as the text between
+ * their common start and end, for editors that replace the text rather than report the edit.
+ */
+export function paragraphStylesAfterTextChange(
+ paragraphs: readonly TextParagraphStyle[],
+ before: string,
+ after: string
+): TextParagraphStyle[] {
+ if (paragraphs.length === 0 || before === after) return paragraphs.map((style) => ({ ...style }))
+ let prefix = 0
+ const shorter = Math.min(before.length, after.length)
+ while (prefix < shorter && before[prefix] === after[prefix]) prefix++
+ let suffix = 0
+ while (
+ suffix < shorter - prefix &&
+ before[before.length - 1 - suffix] === after[after.length - 1 - suffix]
+ ) {
+ suffix++
+ }
+ return paragraphStylesAfterEdit(
+ paragraphs,
+ before,
+ prefix,
+ before.length - suffix,
+ after.slice(prefix, after.length - suffix)
+ )
+}
diff --git a/packages/scene-graph/src/text-picture.ts b/packages/scene-graph/src/text/picture.ts
similarity index 95%
rename from packages/scene-graph/src/text-picture.ts
rename to packages/scene-graph/src/text/picture.ts
index 6d518d7d4..eb99a9db4 100644
--- a/packages/scene-graph/src/text-picture.ts
+++ b/packages/scene-graph/src/text/picture.ts
@@ -1,7 +1,7 @@
import { isEqual } from 'es-toolkit/predicate'
-import { TEXT_SHAPING_FIELDS, TEXT_LAYOUT_FIELDS } from './fields/text'
-import type { SceneNode } from './types'
+import { TEXT_SHAPING_FIELDS, TEXT_LAYOUT_FIELDS } from '../fields/text'
+import type { SceneNode } from '../types'
/**
* Invalidate cached Skia textPicture (Paragraph snapshot). Includes width/height
diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.ts
index bb96e193d..0843df1b5 100644
--- a/packages/scene-graph/src/types.ts
+++ b/packages/scene-graph/src/types.ts
@@ -235,6 +235,22 @@ export type TextDecorationStyle = 'SOLID' | 'DOTTED' | 'WAVY'
export type LeadingTrim = 'NONE' | 'CAP_HEIGHT'
export type TextDirection = 'AUTO' | 'LTR' | 'RTL'
export type LayoutDirection = 'AUTO' | 'LTR' | 'RTL'
+/** Whether a paragraph is an item of a numbered list, a bulleted list, or no list. */
+export type TextListType = 'NONE' | 'ORDERED' | 'UNORDERED'
+
+/** How one paragraph of a text node (a line ending at a newline) sits in a list. */
+/** Spacing a text sets for all its paragraphs and a paragraph can set for itself. */
+export type TextParagraphSpacingField = 'listSpacing' | 'paragraphSpacing' | 'paragraphIndent'
+
+export interface TextParagraphStyle {
+ listType: TextListType
+ /** Nesting level: 1–5 for list items; kept but not drawn for plain paragraphs. */
+ indentation: number
+ /** This paragraph's own spacing, in place of the text's; absent ones follow the text. */
+ listSpacing?: number
+ paragraphSpacing?: number
+ paragraphIndent?: number
+}
export interface FontVariation {
axis: string
@@ -526,6 +542,19 @@ export interface SceneNode {
lineHeight: number | null
letterSpacing: number
maxLines: number | null
+ /**
+ * One entry per paragraph of `text`, in order. Missing entries are plain paragraphs, so text
+ * without lists keeps this empty.
+ */
+ textParagraphs: TextParagraphStyle[]
+ /** Space after a list item followed by another; a paragraph's own value comes first. */
+ listSpacing: number
+ /** Space after a paragraph other than between two list items. */
+ paragraphSpacing: number
+ /** Indent of the first line of each plain paragraph. */
+ paragraphIndent: number
+ /** Whether list markers hang outside the text box instead of indenting the items. */
+ hangingList: boolean
styleRuns: StyleRun[]
fontVariations: FontVariation[]
diff --git a/packages/scene-graph/tests/text/lists.test.ts b/packages/scene-graph/tests/text/lists.test.ts
new file mode 100644
index 000000000..259820ae3
--- /dev/null
+++ b/packages/scene-graph/tests/text/lists.test.ts
@@ -0,0 +1,96 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ paragraphStylesAfterEdit,
+ paragraphStylesAfterTextChange,
+ paragraphStylesInRange,
+ textListItems,
+ topLevelNumberDigits,
+ withIndentation,
+ withListType,
+ type TextParagraphStyle
+} from '@open-pencil/scene-graph'
+
+const ol = (indentation = 1): TextParagraphStyle => ({ listType: 'ORDERED', indentation })
+const ul = (indentation = 1): TextParagraphStyle => ({ listType: 'UNORDERED', indentation })
+const plain: TextParagraphStyle = { listType: 'NONE', indentation: 0 }
+
+function markers(paragraphs: TextParagraphStyle[]) {
+ const text = paragraphs.map((_, index) => `p${index}`).join('\n')
+ return textListItems(text, paragraphs).map((item) => item.marker)
+}
+
+// Numbers as Figma drew them in live probes (2026-10-09).
+describe('list numbering', () => {
+ test('nests decimal, letters, and roman numerals, and resumes the outer count', () => {
+ expect(markers([ol(1), ol(2), ol(2), ol(3), ol(4), ol(5), ol(1)])).toEqual([
+ '1.',
+ 'a.',
+ 'b.',
+ 'i.',
+ '1.',
+ 'a.',
+ '2.'
+ ])
+ })
+
+ test('restarts after a plain paragraph and after an item of the other type', () => {
+ expect(markers([ol(), ol(), plain, ol(), ol()])).toEqual(['1.', '2.', '1.', '2.'])
+ expect(markers([ol(), ol(), ul(), ul(), ol()])).toEqual(['1.', '2.', '•', '•', '1.'])
+ })
+
+ test('counts letters past z and roman numerals past three', () => {
+ const letters = markers([ol(1), ...Array.from({ length: 28 }, () => ol(2))])
+ expect(letters.slice(-3)).toEqual(['z.', 'aa.', 'ab.'])
+ const numerals = markers([ol(1), ol(2), ...Array.from({ length: 9 }, () => ol(3))])
+ expect(numerals.slice(2)).toEqual(['i.', 'ii.', 'iii.', 'iv.', 'v.', 'vi.', 'vii.', 'viii.', 'ix.'])
+ })
+
+ test('styles markers from the first item of each list group', () => {
+ const items = textListItems('a\nb\nc\nd\ne', [ul(), ol(), ol(2), plain, ul()])
+ expect(items.map((item) => item.groupStart)).toEqual([0, 1, 1, 4])
+ })
+
+ test('widens by the digits of the largest top-level number only', () => {
+ const items = textListItems(
+ Array.from({ length: 13 }, (_, index) => `p${index}`).join('\n'),
+ [ol(1), ...Array.from({ length: 12 }, () => ol(4))]
+ )
+ expect(topLevelNumberDigits(items)).toBe(1)
+ const long = textListItems(
+ Array.from({ length: 12 }, (_, index) => `p${index}`).join('\n'),
+ Array.from({ length: 12 }, () => ol())
+ )
+ expect(topLevelNumberDigits(long)).toBe(2)
+ })
+})
+
+describe('paragraph styles through edits', () => {
+ test('continue the list into inserted paragraphs', () => {
+ expect(paragraphStylesAfterEdit([ul(), ul()], 'a\nb', 1, 1, '\nnew')).toEqual([ul(), ul(), ul()])
+ expect(paragraphStylesAfterEdit([plain, ol()], 'a\nb', 3, 3, '\nend')).toEqual([plain, ol(), ol()])
+ })
+
+ test('keep the first paragraph style when a newline is deleted', () => {
+ expect(paragraphStylesAfterEdit([ul(), plain, ol()], 'a\nb\nc', 1, 2, '')).toEqual([ul(), ol()])
+ expect(paragraphStylesAfterEdit([plain, ol()], 'a\nb', 1, 2, '')).toEqual([])
+ })
+
+ test('follow an editor that replaces the whole text', () => {
+ // Enter at the end of an item, then joining the item back.
+ expect(paragraphStylesAfterTextChange([plain, ol()], 'a\nb', 'a\nb\n')).toEqual([plain, ol(), ol()])
+ expect(paragraphStylesAfterTextChange([ul(), ol()], 'a\nb', 'ab')).toEqual([ul()])
+ })
+
+ test('change whole paragraphs a range touches, not the one after its newline', () => {
+ const next = paragraphStylesInRange([], 'a\nb\nc', 0, 2, (style) => withListType(style, 'ORDERED'))
+ expect(next).toEqual([ol()])
+ })
+
+ test('keep list items nested one to five levels deep', () => {
+ expect(withIndentation(ul(), 0)).toEqual(ul(1))
+ expect(withIndentation(ul(), 9)).toEqual(ul(5))
+ expect(withIndentation(plain, 2)).toEqual({ listType: 'NONE', indentation: 2 })
+ expect(withListType(ol(3), 'NONE')).toEqual(plain)
+ })
+})
diff --git a/packages/scene-graph/tests/text/paragraphs.test.ts b/packages/scene-graph/tests/text/paragraphs.test.ts
new file mode 100644
index 000000000..99ad69607
--- /dev/null
+++ b/packages/scene-graph/tests/text/paragraphs.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ paragraphSpacingAt,
+ paragraphStylesAfterEdit,
+ paragraphStylesWithoutSpacing,
+ sharedParagraphSpacing,
+ trimParagraphStyles,
+ withListType,
+ withParagraphSpacing,
+ type TextParagraphStyle
+} from '@open-pencil/scene-graph'
+
+const plain: TextParagraphStyle = { listType: 'NONE', indentation: 0 }
+const node = (textParagraphs: TextParagraphStyle[]) => ({
+ text: 'A\nB\nC',
+ textParagraphs,
+ listSpacing: 4,
+ paragraphSpacing: 10,
+ paragraphIndent: 0
+})
+
+describe('paragraph spacing', () => {
+ test('follows the text unless a paragraph sets its own', () => {
+ const spaced = node([plain, { ...plain, paragraphSpacing: 25 }])
+ expect([0, 1, 2].map((index) => paragraphSpacingAt(spaced, index, 'paragraphSpacing'))).toEqual(
+ [10, 25, 10]
+ )
+ expect(sharedParagraphSpacing(spaced, 'paragraphSpacing')).toBeNull()
+ expect(sharedParagraphSpacing(spaced, 'paragraphSpacing', 2, 2)).toBe(10)
+ expect(sharedParagraphSpacing(spaced, 'listSpacing')).toBe(4)
+ })
+
+ test('is kept by trimming, list changes, and edits', () => {
+ const own = withParagraphSpacing(plain, 'paragraphIndent', 30)
+ expect(trimParagraphStyles([plain, own], 2)).toEqual([plain, own])
+ expect(withListType(own, 'ORDERED')).toEqual({
+ listType: 'ORDERED',
+ indentation: 1,
+ paragraphIndent: 30
+ })
+ expect(withListType(withListType(own, 'ORDERED'), 'NONE')).toEqual(own)
+ // A paragraph typed after one with its own spacing takes it, as Figma does.
+ expect(paragraphStylesAfterEdit([own], 'A', 1, 1, '\nZ')).toEqual([own, own])
+ })
+
+ test('follows the text again once the text sets it for every paragraph', () => {
+ const styles = [withParagraphSpacing(plain, 'paragraphSpacing', 25)]
+ expect(withParagraphSpacing(styles[0], 'paragraphSpacing', undefined)).toEqual(plain)
+ expect(paragraphStylesWithoutSpacing(styles, 'paragraphSpacing')).toEqual([])
+ expect(paragraphStylesWithoutSpacing(styles, 'listSpacing')).toEqual(styles)
+ })
+})
diff --git a/packages/scene-graph/tsdown.config.ts b/packages/scene-graph/tsdown.config.ts
index a66b9532b..7cc150073 100644
--- a/packages/scene-graph/tsdown.config.ts
+++ b/packages/scene-graph/tsdown.config.ts
@@ -12,7 +12,7 @@ export default defineConfig({
snap: './src/snap.ts',
'source-metadata': './src/source-metadata.ts',
preview: './src/preview.ts',
- 'text-picture': './src/text-picture.ts',
+ 'text-picture': './src/text/picture.ts',
undo: './src/undo.ts',
variables: './src/variables.ts',
'variant-name': './src/variant-name.ts',
@@ -28,13 +28,14 @@ export default defineConfig({
polygon: './src/polygon.ts',
guides: './src/guides.ts',
layout: './src/layout/index.ts',
+ text: './src/text/index.ts',
resize: './src/resize.ts',
'parse-path': './src/parse-path.ts',
random: './src/random.ts',
'order-keys': './src/order-keys.ts',
color: './src/color/index.ts',
css: './src/css/index.ts',
- 'text-direction': './src/text-direction.ts'
+ 'text-direction': './src/text/direction.ts'
},
platform: 'neutral',
format: ['esm'],
diff --git a/packages/vue/src/canvas/text-edit/editing.ts b/packages/vue/src/canvas/text-edit/editing.ts
index 4a2ae0075..48b33c0b3 100644
--- a/packages/vue/src/canvas/text-edit/editing.ts
+++ b/packages/vue/src/canvas/text-edit/editing.ts
@@ -3,7 +3,7 @@ import type { ShallowRef } from 'vue'
import type { Editor } from '@open-pencil/core/editor'
import { adjustRunsForDelete, adjustRunsForInsert } from '@open-pencil/core/text'
-import type { SceneNode } from '@open-pencil/scene-graph'
+import { paragraphStylesAfterTextChange, type SceneNode } from '@open-pencil/scene-graph'
const CARET_BLINK_MS = 530
@@ -140,9 +140,21 @@ export function createTextEditActions(store: Editor) {
return store.graph.getNode(id) ?? null
}
- function syncText(nodeId: string, text: string, runs?: SceneNode['styleRuns']) {
+ function syncText(
+ nodeId: string,
+ text: string,
+ runs?: SceneNode['styleRuns'],
+ paragraphs?: SceneNode['textParagraphs']
+ ) {
const changes: Partial<SceneNode> = { text }
if (runs !== undefined) changes.styleRuns = runs
+ const node = store.graph.getNode(nodeId)
+ if (paragraphs !== undefined) {
+ changes.textParagraphs = paragraphs
+ } else if (node && node.textParagraphs.length > 0) {
+ // A new paragraph continues the list it is typed in; a joined one keeps the first's style.
+ changes.textParagraphs = paragraphStylesAfterTextChange(node.textParagraphs, node.text, text)
+ }
store.updateTextEditNode(nodeId, changes)
const updated = store.graph.getNode(nodeId)
if (updated) store.textEditor?.rebuildParagraph(updated)
@@ -167,6 +179,7 @@ export function createTextEditActions(store: Editor) {
type CompositionDraft = {
baseText: string
baseRuns: SceneNode['styleRuns']
+ baseParagraphs: SceneNode['textParagraphs']
cursor: number
end: number
selectionAnchor: number | null
@@ -187,6 +200,7 @@ export function createTextEditActions(store: Editor) {
compositionDraft = {
baseText: state.text,
baseRuns: node.styleRuns,
+ baseParagraphs: node.textParagraphs,
cursor: state.cursor,
end,
selectionAnchor: state.selectionAnchor,
@@ -207,7 +221,12 @@ export function createTextEditActions(store: Editor) {
let runs = adjustRunsForDelete(draft.baseRuns, draft.start, draft.end - draft.start)
runs = adjustRunsForInsert(runs, draft.start, text.length)
- syncText(node.id, state.text, runs)
+ // Each update replaces the same base, so paragraphs an earlier update joined come back.
+ const paragraphs =
+ draft.baseParagraphs.length > 0
+ ? paragraphStylesAfterTextChange(draft.baseParagraphs, draft.baseText, state.text)
+ : undefined
+ syncText(node.id, state.text, runs, paragraphs)
}
function restoreComposition(node: SceneNode) {
@@ -217,7 +236,12 @@ export function createTextEditActions(store: Editor) {
state.text = compositionDraft.baseText
state.cursor = compositionDraft.cursor
state.selectionAnchor = compositionDraft.selectionAnchor
- syncText(node.id, compositionDraft.baseText, compositionDraft.baseRuns)
+ syncText(
+ node.id,
+ compositionDraft.baseText,
+ compositionDraft.baseRuns,
+ compositionDraft.baseParagraphs
+ )
compositionDraft = null
}
diff --git a/packages/vue/src/canvas/text-edit/formatting.ts b/packages/vue/src/canvas/text-edit/formatting.ts
index 53ce0edcf..deb4de8b2 100644
--- a/packages/vue/src/canvas/text-edit/formatting.ts
+++ b/packages/vue/src/canvas/text-edit/formatting.ts
@@ -8,7 +8,7 @@ import type { SceneNode } from '@open-pencil/scene-graph'
export function createTextFormattingActions(store: Editor) {
function applyFormatting(nodeId: string, changes: Partial<SceneNode>, label: string) {
- store.updateNodeWithUndo(nodeId, changes, label)
+ store.runTextEditStep(() => store.updateNodeWithUndo(nodeId, changes, label))
const updated = store.graph.getNode(nodeId)
if (updated) store.textEditor?.rebuildParagraph(updated)
store.requestRender()
diff --git a/packages/vue/src/canvas/text-edit/input.ts b/packages/vue/src/canvas/text-edit/input.ts
index e81ed97e5..c4f7e29c2 100644
--- a/packages/vue/src/canvas/text-edit/input.ts
+++ b/packages/vue/src/canvas/text-edit/input.ts
@@ -65,7 +65,7 @@ export function createTextEditInput(options: TextEditInputOptions) {
textEd.setCursorAt(localX, localY, shiftKey)
setDrag({ type: 'text-select', startX: cx, startY: cy })
}
- editor.requestRender()
+ editor.textSelectionChanged()
return true
}
@@ -78,7 +78,7 @@ export function createTextEditInput(options: TextEditInputOptions) {
if (textEd) {
const abs = editor.graph.getAbsolutePosition(hit.id)
textEd.selectWordAt(cx - abs.x, cy - abs.y)
- editor.requestRender()
+ editor.textSelectionChanged()
}
}
diff --git a/packages/vue/src/canvas/text-edit/keyboard.ts b/packages/vue/src/canvas/text-edit/keyboard.ts
index c2953cd95..98e12ff39 100644
--- a/packages/vue/src/canvas/text-edit/keyboard.ts
+++ b/packages/vue/src/canvas/text-edit/keyboard.ts
@@ -1,5 +1,5 @@
import type { Editor } from '@open-pencil/core/editor'
-import type { SceneNode } from '@open-pencil/scene-graph'
+import type { SceneNode, TextListType } from '@open-pencil/scene-graph'
import { extendSelectionForDeletion, handleNavigationKey } from './navigation'
@@ -17,12 +17,17 @@ type TextKeyboardOptions = {
toggleBold: (node: SceneNode) => void
toggleItalic: (node: SceneNode) => void
toggleUnderline: (node: SceneNode) => void
+ toggleListType: (node: SceneNode, listType: Exclude<TextListType, 'NONE'>) => void
+ changeIndentation: (node: SceneNode, delta: 1 | -1) => boolean
}
export function createTextKeyDownHandler(options: TextKeyboardOptions) {
type MetaAction = (node: SceneNode) => void
const metaKeyActions: Partial<Record<string, MetaAction>> = {
- KeyA: () => options.store.textEditor?.selectAll(),
+ KeyA: () => {
+ options.store.textEditor?.selectAll()
+ options.store.textSelectionChanged()
+ },
KeyC: () => options.handleCopy(),
KeyX: (node) => options.handleCut(node),
KeyV: (node) => void options.handlePaste(node),
@@ -31,8 +36,14 @@ export function createTextKeyDownHandler(options: TextKeyboardOptions) {
KeyU: (node) => options.toggleUnderline(node)
}
+ // Figma's list shortcuts: ⌘⇧8 for bullets, ⌘⇧7 for numbers.
+ const metaShiftKeyActions: Partial<Record<string, MetaAction>> = {
+ Digit8: (node) => options.toggleListType(node, 'UNORDERED'),
+ Digit7: (node) => options.toggleListType(node, 'ORDERED')
+ }
+
function handleMetaKey(e: KeyboardEvent, node: SceneNode) {
- const action = metaKeyActions[e.code]
+ const action = (e.shiftKey ? metaShiftKeyActions : metaKeyActions)[e.code]
if (!action) return false
action(node)
e.preventDefault()
@@ -58,6 +69,9 @@ export function createTextKeyDownHandler(options: TextKeyboardOptions) {
if (e.code === 'Enter') {
options.insertText('\n', node)
textChanged = true
+ } else if (e.code === 'Tab' && !isMeta) {
+ // Tab nests a list item and Shift+Tab unnests it; outside a list Tab keeps its default.
+ if (!options.changeIndentation(node, e.shiftKey ? -1 : 1)) return
} else if (e.code === 'Backspace' || e.code === 'Delete') {
extendSelectionForDeletion(e, editor)
options.deleteText(node, e.code === 'Delete')
@@ -67,7 +81,8 @@ export function createTextKeyDownHandler(options: TextKeyboardOptions) {
return
}
- if (!textChanged) options.store.requestRender()
+ // Moving the caret changes no text: the overlay repaints and the panel follows it.
+ if (!textChanged) options.store.textSelectionChanged()
options.resetBlink()
e.preventDefault()
}
diff --git a/packages/vue/src/canvas/text-edit/paragraphs.ts b/packages/vue/src/canvas/text-edit/paragraphs.ts
new file mode 100644
index 000000000..9b16b38f5
--- /dev/null
+++ b/packages/vue/src/canvas/text-edit/paragraphs.ts
@@ -0,0 +1,122 @@
+import type { Editor } from '@open-pencil/core/editor'
+import {
+ paragraphIndexAt,
+ paragraphStyleAt,
+ paragraphStylesInRange,
+ paragraphStylesWithoutSpacing,
+ sharedParagraphSpacing,
+ withIndentation,
+ withListType,
+ withParagraphSpacing,
+ type SceneNode,
+ type TextListType,
+ type TextParagraphSpacingField,
+ type TextParagraphStyle
+} from '@open-pencil/scene-graph'
+
+/**
+ * The characters paragraph changes apply to: the selection or the caret's paragraph while the
+ * text is being edited, and the whole text otherwise, as in Figma.
+ */
+function listRange(store: Editor, node: SceneNode): [number, number] {
+ const editor = store.state.editingTextId === node.id ? store.textEditor : null
+ if (!editor?.state) return [0, node.text.length]
+ return editor.getSelectionRange() ?? [editor.state.cursor, editor.state.cursor]
+}
+
+function rangeParagraphs(node: SceneNode, [start, end]: [number, number]): [number, number] {
+ const first = paragraphIndexAt(node.text, start)
+ return [first, end > start ? paragraphIndexAt(node.text, end - 1) : first]
+}
+
+function rangeStyles(node: SceneNode, range: [number, number]): TextParagraphStyle[] {
+ const [first, last] = rangeParagraphs(node, range)
+ return Array.from({ length: last - first + 1 }, (_, index) =>
+ paragraphStyleAt(node.textParagraphs, first + index)
+ )
+}
+
+/** The list type of the paragraphs list changes apply to, or `null` when they differ. */
+export function listTypeOf(store: Editor, node: SceneNode): TextListType | null {
+ const types = new Set(rangeStyles(node, listRange(store, node)).map((style) => style.listType))
+ const [type] = types
+ return types.size === 1 ? type : null
+}
+
+/** The spacing of the paragraphs changes apply to, or `null` when they differ. */
+export function paragraphSpacingOf(
+ store: Editor,
+ node: SceneNode,
+ field: TextParagraphSpacingField
+): number | null {
+ return sharedParagraphSpacing(node, field, ...rangeParagraphs(node, listRange(store, node)))
+}
+
+/**
+ * The change that gives the paragraphs changes apply to spacing `value`: their own while the
+ * text is edited, and the text's for all of them otherwise.
+ */
+export function paragraphSpacingChanges(
+ store: Editor,
+ node: SceneNode,
+ field: TextParagraphSpacingField,
+ value: number
+): Partial<SceneNode> {
+ if (store.state.editingTextId !== node.id) {
+ return {
+ [field]: value,
+ textParagraphs: paragraphStylesWithoutSpacing(node.textParagraphs, field)
+ }
+ }
+ const [start, end] = listRange(store, node)
+ return {
+ textParagraphs: paragraphStylesInRange(node.textParagraphs, node.text, start, end, (style) =>
+ withParagraphSpacing(style, field, value)
+ )
+ }
+}
+
+export function createTextListActions(store: Editor) {
+ function apply(
+ node: SceneNode,
+ change: (style: TextParagraphStyle) => TextParagraphStyle,
+ label: string
+ ) {
+ const [start, end] = listRange(store, node)
+ const textParagraphs = paragraphStylesInRange(
+ node.textParagraphs,
+ node.text,
+ start,
+ end,
+ change
+ )
+ store.runTextEditStep(() => store.updateNodeWithUndo(node.id, { textParagraphs }, label))
+ const updated = store.graph.getNode(node.id)
+ if (updated) store.textEditor?.rebuildParagraph(updated)
+ store.requestRender()
+ }
+
+ function setListType(node: SceneNode, listType: TextListType) {
+ apply(node, (style) => withListType(style, listType), 'Change list style')
+ }
+
+ /** A list shortcut makes the paragraphs that list, or plain when they already are. */
+ function toggleListType(node: SceneNode, listType: Exclude<TextListType, 'NONE'>) {
+ setListType(node, listTypeOf(store, node) === listType ? 'NONE' : listType)
+ }
+
+ /** Nests or unnests list items; returns whether any paragraph was a list item to change. */
+ function changeIndentation(node: SceneNode, delta: 1 | -1): boolean {
+ const styles = rangeStyles(node, listRange(store, node))
+ if (!styles.some((style) => style.listType !== 'NONE')) return false
+ apply(
+ node,
+ (style) =>
+ style.listType === 'NONE' ? style : withIndentation(style, style.indentation + delta),
+ delta > 0 ? 'Indent list item' : 'Outdent list item'
+ )
+ return true
+ }
+
+ return { setListType, toggleListType, changeIndentation }
+}
diff --git a/packages/vue/src/canvas/text-edit/use.ts b/packages/vue/src/canvas/text-edit/use.ts
index a5a7ec3c9..c6d78463d 100644
--- a/packages/vue/src/canvas/text-edit/use.ts
+++ b/packages/vue/src/canvas/text-edit/use.ts
@@ -7,6 +7,7 @@ import { createTextClipboardActions } from './clipboard'
import { createCaretBlink, createTextCompositionHandlers, createTextEditActions } from './editing'
import { createTextFormattingActions } from './formatting'
import { createTextKeyDownHandler } from './keyboard'
+import { createTextListActions } from './paragraphs'
import { focusTextAreaOnCanvasPointerDown, useTextEditingSession } from './textarea'
/**
@@ -32,6 +33,7 @@ export function useTextEdit(
deleteText
} = createTextEditActions(store)
const { toggleBold, toggleItalic, toggleUnderline } = createTextFormattingActions(store)
+ const { toggleListType, changeIndentation } = createTextListActions(store)
const { handleCopy, handleCut, handlePaste } = createTextClipboardActions({
store,
@@ -69,7 +71,9 @@ export function useTextEdit(
handlePaste,
toggleBold,
toggleItalic,
- toggleUnderline
+ toggleUnderline,
+ toggleListType,
+ changeIndentation
})
useEventListener(textareaRef, 'input', onInput)
diff --git a/packages/vue/src/canvas/transform/text-selection.ts b/packages/vue/src/canvas/transform/text-selection.ts
index 1bb6baa1a..797282551 100644
--- a/packages/vue/src/canvas/transform/text-selection.ts
+++ b/packages/vue/src/canvas/transform/text-selection.ts
@@ -8,6 +8,6 @@ export function handleTextSelectMove(editor: Editor, cx: number, cy: number) {
if (textEditor && editNode) {
const abs = editor.graph.getAbsolutePosition(editNode.id)
textEditor.setCursorAt(cx - abs.x, cy - abs.y, true)
- editor.requestRender()
+ editor.textSelectionChanged()
}
}
diff --git a/packages/vue/src/controls/typography/actions.ts b/packages/vue/src/controls/typography/actions.ts
index 7628604c5..7c368953f 100644
--- a/packages/vue/src/controls/typography/actions.ts
+++ b/packages/vue/src/controls/typography/actions.ts
@@ -3,8 +3,19 @@ import type { ComputedRef } from 'vue'
import type { Editor } from '@open-pencil/core/editor'
import { FONT_WEIGHT_NAMES, weightToStyle } from '@open-pencil/core/text'
-import type { SceneNode, TextDecoration } from '@open-pencil/scene-graph'
+import type {
+ SceneNode,
+ TextDecoration,
+ TextListType,
+ TextParagraphSpacingField
+} from '@open-pencil/scene-graph'
+import {
+ createTextListActions,
+ listTypeOf,
+ paragraphSpacingChanges,
+ paragraphSpacingOf
+} from '#vue/canvas/text-edit/paragraphs'
import { MIXED, type MixedValue } from '#vue/controls/node-props/use'
import type { UseTypographyOptions } from '#vue/controls/typography/use'
import { useSceneComputed } from '#vue/internal/scene-computed/use'
@@ -54,12 +65,29 @@ export function createTypographyState(editor: Editor) {
() => FONT_WEIGHT_NAMES[node.value?.fontWeight ?? 400] ?? 'Regular'
)
const activeFormatting = computed(() => sharedFormatting(nodes.value))
+ /**
+ * The list style every selected text shares, or that of the paragraphs being edited; `null`
+ * when they differ.
+ */
+ const listType = computed(() => {
+ void editor.state.textSelectionVersion
+ const shared = sharedValue(nodes.value.map((n) => listTypeOf(editor, n)))
+ return shared === MIXED ? null : shared
+ })
/** The value every selected text layer shares, or MIXED when they differ. */
function merged<K extends keyof SceneNode>(key: K): MixedValue<SceneNode[K]> {
return sharedValue(nodes.value.map((n) => n[key]))
}
+ /** A spacing every paragraph changes apply to shares, or MIXED when they differ. */
+ function paragraphSpacing(field: TextParagraphSpacingField): MixedValue<number> {
+ void editor.state.textSelectionVersion
+ const values = nodes.value.map((n) => paragraphSpacingOf(editor, n, field))
+ const shared = sharedValue(values)
+ return shared === null ? MIXED : shared
+ }
+
/** Whether one OpenType feature is on for every text layer, MIXED when they differ. */
function fontFeature(tag: string): MixedValue<boolean> {
return sharedValue(
@@ -71,12 +99,14 @@ export function createTypographyState(editor: Editor) {
node,
nodes,
merged,
+ paragraphSpacing,
fontFeature,
fontFamily,
fontWeight,
fontSize,
currentWeightLabel,
activeFormatting,
+ listType,
missingFonts,
hasMissingFonts
}
@@ -95,6 +125,7 @@ export function createTypographyActions({
activeFormatting,
options
}: TypographyActionOptions) {
+ const lists = createTextListActions(editor)
type Preview = { value: SceneNode[keyof SceneNode]; textStyleId: string | null }
let previewKey: keyof SceneNode | undefined
const beforePreview = new Map<string, Preview>()
@@ -160,6 +191,72 @@ export function createTypographyActions({
}))
}
+ function setListType(listType: TextListType) {
+ const targets = nodes.value
+ if (targets.length === 0) return
+ editor.undo.runBatch('Change list style', () => {
+ for (const target of targets) lists.setListType(target, listType)
+ })
+ }
+
+ type SpacingPreview = Pick<SceneNode, TextParagraphSpacingField | 'textParagraphs'>
+ let spacingPreviewField: TextParagraphSpacingField | undefined
+ const beforeSpacing = new Map<string, SpacingPreview>()
+
+ function previewParagraphSpacing(field: TextParagraphSpacingField, value: number) {
+ if (spacingPreviewField !== field) {
+ restoreSpacingPreview()
+ spacingPreviewField = field
+ }
+ for (const target of nodes.value) {
+ if (!beforeSpacing.has(target.id)) {
+ const { listSpacing, paragraphSpacing, paragraphIndent, textParagraphs } = target
+ beforeSpacing.set(target.id, {
+ listSpacing,
+ paragraphSpacing,
+ paragraphIndent,
+ textParagraphs
+ })
+ }
+ editor.updateNode(target.id, paragraphSpacingChanges(editor, target, field, value))
+ }
+ editor.requestRender()
+ }
+
+ function restoreSpacingPreview() {
+ for (const [id, before] of beforeSpacing) editor.updateNode(id, before)
+ beforeSpacing.clear()
+ spacingPreviewField = undefined
+ }
+
+ /**
+ * Sets a spacing for the paragraphs being edited, or for whole text layers, in one undo step;
+ * while text is edited the change is a step of its own after what was typed.
+ */
+ function setParagraphSpacing(field: TextParagraphSpacingField, value: number) {
+ restoreSpacingPreview()
+ const targets = nodes.value
+ if (targets.length === 0) return
+ const label = `Change ${field}`
+ editor.runTextEditStep(() => {
+ editor.undo.runBatch(label, () => {
+ for (const target of targets) {
+ const current = editor.graph.getNode(target.id) ?? target
+ editor.updateNodeWithUndo(
+ target.id,
+ paragraphSpacingChanges(editor, current, field, value),
+ label
+ )
+ }
+ })
+ })
+ editor.requestRender()
+ }
+
+ function setHangingList(hangingList: boolean) {
+ update('Change hanging lists', { hangingList })
+ }
+
/** Bold unless every text layer already is, as Figma's toggle does for a mixed selection. */
function toggleBold() {
const bold = activeFormatting.value.includes('bold')
@@ -235,6 +332,10 @@ export function createTypographyActions({
setTextCase,
setTruncation,
setFontFeature,
+ setListType,
+ previewParagraphSpacing,
+ setParagraphSpacing,
+ setHangingList,
toggleBold,
toggleItalic,
toggleDecoration,
diff --git a/packages/vue/src/i18n/locales/de/panels.json b/packages/vue/src/i18n/locales/de/panels.json
index 96ccec2b6..02bbfa3e8 100644
--- a/packages/vue/src/i18n/locales/de/panels.json
+++ b/packages/vue/src/i18n/locales/de/panels.json
@@ -45,6 +45,15 @@
"truncationDisabled": "Deaktiviert",
"truncationEnding": "Auslassung am Ende",
"maxLines": "Maximale Zeilen",
+ "listsAndParagraphs": "Listen und Absätze",
+ "listStyle": "Listenstil",
+ "listNone": "Keine Liste",
+ "listBulleted": "Aufzählung",
+ "listNumbered": "Nummerierte Liste",
+ "listSpacing": "Listenabstand",
+ "paragraphSpacing": "Absatzabstand",
+ "paragraphIndent": "Absatzeinzug",
+ "hangingLists": "Hängende Listen",
"openTypeFeatures": "Schrifteigenschaften",
"standardLigatures": "Standardligaturen",
"contextualAlternates": "Kontextvarianten",
diff --git a/packages/vue/src/i18n/locales/es/panels.json b/packages/vue/src/i18n/locales/es/panels.json
index 0e8f52d9e..20c3b0c1b 100644
--- a/packages/vue/src/i18n/locales/es/panels.json
+++ b/packages/vue/src/i18n/locales/es/panels.json
@@ -57,6 +57,15 @@
"truncationDisabled": "Desactivado",
"truncationEnding": "Puntos suspensivos finales",
"maxLines": "Líneas máximas",
+ "listsAndParagraphs": "Listas y párrafos",
+ "listStyle": "Estilo de lista",
+ "listNone": "Sin lista",
+ "listBulleted": "Lista con viñetas",
+ "listNumbered": "Lista numerada",
+ "listSpacing": "Espaciado de lista",
+ "paragraphSpacing": "Espaciado de párrafo",
+ "paragraphIndent": "Sangría de párrafo",
+ "hangingLists": "Listas colgantes",
"openTypeFeatures": "Funciones de fuente",
"standardLigatures": "Ligaduras estándar",
"contextualAlternates": "Alternativas contextuales",
diff --git a/packages/vue/src/i18n/locales/fr/panels.json b/packages/vue/src/i18n/locales/fr/panels.json
index 1f73491ed..d0a941507 100644
--- a/packages/vue/src/i18n/locales/fr/panels.json
+++ b/packages/vue/src/i18n/locales/fr/panels.json
@@ -45,6 +45,15 @@
"truncationDisabled": "Désactivée",
"truncationEnding": "Points de suspension finaux",
"maxLines": "Lignes maximales",
+ "listsAndParagraphs": "Listes et paragraphes",
+ "listStyle": "Style de liste",
+ "listNone": "Aucune liste",
+ "listBulleted": "Liste à puces",
+ "listNumbered": "Liste numérotée",
+ "listSpacing": "Espacement de liste",
+ "paragraphSpacing": "Espacement des paragraphes",
+ "paragraphIndent": "Retrait de paragraphe",
+ "hangingLists": "Listes en retrait négatif",
"openTypeFeatures": "Propriétés de police",
"standardLigatures": "Ligatures standard",
"contextualAlternates": "Variantes contextuelles",
diff --git a/packages/vue/src/i18n/locales/it/panels.json b/packages/vue/src/i18n/locales/it/panels.json
index a98fda85a..296f3bfc9 100644
--- a/packages/vue/src/i18n/locales/it/panels.json
+++ b/packages/vue/src/i18n/locales/it/panels.json
@@ -45,6 +45,15 @@
"truncationDisabled": "Disattivato",
"truncationEnding": "Puntini finali",
"maxLines": "Righe massime",
+ "listsAndParagraphs": "Elenchi e paragrafi",
+ "listStyle": "Stile elenco",
+ "listNone": "Nessun elenco",
+ "listBulleted": "Elenco puntato",
+ "listNumbered": "Elenco numerato",
+ "listSpacing": "Spaziatura elenco",
+ "paragraphSpacing": "Spaziatura paragrafo",
+ "paragraphIndent": "Rientro paragrafo",
+ "hangingLists": "Elenchi sporgenti",
"openTypeFeatures": "Funzioni del font",
"standardLigatures": "Legature standard",
"contextualAlternates": "Alternative contestuali",
diff --git a/packages/vue/src/i18n/locales/ja/panels.json b/packages/vue/src/i18n/locales/ja/panels.json
index 341682c3a..dbc06487c 100644
--- a/packages/vue/src/i18n/locales/ja/panels.json
+++ b/packages/vue/src/i18n/locales/ja/panels.json
@@ -57,6 +57,15 @@
"truncationDisabled": "無効",
"truncationEnding": "末尾を省略",
"maxLines": "最大行数",
+ "listsAndParagraphs": "リストと段落",
+ "listStyle": "リストスタイル",
+ "listNone": "リストなし",
+ "listBulleted": "箇条書きリスト",
+ "listNumbered": "番号付きリスト",
+ "listSpacing": "リストの間隔",
+ "paragraphSpacing": "段落の間隔",
+ "paragraphIndent": "段落のインデント",
+ "hangingLists": "ぶら下げリスト",
"openTypeFeatures": "フォント機能",
"standardLigatures": "標準合字",
"contextualAlternates": "文脈依存字形",
diff --git a/packages/vue/src/i18n/locales/pl/panels.json b/packages/vue/src/i18n/locales/pl/panels.json
index d5a8ec745..c0ba20189 100644
--- a/packages/vue/src/i18n/locales/pl/panels.json
+++ b/packages/vue/src/i18n/locales/pl/panels.json
@@ -45,6 +45,15 @@
"truncationDisabled": "Wyłączone",
"truncationEnding": "Wielokropek na końcu",
"maxLines": "Maksymalna liczba wierszy",
+ "listsAndParagraphs": "Listy i akapity",
+ "listStyle": "Styl listy",
+ "listNone": "Bez listy",
+ "listBulleted": "Lista punktowana",
+ "listNumbered": "Lista numerowana",
+ "listSpacing": "Odstęp listy",
+ "paragraphSpacing": "Odstęp akapitu",
+ "paragraphIndent": "Wcięcie akapitu",
+ "hangingLists": "Wiszące listy",
"openTypeFeatures": "Funkcje czcionki",
"standardLigatures": "Ligatury standardowe",
"contextualAlternates": "Alternatywy kontekstowe",
diff --git a/packages/vue/src/i18n/locales/ru/panels.json b/packages/vue/src/i18n/locales/ru/panels.json
index f2db9b92b..999535662 100644
--- a/packages/vue/src/i18n/locales/ru/panels.json
+++ b/packages/vue/src/i18n/locales/ru/panels.json
@@ -45,6 +45,15 @@
"truncationDisabled": "Отключена",
"truncationEnding": "Многоточие в конце",
"maxLines": "Максимум строк",
+ "listsAndParagraphs": "Списки и абзацы",
+ "listStyle": "Стиль списка",
+ "listNone": "Без списка",
+ "listBulleted": "Маркированный список",
+ "listNumbered": "Нумерованный список",
+ "listSpacing": "Интервал списка",
+ "paragraphSpacing": "Интервал между абзацами",
+ "paragraphIndent": "Отступ абзаца",
+ "hangingLists": "Висячие списки",
"openTypeFeatures": "Свойства шрифта",
"standardLigatures": "Стандартные лигатуры",
"contextualAlternates": "Контекстные варианты",
diff --git a/packages/vue/src/i18n/locales/zh-cn/panels.json b/packages/vue/src/i18n/locales/zh-cn/panels.json
index 2849d6640..66f02d215 100644
--- a/packages/vue/src/i18n/locales/zh-cn/panels.json
+++ b/packages/vue/src/i18n/locales/zh-cn/panels.json
@@ -45,6 +45,15 @@
"truncationDisabled": "禁用",
"truncationEnding": "末尾省略号",
"maxLines": "最大行数",
+ "listsAndParagraphs": "列表和段落",
+ "listStyle": "列表样式",
+ "listNone": "无列表",
+ "listBulleted": "项目符号列表",
+ "listNumbered": "编号列表",
+ "listSpacing": "列表间距",
+ "paragraphSpacing": "段落间距",
+ "paragraphIndent": "段落缩进",
+ "hangingLists": "悬挂列表",
"openTypeFeatures": "字体功能",
"standardLigatures": "标准连字",
"contextualAlternates": "上下文替代字形",
diff --git a/packages/vue/src/i18n/messages/panels.ts b/packages/vue/src/i18n/messages/panels.ts
index 0e28f7e4f..4880b9dff 100644
--- a/packages/vue/src/i18n/messages/panels.ts
+++ b/packages/vue/src/i18n/messages/panels.ts
@@ -188,6 +188,15 @@ export const panelMessageDefaults = {
truncationDisabled: 'Disabled',
truncationEnding: 'Ending ellipsis',
maxLines: 'Maximum lines',
+ listsAndParagraphs: 'Lists and paragraphs',
+ listStyle: 'List style',
+ listNone: 'No list',
+ listBulleted: 'Bulleted list',
+ listNumbered: 'Numbered list',
+ listSpacing: 'List spacing',
+ paragraphSpacing: 'Paragraph spacing',
+ paragraphIndent: 'Paragraph indent',
+ hangingLists: 'Hanging lists',
openTypeFeatures: 'Font features',
standardLigatures: 'Standard ligatures',
contextualAlternates: 'Contextual alternates',
diff --git a/packages/vue/src/primitives/NumberField/NumberFieldRoot.vue b/packages/vue/src/primitives/NumberField/NumberFieldRoot.vue
index 8b37ce889..da4a44b93 100644
--- a/packages/vue/src/primitives/NumberField/NumberFieldRoot.vue
+++ b/packages/vue/src/primitives/NumberField/NumberFieldRoot.vue
@@ -213,7 +213,8 @@ function startScrub(event: PointerEvent) {
const startX = event.clientX
let lastX = startX
- let accumulated = numericValue.value
+ const startValue = numericValue.value
+ let accumulated = startValue
let hasMoved = false
const target = event.currentTarget instanceof Element ? event.currentTarget : undefined
scrubTarget = target
@@ -233,7 +234,9 @@ function startScrub(event: PointerEvent) {
}
if (!hasMoved) return
accumulated += dx * stepValue.value * sensitivity
- updateValue(accumulated)
+ // Pointer movement is fractional on high-density screens; the value moves in whole steps.
+ const steps = Math.round((accumulated - startValue) / stepValue.value)
+ updateValue(startValue + steps * stepValue.value)
})
const finish = (cancelled: boolean) => {
diff --git a/packages/vue/src/primitives/TypographyControls/TypographyControlsRoot.vue b/packages/vue/src/primitives/TypographyControls/TypographyControlsRoot.vue
index 5c443b366..f2812264c 100644
--- a/packages/vue/src/primitives/TypographyControls/TypographyControlsRoot.vue
+++ b/packages/vue/src/primitives/TypographyControls/TypographyControlsRoot.vue
@@ -26,6 +26,10 @@ const actions = {
setTextCase: ctx.setTextCase,
setTruncation: ctx.setTruncation,
setFontFeature: ctx.setFontFeature,
+ setListType: ctx.setListType,
+ setHangingList: ctx.setHangingList,
+ previewParagraphSpacing: ctx.previewParagraphSpacing,
+ setParagraphSpacing: ctx.setParagraphSpacing,
updateProp: ctx.updateProp,
commitProp: ctx.commitProp,
align: onAlignChange,
@@ -41,11 +45,13 @@ const actions = {
:node="ctx.node"
:nodes="ctx.nodes"
:merged="ctx.merged"
+ :paragraph-spacing="ctx.paragraphSpacing"
:font-feature="ctx.fontFeature"
:weights="ctx.weights"
:missing-fonts="ctx.missingFonts"
:has-missing-fonts="ctx.hasMissingFonts"
:active-formatting="ctx.activeFormatting"
+ :list-type="ctx.listType"
:actions="actions"
/>
</template>
diff --git a/packages/vue/tests/canvas/text-edit/paragraphs.test.ts b/packages/vue/tests/canvas/text-edit/paragraphs.test.ts
new file mode 100644
index 000000000..6eabf8a25
--- /dev/null
+++ b/packages/vue/tests/canvas/text-edit/paragraphs.test.ts
@@ -0,0 +1,74 @@
+import { afterEach, describe, expect, test } from 'bun:test'
+
+import { createEditor, type Editor } from '@open-pencil/core/editor'
+
+import {
+ createTextListActions,
+ listTypeOf,
+ paragraphSpacingChanges,
+ paragraphSpacingOf
+} from '#vue/canvas/text-edit/paragraphs'
+
+let editor: Editor
+
+afterEach(() => editor.dispose())
+
+function textWithList() {
+ editor = createEditor()
+ const node = editor.graph.createNode('TEXT', editor.state.currentPageId, {
+ text: 'Intro\nOne\nTwo',
+ textParagraphs: [
+ { listType: 'NONE', indentation: 0 },
+ { listType: 'UNORDERED', indentation: 1 }
+ ]
+ })
+ const read = () => editor.graph.getNode(node.id) ?? node
+ return { node, read, lists: createTextListActions(editor) }
+}
+
+describe('text list actions', () => {
+ test('change the whole text outside editing, in one undo step', () => {
+ const { read, lists } = textWithList()
+ expect(listTypeOf(editor, read())).toBeNull()
+
+ lists.setListType(read(), 'ORDERED')
+ expect(listTypeOf(editor, read())).toBe('ORDERED')
+ expect(read().textParagraphs).toHaveLength(3)
+
+ editor.undoAction()
+ expect(read().textParagraphs.map((style) => style.listType)).toEqual(['NONE', 'UNORDERED'])
+ })
+
+ test('toggle a list shortcut off when the text already is that list', () => {
+ const { read, lists } = textWithList()
+ lists.toggleListType(read(), 'UNORDERED')
+ expect(listTypeOf(editor, read())).toBe('UNORDERED')
+ lists.toggleListType(read(), 'UNORDERED')
+ expect(read().textParagraphs).toEqual([])
+ })
+
+ test('nest list items only, and leave Tab to plain text', () => {
+ const { read, lists } = textWithList()
+ lists.setListType(read(), 'NONE')
+ expect(lists.changeIndentation(read(), 1)).toBe(false)
+
+ lists.setListType(read(), 'UNORDERED')
+ expect(lists.changeIndentation(read(), 1)).toBe(true)
+ expect(read().textParagraphs.map((style) => style.indentation)).toEqual([2, 2, 2])
+ })
+})
+
+describe('paragraph spacing', () => {
+ test('sets the whole text outside editing, dropping paragraphs\' own values', () => {
+ const { node, read } = textWithList()
+ editor.graph.updateNode(node.id, {
+ textParagraphs: [{ listType: 'NONE', indentation: 0, paragraphSpacing: 25 }]
+ })
+ expect(paragraphSpacingOf(editor, read(), 'paragraphSpacing')).toBeNull()
+ expect(paragraphSpacingChanges(editor, read(), 'paragraphSpacing', 8)).toEqual({
+ paragraphSpacing: 8,
+ textParagraphs: []
+ })
+ })
+})
+
diff --git a/src/components/properties/TypographySection.vue b/src/components/properties/TypographySection.vue
index 3638e30c5..d21c8870a 100644
--- a/src/components/properties/TypographySection.vue
+++ b/src/components/properties/TypographySection.vue
@@ -42,6 +42,23 @@ const textCaseOptions = computed(() => [
{ value: 'LOWER', label: panels.value.textCaseLower },
{ value: 'TITLE', label: panels.value.textCaseTitle }
])
+const listOptions = computed(() => [
+ { value: 'NONE', label: panels.value.listNone },
+ { value: 'UNORDERED', label: panels.value.listBulleted },
+ { value: 'ORDERED', label: panels.value.listNumbered }
+])
+const paragraphFields = computed(
+ () =>
+ [
+ { key: 'listSpacing', label: panels.value.listSpacing, property: 'list-spacing' },
+ {
+ key: 'paragraphSpacing',
+ label: panels.value.paragraphSpacing,
+ property: 'paragraph-spacing'
+ },
+ { key: 'paragraphIndent', label: panels.value.paragraphIndent, property: 'paragraph-indent' }
+ ] as const
+)
const truncationOptions = computed(() => [
{ value: 'DISABLED', label: panels.value.truncationDisabled },
{ value: 'ENDING', label: panels.value.truncationEnding }
@@ -297,6 +314,74 @@ function picked<T>(value: MixedValue<T>): T | '' {
</PanelFieldGroup>
</div>
+ <div class="border-t border-border pt-3">
+ <PanelFieldGroup
+ :label="panels.listsAndParagraphs"
+ class="mb-3"
+ data-property="lists-and-paragraphs"
+ >
+ <div class="flex flex-col gap-1.5">
+ <div class="flex items-center gap-1.5">
+ <SegmentedControl
+ class="flex-1"
+ :model-value="ctx.listType.value ?? ''"
+ :options="listOptions"
+ :label="panels.listStyle"
+ data-property="list-style"
+ @change="ctx.actions.setListType($event as 'NONE' | 'ORDERED' | 'UNORDERED')"
+ >
+ <template #option="{ option }">
+ <icon-lucide-list v-if="option.value === 'UNORDERED'" class="size-3.5" />
+ <icon-lucide-list-ordered
+ v-else-if="option.value === 'ORDERED'"
+ class="size-3.5"
+ />
+ <icon-lucide-minus v-else class="size-3.5" />
+ </template>
+ </SegmentedControl>
+ <IconButton
+ :label="panels.hangingLists"
+ :active="ctx.merged('hangingList') === true"
+ data-property="hanging-lists"
+ @click="ctx.actions.setHangingList(ctx.merged('hangingList') !== true)"
+ >
+ <icon-lucide-list-indent-decrease class="size-3.5" />
+ </IconButton>
+ </div>
+ <PanelGrid :columns="3">
+ <Tip v-for="field in paragraphFields" :key="field.key" :label="field.label">
+ <NumberField
+ :model-value="ctx.paragraphSpacing(field.key)"
+ :aria-label="field.label"
+ :min="0"
+ :disabled="field.key === 'listSpacing' && ctx.listType.value === 'NONE'"
+ :data-property="field.property"
+ @update:model-value="
+ ctx.actions.previewParagraphSpacing(field.key, Math.max(0, $event))
+ "
+ @commit="
+ (value: number) =>
+ ctx.actions.setParagraphSpacing(field.key, Math.max(0, value))
+ "
+ >
+ <template #icon>
+ <icon-lucide-between-vertical-start
+ v-if="field.key === 'listSpacing'"
+ class="size-3"
+ />
+ <icon-lucide-pilcrow
+ v-else-if="field.key === 'paragraphSpacing'"
+ class="size-3"
+ />
+ <icon-lucide-arrow-right-to-line v-else class="size-3" />
+ </template>
+ </NumberField>
+ </Tip>
+ </PanelGrid>
+ </div>
+ </PanelFieldGroup>
+ </div>
+
<div class="grid gap-2.5 border-t border-border pt-3">
<label
v-for="feature in commonFeatures"
diff --git a/tests/e2e/canvas/text/lists-visual.spec.ts b/tests/e2e/canvas/text/lists-visual.spec.ts
new file mode 100644
index 000000000..454b67885
--- /dev/null
+++ b/tests/e2e/canvas/text/lists-visual.spec.ts
@@ -0,0 +1,111 @@
+import type { Fill, StyleRun, TextParagraphStyle } from '@open-pencil/scene-graph'
+
+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'
+import listGlyphs from '#tests/fixtures/list-saved-glyphs.json' with { type: 'json' }
+
+const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')
+
+test('draws list markers, indents, and spacing as Figma lays them out', async () => {
+ await editor.page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('Missing editor')
+ const item = (listType: 'ORDERED' | 'UNORDERED', indentation = 1) => ({
+ listType,
+ indentation
+ })
+ const plain = { listType: 'NONE' as const, indentation: 0 }
+ const texts = [
+ {
+ x: 40,
+ y: 40,
+ width: 200,
+ text: 'Follow us on:\nTwitter\nNested once\nNested twice\nDiscord',
+ textParagraphs: [
+ plain,
+ item('UNORDERED'),
+ item('UNORDERED', 2),
+ item('UNORDERED', 3),
+ item('UNORDERED')
+ ]
+ },
+ {
+ x: 280,
+ y: 40,
+ width: 160,
+ text: Array.from({ length: 11 }, (_, index) => `Step ${index + 1}`).join('\n'),
+ textParagraphs: Array.from({ length: 11 }, (_, index) =>
+ item('ORDERED', index === 3 || index === 4 ? 2 : 1)
+ )
+ },
+ {
+ x: 480,
+ y: 40,
+ width: 180,
+ text: 'An item long enough to wrap onto more lines\nShort\nA paragraph after',
+ textParagraphs: [item('UNORDERED'), item('UNORDERED'), plain],
+ listSpacing: 8,
+ paragraphSpacing: 16
+ },
+ {
+ x: 480,
+ y: 220,
+ width: 180,
+ text: 'Hanging\nmarkers',
+ textParagraphs: [item('UNORDERED'), item('UNORDERED')],
+ hangingList: true
+ },
+ {
+ x: 700,
+ y: 40,
+ width: 160,
+ text: 'Centred\nlist',
+ textAlignHorizontal: 'CENTER' as const,
+ textParagraphs: [item('ORDERED'), item('ORDERED')]
+ }
+ ]
+ for (const props of texts) {
+ store.graph.createNode('TEXT', store.state.currentPageId, {
+ height: 260,
+ fontFamily: 'Inter',
+ fontSize: 16,
+ textAutoResize: 'HEIGHT',
+ ...props
+ })
+ }
+ store.requestRender()
+ })
+ // Glyphs Figma saved for a list whose first character is larger and red: its markers take
+ // that style, and the canvas draws them as saved.
+ await editor.page.evaluate((fixture) => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('Missing editor')
+ store.graph.createNode('TEXT', store.state.currentPageId, {
+ ...fixture,
+ x: 700,
+ y: 160,
+ textAutoResize: 'WIDTH_AND_HEIGHT',
+ fills: fixture.fills as Fill[],
+ styleRuns: fixture.styleRuns as StyleRun[],
+ textParagraphs: fixture.textParagraphs as TextParagraphStyle[],
+ derivedTextGlyphs: fixture.derivedTextGlyphs.map((glyph) => ({
+ ...glyph,
+ commandsBlob: new Uint8Array(glyph.commandsBlob)
+ }))
+ })
+ store.requestRender()
+ }, listGlyphs)
+ 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-lists.png')
+})
diff --git a/tests/e2e/canvas/text/lists-visual.spec.ts-snapshots/text-lists-openpencil-darwin.png b/tests/e2e/canvas/text/lists-visual.spec.ts-snapshots/text-lists-openpencil-darwin.png
new file mode 100644
index 000000000..3aec92c2e
Binary files /dev/null and b/tests/e2e/canvas/text/lists-visual.spec.ts-snapshots/text-lists-openpencil-darwin.png differ
diff --git a/tests/engine/io/fig/import/schema-coverage.test.ts b/tests/engine/io/fig/import/schema-coverage.test.ts
index 4c1897a5a..6829d6654 100644
--- a/tests/engine/io/fig/import/schema-coverage.test.ts
+++ b/tests/engine/io/fig/import/schema-coverage.test.ts
@@ -373,13 +373,13 @@ describe('Figma Kiwi schema coverage', () => {
expect(
Object.fromEntries([...buckets].map(([bucket, items]) => [bucket, items.length]))
).toEqual({
- modeled: 124,
+ modeled: 128,
schemaTag: 60,
internalBookkeeping: 16,
rawPreserved: 45,
styleLibraryMetadata: 38,
componentInstanceMetadata: 32,
- textMetadata: 23,
+ textMetadata: 19,
slideFigjamMetadata: 39,
visualGeometryMetadata: 37,
layoutMetadata: 29,
diff --git a/tests/engine/render/canvas/painted-text.test.ts b/tests/engine/render/canvas/painted-text.test.ts
index 631789685..79911ba8a 100644
--- a/tests/engine/render/canvas/painted-text.test.ts
+++ b/tests/engine/render/canvas/painted-text.test.ts
@@ -1,13 +1,11 @@
import { beforeAll, expect, test } from 'bun:test'
-import type { Paragraph } from 'canvaskit-wasm'
-
import type { Fill } from '@open-pencil/scene-graph'
import { SceneGraph } from '@open-pencil/scene-graph'
import { initCanvasKit } from '#cli/headless'
import { SkiaRenderer } from '#core/canvas/renderer'
-import { withTextParagraph } from '#core/canvas/text'
+import { withTextParagraph, type TextLayout } from '#core/canvas/text'
import { fontManager } from '#core/text/fonts'
import { expectDefined } from '#tests/helpers/assert'
@@ -43,7 +41,7 @@ test('mutable foreground paints never enter the paragraph cache, including on er
width: 100,
height: 100
})
- let borrowed: Paragraph | undefined
+ let borrowed: TextLayout | undefined
try {
await renderer.loadFonts()
expect(() =>
diff --git a/tests/engine/render/canvas/picture-invalidation.test.ts b/tests/engine/render/canvas/picture-invalidation.test.ts
index 1a748db7b..3c7471cc3 100644
--- a/tests/engine/render/canvas/picture-invalidation.test.ts
+++ b/tests/engine/render/canvas/picture-invalidation.test.ts
@@ -2,7 +2,7 @@ import { expect, mock, test } from 'bun:test'
import { EffectRasterCache } from '#core/canvas/renderer/effect-raster-cache'
import { invalidateAllPictures, invalidateNodePicture } from '#core/canvas/renderer/state'
-import { TextPreparationCache } from '#core/canvas/text/preparation-cache'
+import { TextPreparationCache } from '#core/canvas/text/preparation/cache'
import { asRenderer } from './helpers'
diff --git a/tests/engine/render/canvas/renderer-lifecycle.test.ts b/tests/engine/render/canvas/renderer-lifecycle.test.ts
index 68f7d3b2d..f04493740 100644
--- a/tests/engine/render/canvas/renderer-lifecycle.test.ts
+++ b/tests/engine/render/canvas/renderer-lifecycle.test.ts
@@ -7,8 +7,8 @@ import { ImagePreviewCache } from '#core/canvas/images/previews'
import type { SkiaRenderer } from '#core/canvas/renderer'
import { EffectRasterCache } from '#core/canvas/renderer/effect-raster-cache'
import { destroyRenderer } from '#core/canvas/renderer/lifecycle'
-import { createGlyphSilhouetteCache } from '#core/canvas/text/derived'
-import { TextPreparationCache } from '#core/canvas/text/preparation-cache'
+import { createDerivedGlyphPathCache, createGlyphSilhouetteCache } from '#core/canvas/text/derived'
+import { TextPreparationCache } from '#core/canvas/text/preparation/cache'
import { asDouble, asRenderer } from './helpers'
@@ -31,6 +31,7 @@ function createRenderer() {
fillGeometryCache: new Map(),
strokeGeometryCache: new Map(),
glyphSilhouetteCache: createGlyphSilhouetteCache(),
+ derivedGlyphPathCache: createDerivedGlyphPathCache(),
fillPaint: deletable<Paint>(),
strokePaint: deletable<Paint>(),
selectionPaint: deletable<Paint>(),
diff --git a/tests/engine/render/canvas/text-preparation-cache.test.ts b/tests/engine/render/canvas/text-preparation-cache.test.ts
index a23b7bb64..5c4f42efe 100644
--- a/tests/engine/render/canvas/text-preparation-cache.test.ts
+++ b/tests/engine/render/canvas/text-preparation-cache.test.ts
@@ -1,13 +1,14 @@
import { describe, expect, test } from 'bun:test'
-import type { CanvasKit, Paragraph } from 'canvaskit-wasm'
+import type { CanvasKit } from 'canvaskit-wasm'
import { SceneGraph } from '@open-pencil/scene-graph'
import { initCanvasKit } from '#cli/headless'
import { buildParagraph, nodeFontReadiness } from '#core/canvas/text'
-import type { ParagraphNode } from '#core/canvas/text/paragraph-inputs'
-import { TextPreparationCache } from '#core/canvas/text/preparation-cache'
+import { TextLayout } from '#core/canvas/text/layout'
+import type { ParagraphNode } from '#core/canvas/text/paragraph/inputs'
+import { TextPreparationCache } from '#core/canvas/text/preparation/cache'
import { fontManager } from '#core/text/fonts'
import { expectDefined } from '#tests/helpers/assert'
@@ -22,18 +23,18 @@ async function fixture(maxEntries = 8, maxUnits = 1000) {
height: 50
})
const cache = new TextPreparationCache(maxEntries, maxUnits)
- const built: Paragraph[] = []
+ const built: TextLayout[] = []
function build() {
const builder = ck.ParagraphBuilder.MakeFromFontProvider(
new ck.ParagraphStyle({ textStyle: { fontSize: 16 } }),
provider
)
builder.addText(node.text)
- const paragraph = builder.build()
+ const layout = TextLayout.ofParagraph(ck, builder.build(), node.text.length)
builder.delete()
- paragraph.layout(node.width)
- built.push(paragraph)
- return paragraph
+ layout.layout(node.width)
+ built.push(layout)
+ return layout
}
function use(variant = 'draw', generation = 1) {
return cache.use(node, variant, generation, provider, build, ({ paragraph }) =>
@@ -234,6 +235,11 @@ describe('text preparation cache', () => {
],
textTruncation: 'ENDING',
maxLines: 2,
+ textParagraphs: [{ listType: 'UNORDERED', indentation: 1 }],
+ listSpacing: 4,
+ paragraphSpacing: 6,
+ paragraphIndent: 8,
+ hangingList: true,
textAutoResize: 'WIDTH_AND_HEIGHT',
width: 100,
height: 80,
diff --git a/tests/engine/render/canvas/text.test.ts b/tests/engine/render/canvas/text.test.ts
index 4cf0a2817..6bab7d836 100644
--- a/tests/engine/render/canvas/text.test.ts
+++ b/tests/engine/render/canvas/text.test.ts
@@ -9,7 +9,7 @@ import {
SkiaRenderer as SkiaRendererClass
} from '@open-pencil/core'
import type { SceneNode } from '@open-pencil/scene-graph'
-import { createDefaultSourceMetadata } from '@open-pencil/scene-graph/node-defaults'
+import { createDefaultNode } from '@open-pencil/scene-graph/node-defaults'
import { initCanvasKit } from '#cli/headless'
import type { SkiaRenderer } from '#core/canvas/renderer'
@@ -20,6 +20,7 @@ import {
nodeFontReadiness,
textVerticalOffset
} from '#core/canvas/text'
+import { createDerivedGlyphPathCache } from '#core/canvas/text/derived'
import { transformTextCase } from '#core/text/case'
import { fontManager } from '#core/text/fonts'
import { fontFaceDemand, fontResolver, missingGlyphCharacters } from '#core/text/resolver'
@@ -47,7 +48,14 @@ function createMockCanvas() {
}
function createMockParagraph() {
- return { delete: mock(() => undefined), getHeight: mock(() => 20) }
+ const paragraph = {
+ delete: mock(() => undefined),
+ getHeight: mock(() => 20),
+ draw: mock((canvas: { drawParagraph: (...args: unknown[]) => void }, x: number, y: number) =>
+ canvas.drawParagraph(paragraph, x, y)
+ )
+ }
+ return paragraph
}
function createMockPicture() {
@@ -60,6 +68,7 @@ function createMockRenderer(overrides: Partial<Record<string, unknown>> = {}) {
fontsLoaded: true,
fontProvider: {},
textFont: {},
+ derivedGlyphPathCache: createDerivedGlyphPathCache(),
fillPaint: { getColor: () => new Float32Array([0, 0, 0, 1]) },
effectLayerPaint: {
setBlendMode: mock(() => undefined),
@@ -97,8 +106,7 @@ function createMockRenderer(overrides: Partial<Record<string, unknown>> = {}) {
}
function textNode(overrides: Partial<SceneNode> = {}): SceneNode {
- return {
- type: 'TEXT',
+ return createDefaultNode(() => '0:1', 'TEXT', {
text: 'Hello 你好',
fontSize: 16,
fontFamily: 'Arial',
@@ -112,9 +120,8 @@ function textNode(overrides: Partial<SceneNode> = {}): SceneNode {
textDecoration: 'NONE',
textDirection: 'AUTO',
styleRuns: [],
- source: createDefaultSourceMetadata(),
...overrides
- } as SceneNode
+ })
}
async function createTextRenderer() {
diff --git a/tests/engine/text/edit-undo.test.ts b/tests/engine/text/edit-undo.test.ts
index 646d7dc08..8fcc22165 100644
--- a/tests/engine/text/edit-undo.test.ts
+++ b/tests/engine/text/edit-undo.test.ts
@@ -163,6 +163,42 @@ describe('text edit undo', () => {
expect(getNodeOrThrow(graph, textNode.id).text).toBe('Hello World')
})
+ test('undoes a change made while editing on its own, then the typing before it', () => {
+ const { graph, undo, textEditor, textNode, actions } = setup()
+ const listed = [{ listType: 'ORDERED' as const, indentation: 1 }]
+ const read = () => getNodeOrThrow(graph, textNode.id)
+ actions.startTextEditing(textNode.id)
+ textEditor.insert(' World', textNode)
+ graph.updateNode(textNode.id, {
+ text: expectDefined(textEditor.state, 'text editor state').text
+ })
+
+ // A list shortcut while editing, recorded the way updateNodeWithUndo records it.
+ actions.runTextEditStep(() => {
+ graph.updateNode(textNode.id, { textParagraphs: listed })
+ undo.push({
+ label: 'Change list style',
+ forward: () => graph.updateNode(textNode.id, { textParagraphs: listed }),
+ inverse: () => graph.updateNode(textNode.id, { textParagraphs: [] })
+ })
+ })
+ expect(undo.undoLabel).toBe('Change list style')
+
+ actions.runTextEditStep(() => undo.undo())
+ expect(read().textParagraphs).toEqual([])
+ expect(read().text).toBe('Hello World')
+ expect(textEditor.isActive).toBe(true)
+
+ actions.runTextEditStep(() => undo.undo())
+ expect(read().text).toBe('Hello')
+ expect(textEditor.state?.text).toBe('Hello')
+
+ // Nothing changed since the last undo, so leaving the edit records nothing more.
+ actions.commitTextEdit()
+ expect(undo.canUndo).toBe(false)
+ expect(undo.canRedo).toBe(true)
+ })
+
test('reflows live path-text edits and restores glyphs through undo and redo', async () => {
const setupResult = await setupPathText()
if (!setupResult) return
diff --git a/tests/engine/text/editor.test.ts b/tests/engine/text/editor.test.ts
index eb1329459..78b9e64e1 100644
--- a/tests/engine/text/editor.test.ts
+++ b/tests/engine/text/editor.test.ts
@@ -1,10 +1,12 @@
import { describe, test, expect } from 'bun:test'
-import type { CanvasKit, Paragraph, RectWithDirection } from 'canvaskit-wasm'
+import type { CanvasKit, LineMetrics, Paragraph, RectWithDirection } from 'canvaskit-wasm'
import { TextEditor, type SceneNode } from '@open-pencil/core'
import { createDefaultNode } from '@open-pencil/scene-graph/node-defaults'
+import { TextLayout } from '#core/canvas/text/layout'
+
import { expectDefined } from '#tests/helpers/assert'
import { asDouble } from '#tests/helpers/doubles'
@@ -13,6 +15,19 @@ const mockCk = asDouble<CanvasKit>({
RectWidthStyle: { Tight: 0 }
})
+/** A layout of one native paragraph double holding `length` characters. */
+function layoutOf(native: Partial<Paragraph>, length: number): TextLayout {
+ const paragraph = asDouble<Paragraph>({
+ layout: () => undefined,
+ didExceedMaxLines: () => false,
+ getLongestLine: () => 0,
+ ...native
+ })
+ const layout = TextLayout.ofParagraph(mockCk, paragraph, length)
+ layout.layout(100)
+ return layout
+}
+
function createEditor(text = 'Hello World') {
const editor = new TextEditor(mockCk)
const node = { id: 'test-node', text } as SceneNode
@@ -33,20 +48,22 @@ function createParagraphEditor(textAlignVertical: SceneNode['textAlignVertical']
left: 3,
startIndex: 0
}
- const paragraph = asDouble<Paragraph>({
- delete: () => undefined,
- getGlyphPositionAtCoordinate: (_x: number, y: number) => {
- hitTestYs.push(y)
- return { pos: Math.round(y) }
- },
- getHeight: () => 20,
- getLineMetrics: () => [lineMetrics],
- getLineMetricsAt: () => lineMetrics,
- getLineNumberAt: () => 0,
- getRectsForRange: () => rects
- })
const renderer = asDouble<Parameters<TextEditor['setRenderer']>[0]>({
- buildParagraph: () => paragraph,
+ buildParagraph: (node: SceneNode) =>
+ layoutOf(
+ {
+ delete: () => undefined,
+ getGlyphPositionAtCoordinate: (_x: number, y: number) => {
+ hitTestYs.push(y)
+ return asDouble({ pos: Math.round(y) })
+ },
+ getHeight: () => 20,
+ getLineMetrics: () => [asDouble(lineMetrics)],
+ getLineNumberAt: () => 0,
+ getRectsForRange: () => rects
+ },
+ node.text.length
+ ),
fontGeneration: 1
})
const editor = new TextEditor(mockCk)
@@ -190,20 +207,21 @@ describe('TextEditor', () => {
})
test('places the caret of empty text, which CanvasKit lays out no line for', () => {
- const empty = asDouble<Paragraph>({
+ const empty = {
delete: () => undefined,
getHeight: () => 0,
getLineMetrics: () => []
- })
- const space = asDouble<Paragraph>({
+ }
+ const space = {
delete: () => undefined,
getHeight: () => 17,
- getLineMetrics: () => [{ height: 17, left: 0 }]
- })
+ getLineMetrics: () => [asDouble<LineMetrics>({ height: 17, left: 0 })]
+ }
const editor = new TextEditor(mockCk)
editor.setRenderer(
asDouble<Parameters<TextEditor['setRenderer']>[0]>({
- buildParagraph: (node: SceneNode) => (node.text === '' ? empty : space),
+ buildParagraph: (node: SceneNode) =>
+ node.text === '' ? layoutOf(empty, 0) : layoutOf(space, 1),
fontGeneration: 1
})
)
@@ -219,6 +237,36 @@ describe('TextEditor', () => {
expect(editor.getCaretRect()).toEqual({ x: 60, y0: 40, y1: 57 })
})
+ test('lays the text out again when its node changes outside the editor', () => {
+ const built: number[] = []
+ const editor = new TextEditor(mockCk)
+ editor.setRenderer(
+ asDouble<Parameters<TextEditor['setRenderer']>[0]>({
+ buildParagraph: (node: SceneNode) => {
+ built.push(node.paragraphSpacing)
+ return layoutOf(
+ {
+ delete: () => undefined,
+ getHeight: () => 20,
+ getLineMetrics: () => [],
+ getRectsForRange: () => []
+ },
+ node.text.length
+ )
+ },
+ fontGeneration: 1
+ })
+ )
+ const node = createDefaultNode(() => 'spaced-text', 'TEXT', { text: 'A\nB' })
+ editor.start(node)
+ editor.invalidateParagraph({ ...node, paragraphSpacing: 12 })
+ expect(built).toEqual([0])
+ // A panel field previews a value: the selection drawn next follows it.
+ editor.getSelectionRects()
+ editor.getSelectionRects()
+ expect(built).toEqual([0, 12])
+ })
+
test('offsets the empty-text caret for vertical alignment', () => {
const { editor } = createParagraphEditor('BOTTOM')
editorState(editor).text = ''
diff --git a/tests/fixtures/list-saved-glyphs.json b/tests/fixtures/list-saved-glyphs.json
new file mode 100644
index 000000000..a6beb9bc9
--- /dev/null
+++ b/tests/fixtures/list-saved-glyphs.json
@@ -0,0 +1,356 @@
+{
+ "text": "big\nsmall",
+ "fontFamily": "Inter",
+ "fontSize": 16,
+ "fontWeight": 400,
+ "width": 95,
+ "height": 54,
+ "textAutoResize": "WIDTH_AND_HEIGHT",
+ "fills": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 0,
+ "g": 0,
+ "b": 0,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": true,
+ "blendMode": "NORMAL"
+ }
+ ],
+ "styleRuns": [
+ {
+ "start": 0,
+ "length": 4,
+ "style": {
+ "fontSize": 32,
+ "fills": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 1,
+ "g": 0,
+ "b": 0,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": true,
+ "blendMode": "NORMAL"
+ }
+ ]
+ }
+ }
+ ],
+ "textParagraphs": [
+ {
+ "listType": "ORDERED",
+ "indentation": 1
+ },
+ {
+ "listType": "ORDERED",
+ "indentation": 1
+ }
+ ],
+ "derivedTextGlyphs": [
+ {
+ "commandsBlob": [
+ 0, 1, 0, 0, 216, 62, 140, 46, 58, 63, 2, 0, 0, 216, 62, 0, 0, 0, 0, 2, 187, 232, 170, 62, 0,
+ 0, 0, 0, 2, 187, 232, 170, 62, 163, 139, 34, 63, 2, 47, 186, 168, 62, 163, 139, 34, 63, 2,
+ 233, 162, 27, 62, 24, 93, 4, 63, 2, 233, 162, 27, 62, 210, 69, 27, 63, 2, 187, 232, 170, 62,
+ 140, 46, 58, 63, 2, 0, 0, 216, 62, 140, 46, 58, 63, 0
+ ],
+ "x": 7.802189826965332,
+ "y": 31.136363983154297,
+ "fontSize": 32,
+ "rotation": 0,
+ "advance": 20.72727394104004
+ },
+ {
+ "commandsBlob": [
+ 0, 1, 70, 23, 13, 62, 140, 46, 186, 187, 3, 24, 93, 228, 61, 140, 46, 186, 187, 117, 209,
+ 189, 61, 210, 69, 87, 60, 3, 210, 69, 151, 61, 186, 232, 2, 61, 210, 69, 151, 61, 163, 139,
+ 110, 61, 3, 210, 69, 151, 61, 70, 23, 173, 61, 117, 209, 189, 61, 233, 162, 211, 61, 3, 24,
+ 93, 228, 61, 140, 46, 250, 61, 70, 23, 13, 62, 140, 46, 250, 61, 3, 0, 0, 40, 62, 140, 46,
+ 250, 61, 210, 69, 59, 62, 233, 162, 211, 61, 3, 163, 139, 78, 62, 70, 23, 173, 61, 163, 139,
+ 78, 62, 163, 139, 110, 61, 3, 163, 139, 78, 62, 210, 69, 39, 61, 93, 116, 69, 62, 210, 69,
+ 215, 60, 3, 47, 186, 60, 62, 0, 0, 64, 60, 117, 209, 45, 62, 140, 46, 58, 59, 3, 210, 69,
+ 31, 62, 140, 46, 186, 187, 70, 23, 13, 62, 140, 46, 186, 187, 0
+ ],
+ "x": 28.52094078063965,
+ "y": 31.136363983154297,
+ "fontSize": 32,
+ "rotation": 0,
+ "advance": 8.818181991577148
+ },
+ {
+ "commandsBlob": [
+ 0, 1, 24, 93, 180, 61, 0, 0, 0, 0, 2, 24, 93, 180, 61, 140, 46, 58, 63, 2, 0, 0, 48, 62,
+ 140, 46, 58, 63, 2, 0, 0, 48, 62, 187, 232, 234, 62, 2, 210, 69, 55, 62, 187, 232, 234, 62,
+ 3, 47, 186, 64, 62, 140, 46, 242, 62, 94, 116, 81, 62, 94, 116, 253, 62, 3, 163, 139, 98,
+ 62, 93, 116, 4, 63, 70, 23, 129, 62, 186, 232, 8, 63, 3, 70, 23, 145, 62, 93, 116, 13, 63,
+ 24, 93, 172, 62, 93, 116, 13, 63, 3, 233, 162, 207, 62, 93, 116, 13, 63, 163, 139, 234, 62,
+ 233, 162, 4, 63, 3, 47, 186, 2, 63, 233, 162, 247, 62, 210, 69, 10, 63, 210, 69, 215, 62, 3,
+ 117, 209, 17, 63, 187, 232, 182, 62, 117, 209, 17, 63, 186, 232, 138, 62, 3, 117, 209, 17,
+ 63, 70, 23, 61, 62, 210, 69, 10, 63, 0, 0, 248, 61, 3, 47, 186, 2, 63, 70, 23, 109, 61, 47,
+ 186, 234, 62, 70, 23, 189, 60, 3, 0, 0, 208, 62, 140, 46, 58, 188, 70, 23, 173, 62, 140, 46,
+ 58, 188, 3, 140, 46, 146, 62, 140, 46, 58, 188, 0, 0, 130, 62, 117, 209, 197, 59, 3, 233,
+ 162, 99, 62, 187, 232, 194, 60, 140, 46, 82, 62, 70, 23, 61, 61, 3, 47, 186, 64, 62, 70, 23,
+ 141, 61, 210, 69, 55, 62, 233, 162, 171, 61, 2, 70, 23, 45, 62, 233, 162, 171, 61, 2, 70,
+ 23, 45, 62, 0, 0, 0, 0, 2, 24, 93, 180, 61, 0, 0, 0, 0, 0, 1, 163, 139, 46, 62, 233, 162,
+ 139, 62, 3, 163, 139, 46, 62, 0, 0, 88, 62, 70, 23, 65, 62, 233, 162, 39, 62, 3, 233, 162,
+ 83, 62, 210, 69, 239, 61, 210, 69, 119, 62, 47, 186, 184, 61, 3, 93, 116, 141, 62, 186, 232,
+ 130, 61, 210, 69, 167, 62, 186, 232, 130, 61, 3, 140, 46, 194, 62, 186, 232, 130, 61, 140,
+ 46, 212, 62, 233, 162, 187, 61, 3, 24, 93, 230, 62, 70, 23, 245, 61, 94, 116, 239, 62, 187,
+ 232, 42, 62, 3, 47, 186, 248, 62, 233, 162, 91, 62, 47, 186, 248, 62, 233, 162, 139, 62, 3,
+ 47, 186, 248, 62, 70, 23, 169, 62, 233, 162, 239, 62, 47, 186, 192, 62, 3, 47, 186, 230, 62,
+ 163, 139, 216, 62, 163, 139, 212, 62, 24, 93, 230, 62, 3, 163, 139, 194, 62, 24, 93, 244,
+ 62, 210, 69, 167, 62, 24, 93, 244, 62, 3, 70, 23, 141, 62, 24, 93, 244, 62, 163, 139, 118,
+ 62, 70, 23, 231, 62, 3, 187, 232, 82, 62, 0, 0, 218, 62, 47, 186, 64, 62, 24, 93, 194, 62,
+ 3, 163, 139, 46, 62, 187, 232, 170, 62, 163, 139, 46, 62, 233, 162, 139, 62, 0
+ ],
+ "x": 48,
+ "y": 31.136363983154297,
+ "fontSize": 32,
+ "firstCharacter": 0,
+ "rotation": 0,
+ "advance": 19.863636016845703
+ },
+ {
+ "commandsBlob": [
+ 0, 1, 70, 23, 157, 61, 0, 0, 0, 0, 2, 70, 23, 157, 61, 233, 162, 11, 63, 2, 24, 93, 36, 62,
+ 233, 162, 11, 63, 2, 24, 93, 36, 62, 0, 0, 0, 0, 2, 70, 23, 157, 61, 0, 0, 0, 0, 0, 1, 24,
+ 93, 244, 61, 186, 232, 34, 63, 3, 140, 46, 194, 61, 186, 232, 34, 63, 117, 209, 157, 61,
+ 140, 46, 39, 63, 3, 24, 93, 116, 61, 93, 116, 43, 63, 24, 93, 116, 61, 93, 116, 49, 63, 3,
+ 24, 93, 116, 61, 93, 116, 55, 63, 117, 209, 157, 61, 47, 186, 59, 63, 3, 140, 46, 194, 61,
+ 0, 0, 64, 63, 24, 93, 244, 61, 0, 0, 64, 63, 3, 210, 69, 19, 62, 0, 0, 64, 63, 70, 23, 37,
+ 62, 47, 186, 59, 63, 3, 210, 69, 55, 62, 93, 116, 55, 63, 210, 69, 55, 62, 93, 116, 49, 63,
+ 3, 210, 69, 55, 62, 93, 116, 43, 63, 70, 23, 37, 62, 140, 46, 39, 63, 3, 210, 69, 19, 62,
+ 186, 232, 34, 63, 24, 93, 244, 61, 186, 232, 34, 63, 0
+ ],
+ "x": 67.875,
+ "y": 31.136363983154297,
+ "fontSize": 32,
+ "firstCharacter": 1,
+ "rotation": 0,
+ "advance": 7.590909481048584
+ },
+ {
+ "commandsBlob": [
+ 0, 1, 0, 0, 152, 62, 70, 23, 93, 190, 3, 117, 209, 113, 62, 70, 23, 93, 190, 70, 23, 69, 62,
+ 70, 23, 77, 190, 3, 24, 93, 24, 62, 93, 116, 61, 190, 70, 23, 245, 61, 233, 162, 35, 190, 3,
+ 140, 46, 186, 61, 140, 46, 10, 190, 210, 69, 151, 61, 140, 46, 218, 189, 2, 0, 0, 16, 62,
+ 24, 93, 116, 189, 3, 233, 162, 27, 62, 47, 186, 152, 189, 93, 116, 45, 62, 0, 0, 192, 189,
+ 3, 210, 69, 63, 62, 0, 0, 232, 189, 140, 46, 94, 62, 163, 139, 2, 190, 3, 94, 116, 125, 62,
+ 93, 116, 17, 190, 0, 0, 152, 62, 93, 116, 17, 190, 3, 117, 209, 185, 62, 93, 116, 17, 190,
+ 117, 209, 207, 62, 94, 116, 225, 189, 3, 117, 209, 229, 62, 0, 0, 160, 189, 117, 209, 229,
+ 62, 186, 232, 34, 188, 2, 117, 209, 229, 62, 163, 139, 206, 61, 2, 140, 46, 226, 62, 163,
+ 139, 206, 61, 3, 94, 116, 221, 62, 0, 0, 176, 61, 47, 186, 212, 62, 186, 232, 130, 61, 3,
+ 140, 46, 204, 62, 70, 23, 45, 61, 0, 0, 188, 62, 163, 139, 206, 60, 3, 0, 0, 172, 62, 233,
+ 162, 11, 60, 47, 186, 144, 62, 233, 162, 11, 60, 3, 117, 209, 93, 62, 233, 162, 11, 60, 0,
+ 0, 40, 62, 186, 232, 34, 61, 3, 70, 23, 229, 61, 93, 116, 145, 61, 163, 139, 166, 61, 117,
+ 209, 5, 62, 3, 94, 116, 81, 61, 187, 232, 66, 62, 94, 116, 81, 61, 70, 23, 141, 62, 3, 94,
+ 116, 81, 61, 0, 0, 184, 62, 70, 23, 165, 61, 117, 209, 215, 62, 3, 94, 116, 225, 61, 117,
+ 209, 247, 62, 163, 139, 38, 62, 233, 162, 4, 63, 3, 24, 93, 92, 62, 93, 116, 13, 63, 93,
+ 116, 145, 62, 93, 116, 13, 63, 3, 47, 186, 172, 62, 93, 116, 13, 63, 47, 186, 188, 62, 186,
+ 232, 8, 63, 3, 187, 232, 204, 62, 93, 116, 4, 63, 94, 116, 213, 62, 94, 116, 253, 62, 3,
+ 140, 46, 222, 62, 140, 46, 242, 62, 187, 232, 226, 62, 187, 232, 234, 62, 2, 210, 69, 231,
+ 62, 187, 232, 234, 62, 2, 210, 69, 231, 62, 233, 162, 11, 63, 2, 24, 93, 8, 63, 233, 162,
+ 11, 63, 2, 24, 93, 8, 63, 0, 0, 128, 188, 3, 24, 93, 8, 63, 0, 0, 176, 189, 140, 46, 0, 63,
+ 70, 23, 5, 190, 3, 140, 46, 240, 62, 163, 139, 50, 190, 47, 186, 212, 62, 233, 162, 71, 190,
+ 3, 93, 116, 185, 62, 70, 23, 93, 190, 0, 0, 152, 62, 70, 23, 93, 190, 0, 1, 163, 139, 150,
+ 62, 233, 162, 171, 61, 3, 24, 93, 176, 62, 233, 162, 171, 61, 140, 46, 194, 62, 187, 232,
+ 218, 61, 3, 0, 0, 212, 62, 70, 23, 5, 62, 210, 69, 221, 62, 93, 116, 49, 62, 3, 163, 139,
+ 230, 62, 117, 209, 93, 62, 163, 139, 230, 62, 117, 209, 141, 62, 3, 163, 139, 230, 62, 0, 0,
+ 172, 62, 94, 116, 221, 62, 70, 23, 195, 62, 3, 24, 93, 212, 62, 140, 46, 218, 62, 163, 139,
+ 194, 62, 210, 69, 231, 62, 3, 47, 186, 176, 62, 24, 93, 244, 62, 163, 139, 150, 62, 24, 93,
+ 244, 62, 3, 163, 139, 118, 62, 24, 93, 244, 62, 140, 46, 82, 62, 163, 139, 230, 62, 3, 140,
+ 46, 46, 62, 47, 186, 216, 62, 0, 0, 28, 62, 93, 116, 193, 62, 3, 140, 46, 10, 62, 140, 46,
+ 170, 62, 140, 46, 10, 62, 117, 209, 141, 62, 3, 140, 46, 10, 62, 94, 116, 97, 62, 24, 93,
+ 28, 62, 47, 186, 52, 62, 3, 187, 232, 46, 62, 24, 93, 8, 62, 187, 232, 82, 62, 117, 209,
+ 221, 61, 3, 210, 69, 119, 62, 233, 162, 171, 61, 163, 139, 150, 62, 233, 162, 171, 61, 0
+ ],
+ "x": 75.46875,
+ "y": 31.136363983154297,
+ "fontSize": 32,
+ "firstCharacter": 2,
+ "rotation": 0,
+ "advance": 19.5
+ },
+ {
+ "commandsBlob": [
+ 0, 1, 117, 209, 197, 61, 0, 0, 0, 0, 2, 117, 209, 197, 61, 186, 232, 130, 61, 2, 24, 93,
+ 172, 62, 210, 69, 167, 62, 3, 0, 0, 194, 62, 187, 232, 190, 62, 0, 0, 208, 62, 24, 93, 208,
+ 62, 3, 0, 0, 222, 62, 0, 0, 226, 62, 47, 186, 228, 62, 94, 116, 241, 62, 3, 233, 162, 235,
+ 62, 163, 139, 0, 63, 233, 162, 235, 62, 70, 23, 9, 63, 3, 233, 162, 235, 62, 186, 232, 18,
+ 63, 140, 46, 226, 62, 70, 23, 26, 63, 3, 187, 232, 216, 62, 210, 69, 33, 63, 47, 186, 200,
+ 62, 140, 46, 37, 63, 3, 163, 139, 184, 62, 70, 23, 41, 63, 24, 93, 164, 62, 70, 23, 41, 63,
+ 3, 186, 232, 142, 62, 70, 23, 41, 63, 117, 209, 125, 62, 233, 162, 36, 63, 3, 140, 46, 94,
+ 62, 210, 69, 32, 63, 47, 186, 76, 62, 24, 93, 24, 63, 3, 233, 162, 59, 62, 93, 116, 16, 63,
+ 233, 162, 59, 62, 117, 209, 5, 63, 2, 233, 162, 203, 61, 117, 209, 5, 63, 3, 233, 162, 203,
+ 61, 140, 46, 22, 63, 0, 0, 4, 62, 163, 139, 34, 63, 3, 140, 46, 34, 62, 187, 232, 46, 63,
+ 140, 46, 86, 62, 117, 209, 53, 63, 3, 210, 69, 133, 62, 47, 186, 60, 63, 117, 209, 165, 62,
+ 47, 186, 60, 63, 3, 163, 139, 198, 62, 47, 186, 60, 63, 117, 209, 223, 62, 117, 209, 53, 63,
+ 3, 70, 23, 249, 62, 187, 232, 46, 63, 47, 186, 3, 63, 140, 46, 35, 63, 3, 186, 232, 10, 63,
+ 93, 116, 23, 63, 186, 232, 10, 63, 70, 23, 9, 63, 3, 186, 232, 10, 63, 233, 162, 253, 62,
+ 140, 46, 7, 63, 0, 0, 234, 62, 3, 163, 139, 3, 63, 163, 139, 214, 62, 187, 232, 244, 62,
+ 163, 139, 190, 62, 3, 187, 232, 226, 62, 47, 186, 166, 62, 187, 232, 194, 62, 24, 93, 132,
+ 62, 2, 163, 139, 94, 62, 233, 162, 171, 61, 2, 163, 139, 94, 62, 0, 0, 160, 61, 2, 140, 46,
+ 14, 63, 0, 0, 160, 61, 2, 140, 46, 14, 63, 0, 0, 0, 0, 2, 117, 209, 197, 61, 0, 0, 0, 0, 0
+ ],
+ "x": 7.802189826965332,
+ "y": 50.1363639831543,
+ "fontSize": 32,
+ "rotation": 0,
+ "advance": 20.72727394104004
+ },
+ {
+ "commandsBlob": [
+ 0, 1, 70, 23, 13, 62, 140, 46, 186, 187, 3, 24, 93, 228, 61, 140, 46, 186, 187, 117, 209,
+ 189, 61, 210, 69, 87, 60, 3, 210, 69, 151, 61, 186, 232, 2, 61, 210, 69, 151, 61, 163, 139,
+ 110, 61, 3, 210, 69, 151, 61, 70, 23, 173, 61, 117, 209, 189, 61, 233, 162, 211, 61, 3, 24,
+ 93, 228, 61, 140, 46, 250, 61, 70, 23, 13, 62, 140, 46, 250, 61, 3, 0, 0, 40, 62, 140, 46,
+ 250, 61, 210, 69, 59, 62, 233, 162, 211, 61, 3, 163, 139, 78, 62, 70, 23, 173, 61, 163, 139,
+ 78, 62, 163, 139, 110, 61, 3, 163, 139, 78, 62, 210, 69, 39, 61, 93, 116, 69, 62, 210, 69,
+ 215, 60, 3, 47, 186, 60, 62, 0, 0, 64, 60, 117, 209, 45, 62, 140, 46, 58, 59, 3, 210, 69,
+ 31, 62, 140, 46, 186, 187, 70, 23, 13, 62, 140, 46, 186, 187, 0
+ ],
+ "x": 28.52094078063965,
+ "y": 50.1363639831543,
+ "fontSize": 32,
+ "rotation": 0,
+ "advance": 8.818181991577148
+ },
+ {
+ "commandsBlob": [
+ 0, 1, 70, 23, 237, 62, 47, 186, 216, 62, 2, 163, 139, 198, 62, 117, 209, 205, 62, 3, 187,
+ 232, 194, 62, 94, 116, 215, 62, 117, 209, 187, 62, 163, 139, 224, 62, 3, 187, 232, 180, 62,
+ 117, 209, 233, 62, 187, 232, 168, 62, 117, 209, 239, 62, 3, 186, 232, 156, 62, 117, 209,
+ 245, 62, 140, 46, 138, 62, 117, 209, 245, 62, 3, 70, 23, 97, 62, 117, 209, 245, 62, 187,
+ 232, 62, 62, 0, 0, 234, 62, 3, 70, 23, 29, 62, 24, 93, 222, 62, 70, 23, 29, 62, 24, 93, 204,
+ 62, 3, 70, 23, 29, 62, 24, 93, 188, 62, 24, 93, 52, 62, 70, 23, 179, 62, 3, 233, 162, 75,
+ 62, 117, 209, 169, 62, 70, 23, 125, 62, 233, 162, 163, 62, 2, 0, 0, 168, 62, 93, 116, 153,
+ 62, 3, 93, 116, 205, 62, 24, 93, 144, 62, 117, 209, 223, 62, 210, 69, 123, 62, 3, 140, 46,
+ 242, 62, 140, 46, 86, 62, 140, 46, 242, 62, 233, 162, 27, 62, 3, 140, 46, 242, 62, 210, 69,
+ 215, 61, 24, 93, 228, 62, 233, 162, 139, 61, 3, 47, 186, 214, 62, 0, 0, 0, 61, 140, 46, 190,
+ 62, 186, 232, 34, 60, 3, 233, 162, 165, 62, 140, 46, 58, 188, 70, 23, 133, 62, 140, 46, 58,
+ 188, 3, 47, 186, 52, 62, 140, 46, 58, 188, 94, 116, 249, 61, 233, 162, 203, 60, 3, 93, 116,
+ 137, 61, 140, 46, 122, 61, 210, 69, 87, 61, 117, 209, 5, 62, 2, 210, 69, 7, 62, 140, 46, 26,
+ 62, 3, 186, 232, 18, 62, 140, 46, 218, 61, 210, 69, 51, 62, 70, 23, 173, 61, 3, 0, 0, 84,
+ 62, 0, 0, 128, 61, 24, 93, 132, 62, 0, 0, 128, 61, 3, 24, 93, 162, 62, 0, 0, 128, 61, 0, 0,
+ 180, 62, 187, 232, 178, 61, 3, 117, 209, 197, 62, 163, 139, 230, 61, 117, 209, 197, 62, 210,
+ 69, 23, 62, 3, 117, 209, 197, 62, 24, 93, 52, 62, 233, 162, 187, 62, 0, 0, 72, 62, 3, 93,
+ 116, 177, 62, 0, 0, 92, 62, 24, 93, 156, 62, 117, 209, 101, 62, 2, 233, 162, 91, 62, 233,
+ 162, 123, 62, 3, 186, 232, 14, 62, 186, 232, 134, 62, 117, 209, 213, 61, 0, 0, 154, 62, 3,
+ 163, 139, 142, 61, 210, 69, 173, 62, 163, 139, 142, 61, 140, 46, 202, 62, 3, 163, 139, 142,
+ 61, 117, 209, 225, 62, 233, 162, 195, 61, 0, 0, 244, 62, 3, 94, 116, 249, 61, 70, 23, 3, 63,
+ 187, 232, 42, 62, 210, 69, 8, 63, 3, 94, 116, 89, 62, 93, 116, 13, 63, 140, 46, 138, 62, 93,
+ 116, 13, 63, 3, 233, 162, 179, 62, 93, 116, 13, 63, 210, 69, 203, 62, 24, 93, 4, 63, 3, 70,
+ 23, 227, 62, 163, 139, 246, 62, 70, 23, 237, 62, 47, 186, 216, 62, 0
+ ],
+ "x": 48,
+ "y": 50.1363639831543,
+ "fontSize": 16,
+ "firstCharacter": 4,
+ "rotation": 0,
+ "advance": 8.36363697052002
+ },
+ {
+ "commandsBlob": [
+ 0, 1, 70, 23, 157, 61, 0, 0, 0, 0, 2, 70, 23, 157, 61, 233, 162, 11, 63, 2, 93, 116, 33, 62,
+ 233, 162, 11, 63, 2, 93, 116, 33, 62, 233, 162, 235, 62, 2, 47, 186, 40, 62, 233, 162, 235,
+ 62, 3, 140, 46, 58, 62, 0, 0, 1, 63, 70, 23, 97, 62, 140, 46, 7, 63, 3, 0, 0, 132, 62, 93,
+ 116, 13, 63, 210, 69, 159, 62, 93, 116, 13, 63, 3, 187, 232, 186, 62, 93, 116, 13, 63, 210,
+ 69, 205, 62, 140, 46, 7, 63, 3, 117, 209, 223, 62, 0, 0, 1, 63, 140, 46, 234, 62, 233, 162,
+ 235, 62, 2, 70, 23, 237, 62, 233, 162, 235, 62, 3, 117, 209, 247, 62, 233, 162, 0, 63, 233,
+ 162, 6, 63, 0, 0, 7, 63, 3, 24, 93, 17, 63, 93, 116, 13, 63, 24, 93, 32, 63, 93, 116, 13,
+ 63, 3, 70, 23, 51, 63, 93, 116, 13, 63, 0, 0, 63, 63, 47, 186, 1, 63, 3, 187, 232, 74, 63,
+ 140, 46, 236, 62, 187, 232, 74, 63, 187, 232, 186, 62, 2, 187, 232, 74, 63, 0, 0, 0, 0, 2,
+ 93, 116, 53, 63, 0, 0, 0, 0, 2, 93, 116, 53, 63, 187, 232, 186, 62, 3, 93, 116, 53, 63, 117,
+ 209, 217, 62, 0, 0, 45, 63, 70, 23, 231, 62, 3, 163, 139, 36, 63, 24, 93, 244, 62, 70, 23,
+ 25, 63, 24, 93, 244, 62, 3, 24, 93, 10, 63, 24, 93, 244, 62, 210, 69, 2, 63, 163, 139, 226,
+ 62, 3, 24, 93, 244, 62, 187, 232, 208, 62, 24, 93, 244, 62, 117, 209, 181, 62, 2, 24, 93,
+ 244, 62, 0, 0, 0, 0, 2, 47, 186, 200, 62, 0, 0, 0, 0, 2, 47, 186, 200, 62, 210, 69, 191, 62,
+ 3, 47, 186, 200, 62, 70, 23, 215, 62, 210, 69, 185, 62, 233, 162, 229, 62, 3, 117, 209, 169,
+ 62, 24, 93, 244, 62, 93, 116, 145, 62, 24, 93, 244, 62, 3, 47, 186, 128, 62, 24, 93, 244,
+ 62, 24, 93, 100, 62, 94, 116, 235, 62, 3, 233, 162, 71, 62, 163, 139, 226, 62, 117, 209, 53,
+ 62, 47, 186, 210, 62, 3, 24, 93, 36, 62, 70, 23, 195, 62, 24, 93, 36, 62, 163, 139, 174, 62,
+ 2, 24, 93, 36, 62, 0, 0, 0, 0, 2, 70, 23, 157, 61, 0, 0, 0, 0, 0
+ ],
+ "x": 56.359375,
+ "y": 50.1363639831543,
+ "fontSize": 16,
+ "firstCharacter": 5,
+ "rotation": 0,
+ "advance": 13.909090995788574
+ },
+ {
+ "commandsBlob": [
+ 0, 1, 187, 232, 114, 62, 94, 116, 81, 188, 3, 117, 209, 61, 62, 94, 116, 81, 188, 163, 139,
+ 18, 62, 70, 23, 221, 59, 3, 163, 139, 206, 61, 140, 46, 218, 60, 233, 162, 155, 61, 186,
+ 232, 130, 61, 3, 94, 116, 81, 61, 0, 0, 208, 61, 94, 116, 81, 61, 163, 139, 30, 62, 3, 94,
+ 116, 81, 61, 163, 139, 78, 62, 163, 139, 142, 61, 24, 93, 108, 62, 3, 24, 93, 180, 61, 210,
+ 69, 133, 62, 233, 162, 243, 61, 117, 209, 141, 62, 3, 93, 116, 25, 62, 24, 93, 150, 62, 233,
+ 162, 63, 62, 163, 139, 154, 62, 3, 140, 46, 102, 62, 186, 232, 158, 62, 163, 139, 134, 62,
+ 93, 116, 161, 62, 3, 0, 0, 160, 62, 47, 186, 164, 62, 117, 209, 175, 62, 24, 93, 166, 62, 3,
+ 117, 209, 191, 62, 140, 46, 168, 62, 70, 23, 199, 62, 24, 93, 172, 62, 3, 163, 139, 206, 62,
+ 163, 139, 176, 62, 163, 139, 206, 62, 187, 232, 186, 62, 2, 163, 139, 206, 62, 24, 93, 188,
+ 62, 3, 163, 139, 206, 62, 210, 69, 215, 62, 117, 209, 191, 62, 140, 46, 230, 62, 3, 210, 69,
+ 177, 62, 70, 23, 245, 62, 233, 162, 147, 62, 70, 23, 245, 62, 3, 117, 209, 105, 62, 70, 23,
+ 245, 62, 187, 232, 70, 62, 233, 162, 231, 62, 3, 0, 0, 36, 62, 140, 46, 218, 62, 117, 209,
+ 21, 62, 187, 232, 202, 62, 2, 47, 186, 136, 61, 94, 116, 217, 62, 3, 24, 93, 180, 61, 187,
+ 232, 242, 62, 70, 23, 253, 61, 163, 139, 0, 63, 3, 210, 69, 35, 62, 47, 186, 7, 63, 163,
+ 139, 78, 62, 163, 139, 10, 63, 3, 140, 46, 122, 62, 93, 116, 13, 63, 140, 46, 146, 62, 93,
+ 116, 13, 63, 3, 233, 162, 159, 62, 93, 116, 13, 63, 70, 23, 177, 62, 117, 209, 11, 63, 3,
+ 47, 186, 194, 62, 210, 69, 10, 63, 70, 23, 211, 62, 24, 93, 5, 63, 3, 233, 162, 227, 62, 93,
+ 116, 0, 63, 163, 139, 238, 62, 70, 23, 237, 62, 3, 94, 116, 249, 62, 210, 69, 217, 62, 94,
+ 116, 249, 62, 0, 0, 184, 62, 2, 94, 116, 249, 62, 0, 0, 0, 0, 2, 163, 139, 206, 62, 0, 0, 0,
+ 0, 2, 163, 139, 206, 62, 210, 69, 151, 61, 2, 24, 93, 204, 62, 210, 69, 151, 61, 3, 0, 0,
+ 200, 62, 117, 209, 101, 61, 117, 209, 189, 62, 186, 232, 18, 61, 3, 233, 162, 179, 62, 0, 0,
+ 128, 60, 47, 186, 162, 62, 140, 46, 186, 58, 3, 117, 209, 145, 62, 94, 116, 81, 188, 187,
+ 232, 114, 62, 94, 116, 81, 188, 0, 1, 0, 0, 128, 62, 0, 0, 128, 61, 3, 93, 116, 153, 62, 0,
+ 0, 128, 61, 187, 232, 170, 62, 0, 0, 168, 61, 3, 163, 139, 188, 62, 0, 0, 208, 61, 93, 116,
+ 197, 62, 233, 162, 7, 62, 3, 163, 139, 206, 62, 210, 69, 39, 62, 163, 139, 206, 62, 140, 46,
+ 74, 62, 2, 163, 139, 206, 62, 24, 93, 140, 62, 3, 117, 209, 203, 62, 70, 23, 137, 62, 163,
+ 139, 194, 62, 24, 93, 134, 62, 3, 93, 116, 185, 62, 117, 209, 131, 62, 93, 116, 173, 62,
+ 117, 209, 129, 62, 3, 233, 162, 161, 62, 0, 0, 128, 62, 24, 93, 150, 62, 70, 23, 125, 62, 3,
+ 210, 69, 139, 62, 163, 139, 122, 62, 24, 93, 132, 62, 47, 186, 120, 62, 3, 210, 69, 103, 62,
+ 24, 93, 116, 62, 140, 46, 74, 62, 163, 139, 106, 62, 3, 93, 116, 45, 62, 70, 23, 97, 62,
+ 233, 162, 27, 62, 117, 209, 77, 62, 3, 140, 46, 10, 62, 187, 232, 58, 62, 140, 46, 10, 62,
+ 140, 46, 26, 62, 3, 140, 46, 10, 62, 187, 232, 218, 61, 210, 69, 43, 62, 70, 23, 173, 61, 3,
+ 47, 186, 76, 62, 0, 0, 128, 61, 0, 0, 128, 62, 0, 0, 128, 61, 0
+ ],
+ "x": 70.265625,
+ "y": 50.1363639831543,
+ "fontSize": 16,
+ "firstCharacter": 6,
+ "rotation": 0,
+ "advance": 9.022727966308594
+ },
+ {
+ "commandsBlob": [
+ 0, 1, 24, 93, 36, 62, 140, 46, 58, 63, 2, 24, 93, 36, 62, 0, 0, 0, 0, 2, 70, 23, 157, 61, 0,
+ 0, 0, 0, 2, 70, 23, 157, 61, 140, 46, 58, 63, 2, 24, 93, 36, 62, 140, 46, 58, 63, 0
+ ],
+ "x": 79.28125,
+ "y": 50.1363639831543,
+ "fontSize": 16,
+ "firstCharacter": 7,
+ "rotation": 0,
+ "advance": 3.795454740524292
+ },
+ {
+ "commandsBlob": [
+ 0, 1, 24, 93, 36, 62, 140, 46, 58, 63, 2, 24, 93, 36, 62, 0, 0, 0, 0, 2, 70, 23, 157, 61, 0,
+ 0, 0, 0, 2, 70, 23, 157, 61, 140, 46, 58, 63, 2, 24, 93, 36, 62, 140, 46, 58, 63, 0
+ ],
+ "x": 83.078125,
+ "y": 50.1363639831543,
+ "fontSize": 16,
+ "firstCharacter": 8,
+ "rotation": 0,
+ "advance": 3.795454740524292
+ }
+ ]
+}
diff --git a/vite/aliases.ts b/vite/aliases.ts
index 66c43149e..6ba93f848 100644
--- a/vite/aliases.ts
+++ b/vite/aliases.ts
@@ -38,6 +38,15 @@ export function createOpenPencilAliases(rootDir: string) {
find: /^@open-pencil\/scene-graph$/,
replacement: resolve(rootDir, 'packages/scene-graph/src/index.ts')
},
+ // Subpaths whose names differ from their files under src/.
+ {
+ find: /^@open-pencil\/scene-graph\/text-direction$/,
+ replacement: resolve(rootDir, 'packages/scene-graph/src/text/direction.ts')
+ },
+ {
+ find: /^@open-pencil\/scene-graph\/text-picture$/,
+ replacement: resolve(rootDir, 'packages/scene-graph/src/text/picture.ts')
+ },
{ find: '@open-pencil/scene-graph', replacement: resolve(rootDir, 'packages/scene-graph/src') },
{ find: '#emit', replacement: resolve(rootDir, 'packages/emit/src') },
{