Skip to content

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

fix(core): lay out, resize and edit text on a path as Figma does (#1150)

rcoenenf0b27ba35cb8
diff --git a/bun.lock b/bun.lock
index 639d23086..324c50911 100644
--- a/bun.lock
+++ b/bun.lock
@@ -283,7 +283,6 @@
"pptxgenjs": "^4.0.1",
"rbush": "^4.0.1",
"sucrase": "^3.35.1",
- "svg-path-properties": "^2.0.2",
"svg2pdf.js": "^2.8.1",
"svgpath": "^2.6.0",
"twirlwind": "^0.4.1",
@@ -4571,8 +4570,6 @@
"supports-preserve-symlinks-flag": ["[email protected]", "", {}, "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w=="],
- "svg-path-properties": ["[email protected]", "", {}, "sha512-NsSMBNZmod9Gr22gxa8FOiZUIzrI8o65veuCyppoNftNfpKjP5qoouA3ZyioOsQ2a4O8cRV8rHmG9LZF2HhXvw=="],
-
"svg-pathdata": ["[email protected]", "", {}, "sha512-qsjeeq5YjBZ5eMdFuUa4ZosMLxgr5RZ+F+Y1OrDhuOCEInRMA3x74XdBtggJcj9kOeInz0WE+LgCPDkZFlBYJw=="],
"svg2pdf.js": ["[email protected]", "", { "dependencies": { "cssesc": "^3.0.0", "font-family-papandreou": "^0.2.0-patch1", "specificity": "^0.4.1", "svgpath": "^2.3.0" }, "peerDependencies": { "jspdf": "^4.0.0 || ^3.0.0 || ^2.0.0" } }, "sha512-AzXfPHjHnFt9dpdRPhWWBOKipnMSWQZRKiV3FTTPdY6wwRgT3labbA4s0HIQaskNhwAhrcI2u2rDhD8j8udfNQ=="],
diff --git a/changes/1150/added.md b/changes/1150/added.md
new file mode 100644
index 000000000..ef220ce57
--- /dev/null
+++ b/changes/1150/added.md
@@ -0,0 +1 @@
+- Editing text on a path works along the path, as in Figma: clicking places the caret between the characters you click, dragging, Shift-clicking and double-clicking select characters, and the caret and selection follow the curve.
diff --git a/changes/1150/changed.md b/changes/1150/changed.md
new file mode 100644
index 000000000..db8d08aaa
--- /dev/null
+++ b/changes/1150/changed.md
@@ -0,0 +1 @@
+- Selected text on a path no longer draws a filled band over its lettering: as in Figma, it shows its path, box and handles, and while its text is edited an outline around the lettering.
diff --git a/changes/1150/fixed.md b/changes/1150/fixed.md
new file mode 100644
index 000000000..40f8bd810
--- /dev/null
+++ b/changes/1150/fixed.md
@@ -0,0 +1,2 @@
+- Editing aligned text on a path lays it out from the path's text start point, as in Figma: left-aligned text starts there, centered text is centered on it and right-aligned text ends there. Text too long for its part of the path keeps the characters that fit instead of piling up at the path's ends. Opening a `.fig` keeps which segment that start point is on.
+- Resizing text on a path lays it out again along the resized path at the same font size, as in Figma, instead of moving the old letters, which scattered and rotated them around corners. Text on a path pasted from Figma also keeps its path under the lettering after saving and reopening the `.fig`.
diff --git a/changes/1150/performance.md b/changes/1150/performance.md
new file mode 100644
index 000000000..787168852
--- /dev/null
+++ b/changes/1150/performance.md
@@ -0,0 +1 @@
+- Resizing and selecting text on a path no longer stutters: laying the text along its path is about 50 times faster.
diff --git a/packages/core/package.json b/packages/core/package.json
index 25c4f9edc..3baadb0a0 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -212,7 +212,6 @@
"pptxgenjs": "^4.0.1",
"rbush": "^4.0.1",
"sucrase": "^3.35.1",
- "svg-path-properties": "^2.0.2",
"svg2pdf.js": "^2.8.1",
"svgpath": "^2.6.0",
"twirlwind": "^0.4.1",
diff --git a/packages/core/src/canvas/overlays/selection.ts b/packages/core/src/canvas/overlays/selection.ts
index bc3c294e1..cf29d3483 100644
--- a/packages/core/src/canvas/overlays/selection.ts
+++ b/packages/core/src/canvas/overlays/selection.ts
@@ -25,7 +25,7 @@ import {
type RotationHandleLayout,
type RotationPreview
} from '#core/geometry'
-import { pathTextSelectionBand, pointAtArc } from '#core/text/path'
+import { pointAtArc, textPathStartArc } from '#core/text/path'
import { inNodeSpace, outlineNode, withScreenStroke } from './outline'
@@ -109,8 +109,8 @@ function drawSingleSelection(
const isPathText = node.textPathData !== null && node.textPathBox !== null
const editing = overlays.editingTextId === id
// While editing: normal text hands off to the flat text-edit overlay, but path
- // text keeps its path overlay (curved band + path) — its flat text-edit overlay
- // is suppressed (see drawTextEditOverlay) since it can't follow the path.
+ // text keeps its path and start point, as in Figma; the text-edit overlay
+ // outlines the lettering and draws the caret and selection along the path.
if (editing && !isPathText) return
r.selectionPaint.setColor(r.outlineColor(node, graph))
@@ -120,7 +120,7 @@ function drawSingleSelection(
if (node.type === 'CONNECTOR') {
drawConnectorSelection(r, canvas, graph, node, preview)
} else if (isPathText) {
- drawTextPathSelection(r, canvas, node, rotation, graph, preview)
+ drawTextPathSelection(r, canvas, node, rotation, graph, editing, preview)
if (!editing) r.drawSelectionLabels(canvas, graph, selectedIds, overlays)
} else {
r.drawNodeSelection(canvas, node, rotation, graph, preview)
@@ -201,7 +201,8 @@ function withNodeBounds(
* follows, a faint dashed box + handles, a center crosshair, and a start marker
* at `textPathStart`. Bounds come from the glyph-fitted path box (see
* fitTextPathBoxToGlyphs), so the circle tracks the lettering rather than the
- * ~4%-off textPathBox. Display-only — reads retained data, mutates nothing.
+ * ~4%-off textPathBox. While its text is edited only the path and start marker
+ * stay, as in Figma. Display-only — reads retained data, mutates nothing.
*/
function drawTextPathSelection(
r: SkiaRenderer,
@@ -209,6 +210,7 @@ function drawTextPathSelection(
node: SceneNode,
rotation: number,
graph: SceneGraph,
+ editing: boolean,
preview?: RotationPreview | null
): void {
const pathGeometry = selectionPath(node)
@@ -225,45 +227,34 @@ function drawTextPathSelection(
rotation,
graph,
() => {
- // Figma-style selection band: a filled ribbon that hugs the lettering along
- // the path (replaces the flat, path-blind text-edit selection rects).
- const bandPoly = pathTextSelectionBand(data, box, node.derivedTextGlyphs, sampled)
- if (bandPoly && bandPoly.length >= 6) {
- const band = new r.ck.PathBuilder()
- band.moveTo(bandPoly[0], bandPoly[1])
- for (let i = 2; i < bandPoly.length; i += 2) band.lineTo(bandPoly[i], bandPoly[i + 1])
- band.close()
- const immutableBand = band.detachAndDelete()
- r.auxFill.setColor(r.selColor(0.16))
- canvas.drawPath(immutableBand, r.auxFill)
- withScreenStroke(r, { color: r.selColor() }, (paint) =>
- canvas.drawPath(immutableBand, paint)
+ // While editing, the text-edit overlay outlines the lettering instead.
+ if (!editing) {
+ // Faint dashed bounds + resize/rotate handles from the fitted path box.
+ withScreenStroke(
+ r,
+ { color: r.selColor(SELECTION_DASH_ALPHA), dash: SELECTION_DASH },
+ (paint) =>
+ canvas.drawRect(
+ r.ck.LTRBRect(box.x, box.y, box.x + box.width, box.y + box.height),
+ paint
+ )
+ )
+ drawBoundsHandles(
+ r,
+ canvas,
+ box.x,
+ box.y,
+ box.x + box.width,
+ box.y + box.height,
+ rotationHandleLayout(node, createSceneGeometry(graph, preview), r.zoom, {
+ x: box.x,
+ y: box.y,
+ width: box.width,
+ height: box.height
+ })
)
- immutableBand.delete()
}
- // Faint dashed bounds + resize/rotate handles from the fitted path box.
- withScreenStroke(
- r,
- { color: r.selColor(SELECTION_DASH_ALPHA), dash: SELECTION_DASH },
- (paint) =>
- canvas.drawRect(r.ck.LTRBRect(box.x, box.y, box.x + box.width, box.y + box.height), paint)
- )
- drawBoundsHandles(
- r,
- canvas,
- box.x,
- box.y,
- box.x + box.width,
- box.y + box.height,
- rotationHandleLayout(node, createSceneGeometry(graph, preview), r.zoom, {
- x: box.x,
- y: box.y,
- width: box.x + box.width - box.x,
- height: box.y + box.height - box.y
- })
- )
-
// The path curve itself, sampled from the headless path metrics only for drawing.
const path = new r.ck.PathBuilder()
const overlaySteps = Math.max(64, Math.min(1024, Math.ceil(sampled.length)))
@@ -278,17 +269,18 @@ function drawTextPathSelection(
canvas.drawPath(immutablePath, r.selectionPaint)
immutablePath.delete()
- // Center crosshair at the fitted path box center (screen-constant size).
- const cx = box.x + box.width / 2
- const cy = box.y + box.height / 2
- const arm = (HANDLE_HALF_SIZE * 2) / r.zoom
- canvas.drawLine(cx - arm, cy, cx + arm, cy, r.selectionPaint)
- canvas.drawLine(cx, cy - arm, cx, cy + arm, r.selectionPaint)
+ if (!editing) {
+ // Center crosshair at the fitted path box center (screen-constant size).
+ const cx = box.x + box.width / 2
+ const cy = box.y + box.height / 2
+ const arm = (HANDLE_HALF_SIZE * 2) / r.zoom
+ canvas.drawLine(cx - arm, cy, cx + arm, cy, r.selectionPaint)
+ canvas.drawLine(cx, cy - arm, cx, cy + arm, r.selectionPaint)
+ }
- // Start-point marker on the curve at textPathStart.tValue (arc fraction).
+ // Start-point marker where aligned text is laid out from.
// forward only flips travel direction, which the display-only marker ignores.
- const s = Math.min(Math.max(data.tValue, 0), 1) * sampled.length
- const start = pointAtArc(sampled, s)
+ const start = pointAtArc(sampled, textPathStartArc(data, sampled))
drawHandle(r, canvas, start.x, start.y)
},
preview
diff --git a/packages/core/src/canvas/overlays/text-edit.ts b/packages/core/src/canvas/overlays/text-edit.ts
index f740a127d..7579bee75 100644
--- a/packages/core/src/canvas/overlays/text-edit.ts
+++ b/packages/core/src/canvas/overlays/text-edit.ts
@@ -69,9 +69,10 @@ export function drawTextEditOverlay(
}
/**
- * Caret for text on a path: a tick standing perpendicular to the curve at the
- * insertion glyph (baseline → ~cap height), so the cursor sits on the lettering
- * instead of at the flat-layout position. Blinks with `caretVisible`.
+ * Text on a path while it is edited, as Figma draws it: the lettering outlined by the bounds of
+ * its glyph boxes, the selection covering each selected glyph from the font's descent to its
+ * ascent, turned with the glyph, and the caret square to the path between two characters over the
+ * same height.
*/
function drawPathTextCaret(
r: SkiaRenderer,
@@ -79,19 +80,39 @@ function drawPathTextCaret(
node: SceneNode,
editor: TextEditor
): void {
+ const corners = editor.getPathTextQuads().flat()
+ if (corners.length > 0) {
+ const xs = corners.map((point) => point.x)
+ const ys = corners.map((point) => point.y)
+ withScreenStroke(r, { color: r.selColor() }, (paint) =>
+ canvas.drawRect(
+ r.ck.LTRBRect(Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)),
+ paint
+ )
+ )
+ }
+
+ const quads = editor.getPathSelectionQuads()
+ if (quads.length > 0) {
+ // One path, so boxes overlapping where the path bends are not tinted twice.
+ const builder = new r.ck.PathBuilder()
+ for (const [first, ...rest] of quads) {
+ builder.moveTo(first.x, first.y)
+ for (const point of rest) builder.lineTo(point.x, point.y)
+ builder.close()
+ }
+ const path = builder.detachAndDelete()
+ r.auxFill.setColor(r.selColor(TEXT_SELECTION_ALPHA))
+ canvas.drawPath(path, r.auxFill)
+ path.delete()
+ }
+
if (!editor.caretVisible || editor.hasSelection()) return
- const glyphs = node.derivedTextGlyphs
- const idx = editor.caretIndex
- if (!glyphs?.length || idx == null) return
- const g = glyphs[Math.min(Math.max(idx, 0), glyphs.length - 1)]
- const fontSize = g.fontSize || 0
- if (fontSize <= 0) return
- const rot = g.rotation ?? 0
- // Ascender ("up") direction from the glyph's on-path rotation.
- const ux = -Math.sin(rot)
- const uy = -Math.cos(rot)
- r.auxStroke.setStrokeWidth((TEXT_CARET_WIDTH * 1.5) / r.zoom)
- r.auxStroke.setColor(r.selColor())
+ const caret = editor.getPathCaret()
+ if (!caret) return
+ r.auxStroke.setStrokeWidth(TEXT_CARET_WIDTH / r.zoom)
+ const color = textCaretColor(node, editor.caretIndex ?? 0)
+ r.auxStroke.setColor(r.ck.Color4f(color.r, color.g, color.b, color.a))
r.auxStroke.setPathEffect(null)
- canvas.drawLine(g.x, g.y, g.x + ux * fontSize * 0.72, g.y + uy * fontSize * 0.72, r.auxStroke)
+ canvas.drawLine(caret.from.x, caret.from.y, caret.to.x, caret.to.y, r.auxStroke)
}
diff --git a/packages/core/src/editor/index.ts b/packages/core/src/editor/index.ts
index cc27e4300..2cd4280ab 100644
--- a/packages/core/src/editor/index.ts
+++ b/packages/core/src/editor/index.ts
@@ -41,6 +41,7 @@ export type { TokenImportResult } from '#core/io/formats/design-tokens'
export { reapplyInstanceComponentProperties } from './components/properties'
export { createGuideActions } from './guides'
export { createTextActions } from './text'
+export { resizedPathTextGlyphs } from './text/path-edit'
export { opacityFromBuffer } from './nodes'
export { layerTypeOptions, type LayerType } from './structure/layer-type'
export type { NodePreview } from './node-preview'
diff --git a/packages/core/src/editor/text/path-edit.ts b/packages/core/src/editor/text/path-edit.ts
index 4450a5a45..9a97a8901 100644
--- a/packages/core/src/editor/text/path-edit.ts
+++ b/packages/core/src/editor/text/path-edit.ts
@@ -1,18 +1,80 @@
import { mean } from 'es-toolkit'
import { encodePathCommandsBlob } from '@open-pencil/fig/node-change'
-import type { SceneNode } from '@open-pencil/scene-graph'
+import type { DerivedTextGlyph, SceneNode, TextPathData } from '@open-pencil/scene-graph'
+import type { Rect } from '@open-pencil/scene-graph/primitives'
import { weightToStyle } from '#core/text/fonts'
import { getGlyphOutlineMetricsSync } from '#core/text/opentype'
import {
calibratePathTextLayout,
getTextPathData,
- layoutPathTextFromAdvances
+ layoutPathTextFromAdvances,
+ type PathTextLayout,
+ sampleTextPath,
+ textPathStartDistance
} from '#core/text/path'
+/** The fields path text is laid out from; a change to any of them lays it out again. */
+const PATH_TEXT_LAYOUT_FIELDS = [
+ 'text',
+ 'fontFamily',
+ 'fontWeight',
+ 'italic',
+ 'fontSize',
+ 'letterSpacing',
+ 'textAlignHorizontal'
+] as const
+
+type PathTextType = Pick<SceneNode, (typeof PATH_TEXT_LAYOUT_FIELDS)[number]>
+
/**
- * Re-flow imported path text when its characters change: rebuild glyph
+ * Glyphs for `type` laid out along the path mapped into `box` from the local font: aligned from
+ * the text path start, at the calibrated normal offset. Null when the font is unavailable.
+ */
+function layOutPathText(
+ node: SceneNode,
+ data: TextPathData,
+ box: Rect,
+ type: PathTextType,
+ layout: PathTextLayout
+): DerivedTextGlyph[] | null {
+ const { fontSize, letterSpacing } = type
+ const metrics = getGlyphOutlineMetricsSync(
+ type.fontFamily,
+ weightToStyle(type.fontWeight, type.italic),
+ type.text,
+ fontSize
+ )
+ if (!metrics) return null
+ const run = alignedRun(
+ node,
+ data,
+ box,
+ type.textAlignHorizontal,
+ layout.anchor,
+ metrics,
+ letterSpacing
+ )
+ return layoutPathTextFromAdvances(
+ data,
+ box,
+ run.anchor,
+ mean(layout.offsets),
+ metrics.slice(0, run.count).map((m) => ({
+ commandsBlob: encodePathCommandsBlob(m.commands, fontSize),
+ fontSize,
+ // Pen walk expects em advances (it multiplies by fontSize); metrics and
+ // letterSpacing are px. Folding letterSpacing in here (rather than
+ // threading it through layoutPathTextFromAdvances) keeps that function's
+ // em-advance contract unchanged for its one caller.
+ advance: (m.advance + letterSpacing) / fontSize
+ }))
+ )
+}
+
+/**
+ * Re-flow imported path text when its characters or typography change: rebuild glyph
* outlines from the local font and pen-walk them along the preserved path,
* keeping the calibrated anchor and mean normal offset. Returns {} whenever
* the node is not reflowable path text or the font is unavailable — the
@@ -24,50 +86,158 @@ export function pathTextEditChanges(
changes: Partial<SceneNode>
): Partial<Pick<SceneNode, 'derivedTextGlyphs' | 'strokeGeometry'>> {
if (node?.type !== 'TEXT') return {}
- if (typeof changes.text !== 'string') return {}
- if (changes.text.trim().length === 0) {
+ if (!PATH_TEXT_LAYOUT_FIELDS.some((field) => changes[field] !== undefined)) return {}
+ const text = changes.text ?? node.text
+ if (text.trim().length === 0) {
return node.textPathBox ? { derivedTextGlyphs: null, strokeGeometry: [] } : {}
}
if (!node.textPathBox || !node.derivedTextGlyphs?.length) return {}
const data = getTextPathData(node)
if (!data) return {}
-
- // Prefer pending typography from the same update batch over the pre-update
- // node so { text, fontSize/fontFamily/... } stays consistent for reflow.
- const fontFamily = changes.fontFamily ?? node.fontFamily
- const fontWeight = changes.fontWeight ?? node.fontWeight
- const italic = changes.italic ?? node.italic
- const fontSize = changes.fontSize ?? node.fontSize
- const letterSpacing = changes.letterSpacing ?? node.letterSpacing
-
- const metrics = getGlyphOutlineMetricsSync(
- fontFamily,
- weightToStyle(fontWeight, italic),
- changes.text,
- fontSize
- )
- if (!metrics) return {}
-
const layout = calibratePathTextLayout(node.derivedTextGlyphs, data, node.textPathBox)
if (!layout) return {}
- const offset = mean(layout.offsets)
- const glyphs = layoutPathTextFromAdvances(
+ // Prefer pending typography from the same update batch over the pre-update
+ // node so { text, fontSize/textAlignHorizontal/... } stays consistent for reflow.
+ const glyphs = layOutPathText(
+ node,
data,
node.textPathBox,
- layout.anchor,
- offset,
- metrics.map((m) => ({
- commandsBlob: encodePathCommandsBlob(m.commands, fontSize),
- fontSize,
- // Pen walk expects em advances (it multiplies by fontSize); metrics and
- // letterSpacing are px. Folding letterSpacing in here (rather than
- // threading it through layoutPathTextFromAdvances) keeps that function's
- // em-advance contract unchanged for its one caller.
- advance: (m.advance + letterSpacing) / fontSize
- }))
+ {
+ text,
+ fontFamily: changes.fontFamily ?? node.fontFamily,
+ fontWeight: changes.fontWeight ?? node.fontWeight,
+ italic: changes.italic ?? node.italic,
+ fontSize: changes.fontSize ?? node.fontSize,
+ letterSpacing: changes.letterSpacing ?? node.letterSpacing,
+ textAlignHorizontal: changes.textAlignHorizontal ?? node.textAlignHorizontal
+ },
+ layout
)
// Baked silhouettes belong to the OLD string — clear them so the renderer
// rebuilds per-glyph silhouettes for the new lettering.
return glyphs ? { derivedTextGlyphs: glyphs, strokeGeometry: [] } : {}
}
+
+/**
+ * Glyphs for path text whose path now maps into `box`, laid out again from its characters at the
+ * same font size, as Figma does, rather than moving the old glyphs, which only fit the old path.
+ * `glyphs` and `origBox` are the layer before the resize. Null when the font is unavailable.
+ */
+export function resizedPathTextGlyphs(
+ node: SceneNode,
+ glyphs: DerivedTextGlyph[],
+ origBox: Rect,
+ box: Rect
+): DerivedTextGlyph[] | null {
+ const data = getTextPathData(node)
+ if (!data || node.text.trim().length === 0) return null
+ const layout = calibratePathTextLayout(glyphs, data, origBox)
+ return layout ? layOutPathText(node, data, box, node, layout) : null
+}
+
+/** How far along the path the start of new text moves so it keeps its alignment, px. */
+function alignmentShift(align: SceneNode['textAlignHorizontal'], before: number, after: number) {
+ if (align === 'CENTER') return (before - after) / 2
+ if (align === 'RIGHT') return before - after
+ return 0
+}
+
+const runWidth = (run: Array<{ advance: number }>, spacing: number) =>
+ run.reduce((sum, glyph) => sum + glyph.advance + spacing, 0)
+
+/**
+ * The part of the path aligned text may use, in px from the text path start along the direction
+ * the text runs. Left-aligned text runs from the start to the path's end, right-aligned text from
+ * the path's beginning to the start, and centered text gets the widest span centered on the start.
+ * Justified text on an open path gets the whole path; on a closed path, every alignment gets one
+ * loop anchored at the start.
+ */
+function alignmentWindow(
+ align: SceneNode['textAlignHorizontal'],
+ start: number,
+ length: number,
+ closed: boolean,
+ forward: boolean
+): [number, number] {
+ if (closed) {
+ if (align === 'CENTER') return [-length / 2, length / 2]
+ return align === 'RIGHT' ? [-length, 0] : [0, length]
+ }
+ const ahead = forward ? length - start : start
+ const behind = forward ? start : length - start
+ if (align === 'CENTER') {
+ const half = Math.min(ahead, behind)
+ return [-half, half]
+ }
+ if (align === 'RIGHT') return [-behind, 0]
+ if (align === 'JUSTIFIED') return [-behind, ahead]
+ return [0, ahead]
+}
+
+/** How many leading glyphs fit in `room` px; the first always stays. */
+function fittingGlyphCount(run: Array<{ advance: number }>, spacing: number, room: number) {
+ let width = 0
+ for (const [index, glyph] of run.entries()) {
+ width += glyph.advance + spacing
+ if (index > 0 && width > room + 1e-6) return index
+ }
+ return run.length
+}
+
+/**
+ * Where new text starts on the path, as a fraction of its length, and how many of its glyphs
+ * are drawn.
+ *
+ * Figma lays aligned path text out from the text path start: the point at `tValue` on the
+ * segment its network marks (`textPathStartDistance`). Left-aligned text starts there, centered
+ * text is centered on it and right-aligned text ends there, in the direction the text runs.
+ * Text that doesn't fit the alignment's part of the path (`alignmentWindow`) keeps only the
+ * leading glyphs that do, aligned within that part; nothing runs past the ends of an open path
+ * or around a closed one twice. A lone glyph wider than its part starts where the part does.
+ *
+ * Path text without a known start keeps its alignment relative to the old run instead: the
+ * shift is the difference between the old and new widths.
+ */
+function alignedRun(
+ node: SceneNode,
+ data: TextPathData,
+ box: Rect,
+ align: SceneNode['textAlignHorizontal'],
+ anchor: number,
+ metrics: Array<{ advance: number }>,
+ letterSpacing: number
+): { anchor: number; count: number } {
+ const all = { anchor, count: metrics.length }
+ const path = sampleTextPath(data, box)
+ if (!path || path.length === 0) return all
+ const direction = data.forward ? 1 : -1
+
+ const start = data.startSegment === undefined ? null : textPathStartDistance(data, path)
+ if (start !== null) {
+ const [from, to] = alignmentWindow(align, start, path.length, path.closed, data.forward)
+ const count = fittingGlyphCount(metrics, letterSpacing, to - from)
+ const width = runWidth(metrics.slice(0, count), letterSpacing)
+ let offset = from
+ if (width <= to - from) {
+ if (align === 'CENTER') offset = (from + to - width) / 2
+ else if (align === 'RIGHT') offset = to - width
+ }
+ return { anchor: (start + direction * offset) / path.length, count }
+ }
+
+ if (align !== 'CENTER' && align !== 'RIGHT') return all
+ const old = getGlyphOutlineMetricsSync(
+ node.fontFamily,
+ weightToStyle(node.fontWeight, node.italic),
+ node.text,
+ node.fontSize
+ )
+ if (!old) return all
+ const shift = alignmentShift(
+ align,
+ runWidth(old, node.letterSpacing),
+ runWidth(metrics, letterSpacing)
+ )
+ return { anchor: anchor + (direction * shift) / path.length, count: metrics.length }
+}
diff --git a/packages/core/src/text/editor.ts b/packages/core/src/text/editor.ts
index 63ae5d05c..608cdf2aa 100644
--- a/packages/core/src/text/editor.ts
+++ b/packages/core/src/text/editor.ts
@@ -1,12 +1,21 @@
import type { CanvasKit } from 'canvaskit-wasm'
-import type { SceneNode } from '@open-pencil/scene-graph'
-import type { Rect } from '@open-pencil/scene-graph/primitives'
+import type { DerivedTextGlyph, SceneNode } from '@open-pencil/scene-graph'
+import type { Rect, Vector } 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'
+import { weightToStyle } from '#core/text/fonts'
import { nextGraphemeBoundary, previousGraphemeBoundary } from '#core/text/graphemes'
+import { fontVerticalMetricsSync } from '#core/text/opentype'
+import {
+ pathTextCaret,
+ pathTextIndexAt,
+ pathTextSelectionQuads,
+ type PathTextCaret,
+ type PathTextLineMetrics
+} from '#core/text/path/caret'
export interface TextCaret {
x: number
@@ -51,6 +60,27 @@ export class TextEditor {
return y - this.paragraphVerticalOffset()
}
+ /**
+ * Text on a path is edited on its glyphs rather than the flat paragraph: the caret, the
+ * selection and the character a point hits follow the path, as in Figma.
+ */
+ private pathText(): { glyphs: DerivedTextGlyph[]; metrics: PathTextLineMetrics } | null {
+ const node = this.paragraphNode
+ if (!node?.textPathData || !node.derivedTextGlyphs?.length) return null
+ const metrics = fontVerticalMetricsSync(
+ node.fontFamily,
+ weightToStyle(node.fontWeight, node.italic)
+ )
+ return metrics ? { glyphs: node.derivedTextGlyphs, metrics } : null
+ }
+
+ /** The character boundary at a node-local point. */
+ private indexAt(s: TextEditorState, x: number, y: number): number | null {
+ const path = this.pathText()
+ if (path) return pathTextIndexAt(path.glyphs, s.text.length, { x, y }, path.metrics)
+ return s.paragraph?.getGlyphPositionAtCoordinate(x, this.paragraphY(y)).pos ?? null
+ }
+
private prepareMove(extend: boolean): TextEditorState | null {
const s = this.current()
if (!s) return null
@@ -214,8 +244,9 @@ export class TextEditor {
setCursorAt(x: number, y: number, extend = false): void {
const s = this.current()
- if (!s?.paragraph) return
- const pos = s.paragraph.getGlyphPositionAtCoordinate(x, this.paragraphY(y)).pos
+ if (!s) return
+ const pos = this.indexAt(s, x, y)
+ if (pos === null) return
if (extend) {
if (s.selectionAnchor === null) s.selectionAnchor = s.cursor
} else {
@@ -237,16 +268,14 @@ export class TextEditor {
selectWordAt(x: number, y: number): void {
const s = this.current()
- if (!s?.paragraph) return
- const pos = s.paragraph.getGlyphPositionAtCoordinate(x, this.paragraphY(y)).pos
- this.selectWord(pos)
+ const pos = s && this.indexAt(s, x, y)
+ if (pos !== null) this.selectWord(pos)
}
selectLineAt(x: number, y: number): void {
const s = this.current()
- if (!s?.paragraph) return
- const pos = s.paragraph.getGlyphPositionAtCoordinate(x, this.paragraphY(y)).pos
- this.selectLine(pos)
+ const pos = s && this.indexAt(s, x, y)
+ if (pos !== null) this.selectLine(pos)
}
insert(text: string, node: SceneNode): void {
@@ -400,6 +429,31 @@ export class TextEditor {
return { x, y0: offsetY, y1: offsetY + height }
}
+ /** The caret along the path, for text on a path. */
+ getPathCaret(): PathTextCaret | null {
+ const s = this.current()
+ const path = this.pathText()
+ if (!s || !path) return null
+ return pathTextCaret(path.glyphs, s.text.length, s.cursor, path.metrics)
+ }
+
+ /** The boxes of every glyph along the path, for outlining the lettering while it is edited. */
+ getPathTextQuads(): Vector[][] {
+ const s = this.current()
+ const path = this.pathText()
+ if (!s || !path) return []
+ return pathTextSelectionQuads(path.glyphs, s.text.length, 0, s.text.length, path.metrics)
+ }
+
+ /** The selection along the path, one box per glyph, for text on a path. */
+ getPathSelectionQuads(): Vector[][] {
+ const s = this.current()
+ const path = this.pathText()
+ const range = this.getSelectionRange()
+ if (!s || !path || !range) return []
+ return pathTextSelectionQuads(path.glyphs, s.text.length, range[0], range[1], path.metrics)
+ }
+
getCaretRect(): TextCaret | null {
const s = this.current()
if (!s?.paragraph) return null
diff --git a/packages/core/src/text/opentype.ts b/packages/core/src/text/opentype.ts
index 491ab4c7c..b4f7a6a82 100644
--- a/packages/core/src/text/opentype.ts
+++ b/packages/core/src/text/opentype.ts
@@ -171,6 +171,16 @@ export function fontDecorationMetricsSync(
}
}
+/** How far a loaded font reaches above and below the baseline, in ems; null when not loaded. */
+export function fontVerticalMetricsSync(
+ family: string,
+ style: string
+): { ascent: number; descent: number } | null {
+ const font = getParsedFont(family, style)
+ if (!font || !(font.unitsPerEm > 0)) return null
+ return { ascent: font.ascender / font.unitsPerEm, descent: -font.descender / font.unitsPerEm }
+}
+
export interface GlyphOutlineMetrics {
commands: OutlineCommand[]
x: number
diff --git a/packages/core/src/text/path/caret.ts b/packages/core/src/text/path/caret.ts
new file mode 100644
index 000000000..adab5085f
--- /dev/null
+++ b/packages/core/src/text/path/caret.ts
@@ -0,0 +1,143 @@
+import type { DerivedTextGlyph } from '@open-pencil/scene-graph'
+import type { Vector } from '@open-pencil/scene-graph/primitives'
+
+/** How far the font reaches above and below the baseline, in ems. */
+export interface PathTextLineMetrics {
+ ascent: number
+ descent: number
+}
+
+/** A glyph on the path in its own frame: where its baseline starts, its directions and extent. */
+interface PlacedGlyph {
+ origin: Vector
+ /** Unit baseline direction, the way the text runs. */
+ along: Vector
+ /** Unit direction from the baseline to the ascender. */
+ up: Vector
+ advance: number
+ ascent: number
+ descent: number
+ /** Characters the glyph draws, [start, end). */
+ start: number
+ end: number
+}
+
+/** A caret: a line square to the baseline from the descent to the ascent. */
+export interface PathTextCaret {
+ from: Vector
+ to: Vector
+}
+
+function placedGlyphs(
+ glyphs: readonly DerivedTextGlyph[],
+ textLength: number,
+ metrics: PathTextLineMetrics
+): PlacedGlyph[] {
+ return glyphs.map((glyph, index) => {
+ const rotation = glyph.rotation ?? 0
+ const along = { x: Math.cos(rotation), y: -Math.sin(rotation) }
+ const next = glyphs.at(index + 1)
+ // Without a saved advance a glyph reaches the next one; the last one then has no width.
+ const advance =
+ glyph.advance ?? (next ? (next.x - glyph.x) * along.x + (next.y - glyph.y) * along.y : 0)
+ const start = glyph.firstCharacter ?? index
+ return {
+ origin: { x: glyph.x, y: glyph.y },
+ along,
+ up: { x: -Math.sin(rotation), y: -Math.cos(rotation) },
+ advance: Math.max(0, advance),
+ ascent: metrics.ascent * glyph.fontSize,
+ descent: metrics.descent * glyph.fontSize,
+ start,
+ // Characters past the last glyph, cut where the text ran out of path, have no glyph.
+ end: Math.min(next ? (next.firstCharacter ?? index + 1) : start + 1, textLength)
+ }
+ })
+}
+
+const at = (glyph: PlacedGlyph, distance: number, height: number): Vector => ({
+ x: glyph.origin.x + glyph.along.x * distance + glyph.up.x * height,
+ y: glyph.origin.y + glyph.along.y * distance + glyph.up.y * height
+})
+
+/** How far along a glyph its `index`th character starts, sharing a ligature's width evenly. */
+function distanceOf(glyph: PlacedGlyph, index: number): number {
+ const count = glyph.end - glyph.start
+ if (count <= 0) return 0
+ return (glyph.advance * Math.min(Math.max(index - glyph.start, 0), count)) / count
+}
+
+/**
+ * The caret before character `index`: at the start of the glyph drawing it, or after the last
+ * glyph when the characters from `index` on are past the end or not drawn.
+ */
+export function pathTextCaret(
+ glyphs: readonly DerivedTextGlyph[],
+ textLength: number,
+ index: number,
+ metrics: PathTextLineMetrics
+): PathTextCaret | null {
+ const placed = placedGlyphs(glyphs, textLength, metrics)
+ const glyph = placed.find((candidate) => index < candidate.end) ?? placed.at(-1)
+ if (!glyph) return null
+ const distance = distanceOf(glyph, index)
+ return { from: at(glyph, distance, -glyph.descent), to: at(glyph, distance, glyph.ascent) }
+}
+
+/**
+ * The character boundary nearest a point: the glyph whose box, from the descent to the ascent,
+ * the point is in or closest to, and the side of the character in it the point is on.
+ */
+export function pathTextIndexAt(
+ glyphs: readonly DerivedTextGlyph[],
+ textLength: number,
+ point: Vector,
+ metrics: PathTextLineMetrics
+): number {
+ let best: { glyph: PlacedGlyph; distance: number } | null = null
+ let bestGap = Infinity
+ for (const glyph of placedGlyphs(glyphs, textLength, metrics)) {
+ const dx = point.x - glyph.origin.x
+ const dy = point.y - glyph.origin.y
+ const distance = dx * glyph.along.x + dy * glyph.along.y
+ const height = dx * glyph.up.x + dy * glyph.up.y
+ const gap = Math.hypot(
+ Math.max(0, -distance, distance - glyph.advance),
+ Math.max(0, -glyph.descent - height, height - glyph.ascent)
+ )
+ if (gap < bestGap) {
+ bestGap = gap
+ best = { glyph, distance }
+ }
+ }
+ if (!best) return textLength
+ const { glyph, distance } = best
+ const count = glyph.end - glyph.start
+ if (count <= 0 || glyph.advance <= 0) return glyph.start
+ const step = glyph.advance / count
+ return glyph.start + Math.min(Math.max(Math.round(distance / step), 0), count)
+}
+
+/** The boxes covering the characters [from, to): one per glyph they touch, rotated with it. */
+export function pathTextSelectionQuads(
+ glyphs: readonly DerivedTextGlyph[],
+ textLength: number,
+ from: number,
+ to: number,
+ metrics: PathTextLineMetrics
+): Vector[][] {
+ const quads: Vector[][] = []
+ for (const glyph of placedGlyphs(glyphs, textLength, metrics)) {
+ if (glyph.end <= from || glyph.start >= to) continue
+ const start = distanceOf(glyph, from)
+ const end = distanceOf(glyph, to)
+ if (!(end > start)) continue
+ quads.push([
+ at(glyph, start, -glyph.descent),
+ at(glyph, end, -glyph.descent),
+ at(glyph, end, glyph.ascent),
+ at(glyph, start, glyph.ascent)
+ ])
+ }
+ return quads
+}
diff --git a/packages/core/src/text/path/index.ts b/packages/core/src/text/path/index.ts
index 0d9eee27b..4249f3b5c 100644
--- a/packages/core/src/text/path/index.ts
+++ b/packages/core/src/text/path/index.ts
@@ -1,9 +1,9 @@
import type { SceneNode, TextPathData } from '@open-pencil/scene-graph'
+export * from './caret'
export * from './fitting'
export * from './layout'
export * from './sampling'
-export * from './selection'
export function getTextPathData(node: SceneNode): TextPathData | null {
return node.textPathData
diff --git a/packages/core/src/text/path/layout.ts b/packages/core/src/text/path/layout.ts
index 77cbbab01..338f18d75 100644
--- a/packages/core/src/text/path/layout.ts
+++ b/packages/core/src/text/path/layout.ts
@@ -108,7 +108,8 @@ export function calibratePathTextLayout(
* at `anchor` (fraction of total length), each next glyph advances by
* advance * fontSize (advances are in em units) along the travel direction,
* offset along the left normal by `offset`. Used when the characters change
- * and the baked per-glyph deltas no longer apply.
+ * and the baked per-glyph deltas no longer apply. Each glyph keeps its advance
+ * in px, so the caret can stand after the last one.
*/
export function layoutPathTextFromAdvances(
data: TextPathData,
@@ -123,13 +124,15 @@ export function layoutPathTextFromAdvances(
let s = anchor * path.length
return glyphSources.map((src) => {
const p = pointAtArc(path, s)
- s += dir * src.advance * src.fontSize
+ const advance = src.advance * src.fontSize
+ s += dir * advance
return {
commandsBlob: src.commandsBlob,
x: p.x + -p.ty * offset,
y: p.y + p.tx * offset,
fontSize: src.fontSize,
- rotation: normalizeAngle(chordRotation(p, pointAtArc(path, s), data.forward))
+ rotation: normalizeAngle(chordRotation(p, pointAtArc(path, s), data.forward)),
+ advance
}
})
}
diff --git a/packages/core/src/text/path/sampling.ts b/packages/core/src/text/path/sampling.ts
index 2ed1c7999..658005b12 100644
--- a/packages/core/src/text/path/sampling.ts
+++ b/packages/core/src/text/path/sampling.ts
@@ -1,16 +1,27 @@
-import { svgPathProperties } from 'svg-path-properties'
+import { clamp } from 'es-toolkit'
import type { TextPathData } from '@open-pencil/scene-graph'
-import type { Rect } from '@open-pencil/scene-graph/primitives'
+import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'
-type PathProperties = InstanceType<typeof svgPathProperties>
+interface Cubic {
+ p0: Vector
+ p1: Vector
+ p2: Vector
+ p3: Vector
+}
+/**
+ * The layout path flattened once into points about half a pixel apart. Each point keeps the curve
+ * and parameter it came from, so a lookup between two points evaluates the curve itself.
+ */
export interface SampledPath {
- properties: PathProperties
+ curves: Cubic[]
xs: Float64Array
ys: Float64Array
/** Arc lengths corresponding to the sampled points. */
cum: Float64Array
+ curveIndex: Uint32Array
+ ts: Float64Array
length: number
closed: boolean
}
@@ -24,53 +35,98 @@ export interface PathPoint {
s: number
}
-function svgPath(data: TextPathData, box: Rect): string | null {
+const MIN_SAMPLES = 64
+const MAX_SAMPLES = 2048
+const MIN_CURVE_STEPS = 4
+
+/** The network's segments as cubics mapped into `box`, in segment order. */
+function pathCurves(data: TextPathData, box: Rect): Cubic[] | null {
if (!(data.normalizedSize.x > 0) || !(data.normalizedSize.y > 0)) return null
const sx = box.width / data.normalizedSize.x
const sy = box.height / data.normalizedSize.y
- const commands: string[] = []
- let previousEnd: number | null = null
-
+ const at = (x: number, y: number): Vector => ({ x: box.x + x * sx, y: box.y + y * sy })
+ const curves: Cubic[] = []
for (const segment of data.network.segments) {
const start = data.network.vertices.at(segment.start)
const end = data.network.vertices.at(segment.end)
if (!start || !end) return null
- const startX = box.x + start.x * sx
- const startY = box.y + start.y * sy
- if (previousEnd !== segment.start) commands.push(`M${startX} ${startY}`)
- commands.push(
- `C${box.x + (start.x + segment.tangentStart.x) * sx} ${box.y + (start.y + segment.tangentStart.y) * sy} ` +
- `${box.x + (end.x + segment.tangentEnd.x) * sx} ${box.y + (end.y + segment.tangentEnd.y) * sy} ` +
- `${box.x + end.x * sx} ${box.y + end.y * sy}`
- )
- previousEnd = segment.end
+ curves.push({
+ p0: at(start.x, start.y),
+ p1: at(start.x + segment.tangentStart.x, start.y + segment.tangentStart.y),
+ p2: at(end.x + segment.tangentEnd.x, end.y + segment.tangentEnd.y),
+ p3: at(end.x, end.y)
+ })
}
+ return curves.length > 0 ? curves : null
+}
- return commands.length > 0 ? commands.join(' ') : null
+function cubicPoint({ p0, p1, p2, p3 }: Cubic, t: number): Vector {
+ const u = 1 - t
+ const a = u * u * u
+ const b = 3 * u * u * t
+ const c = 3 * u * t * t
+ const d = t * t * t
+ return {
+ x: a * p0.x + b * p1.x + c * p2.x + d * p3.x,
+ y: a * p0.y + b * p1.y + c * p2.y + d * p3.y
+ }
}
-/** Build headless SVG path metrics for the vector network mapped into `box`. */
+function cubicDerivative({ p0, p1, p2, p3 }: Cubic, t: number): Vector {
+ const u = 1 - t
+ const a = 3 * u * u
+ const b = 6 * u * t
+ const c = 3 * t * t
+ return {
+ x: a * (p1.x - p0.x) + b * (p2.x - p1.x) + c * (p3.x - p2.x),
+ y: a * (p1.y - p0.y) + b * (p2.y - p1.y) + c * (p3.y - p2.y)
+ }
+}
+
+/** Length of the control polygon: an upper bound on the curve's length, for spacing samples. */
+function hullLength({ p0, p1, p2, p3 }: Cubic): number {
+ return (
+ Math.hypot(p1.x - p0.x, p1.y - p0.y) +
+ Math.hypot(p2.x - p1.x, p2.y - p1.y) +
+ Math.hypot(p3.x - p2.x, p3.y - p2.y)
+ )
+}
+
+/** Flatten the vector network mapped into `box` for arc-length lookups. */
export function sampleTextPath(data: TextPathData, box: Rect): SampledPath | null {
- const source = svgPath(data, box)
- if (!source) return null
- const properties = new svgPathProperties(source)
- const length = properties.getTotalLength()
- if (!(length > 0) || !Number.isFinite(length)) return null
- const start = properties.getPointAtLength(0)
- const end = properties.getPointAtLength(length)
- const closed = Math.hypot(end.x - start.x, end.y - start.y) < length / 1024 + 1e-6
- const sampleCount = Math.max(64, Math.min(2048, Math.ceil(length * 2)))
- const xs = new Float64Array(sampleCount + 1)
- const ys = new Float64Array(sampleCount + 1)
- const cum = new Float64Array(sampleCount + 1)
- for (let index = 0; index <= sampleCount; index++) {
- const distance = (length * index) / sampleCount
- const point = properties.getPointAtLength(distance)
- xs[index] = point.x
- ys[index] = point.y
- cum[index] = distance
+ const curves = pathCurves(data, box)
+ if (!curves) return null
+ const hulls = curves.map(hullLength)
+ const hull = hulls.reduce((sum, value) => sum + value, 0)
+ if (!(hull > 0) || !Number.isFinite(hull)) return null
+ const target = clamp(Math.ceil(hull * 2), MIN_SAMPLES, MAX_SAMPLES)
+ const steps = hulls.map((value) => Math.max(MIN_CURVE_STEPS, Math.round((target * value) / hull)))
+ const count = steps.reduce((sum, value) => sum + value + 1, 0)
+ const xs = new Float64Array(count)
+ const ys = new Float64Array(count)
+ const cum = new Float64Array(count)
+ const curveIndex = new Uint32Array(count)
+ const ts = new Float64Array(count)
+
+ let index = 0
+ let length = 0
+ for (const [curve, cubic] of curves.entries()) {
+ for (let step = 0; step <= steps[curve]; step++) {
+ const t = step / steps[curve]
+ const point = cubicPoint(cubic, t)
+ // A segment that does not start where the last one ended jumps there without adding length.
+ if (step > 0) length += Math.hypot(point.x - xs[index - 1], point.y - ys[index - 1])
+ xs[index] = point.x
+ ys[index] = point.y
+ cum[index] = length
+ curveIndex[index] = curve
+ ts[index] = t
+ index++
+ }
}
- return { properties, xs, ys, cum, length, closed }
+ if (!(length > 0)) return null
+ const closed = Math.hypot(xs[count - 1] - xs[0], ys[count - 1] - ys[0]) < length / 1024 + 1e-6
+ return { curves, xs, ys, cum, curveIndex, ts, length, closed }
}
/** Node-local point and unit tangent at absolute arc length `sIn`. */
@@ -78,8 +134,33 @@ export function pointAtArc(path: SampledPath, sIn: number): PathPoint {
let s = sIn
if (path.closed) s = ((s % path.length) + path.length) % path.length
else s = Math.min(Math.max(s, 0), path.length)
- const point = path.properties.getPropertiesAtLength(s)
- return { x: point.x, y: point.y, tx: point.tangentX, ty: point.tangentY, s }
+
+ const { cum, curveIndex, ts } = path
+ let lo = 0
+ let hi = cum.length - 1
+ while (hi - lo > 1) {
+ const mid = (lo + hi) >> 1
+ if (cum[mid] < s) lo = mid
+ else hi = mid
+ }
+ const span = cum[hi] - cum[lo]
+ const sameCurve = curveIndex[lo] === curveIndex[hi]
+ const curve = path.curves[sameCurve ? curveIndex[lo] : curveIndex[hi]]
+ const t = sameCurve && span > 0 ? ts[lo] + ((ts[hi] - ts[lo]) * (s - cum[lo])) / span : ts[hi]
+ const point = cubicPoint(curve, t)
+
+ // A straight segment with no handles has no derivative at its ends; take the samples' direction.
+ let { x: dx, y: dy } = cubicDerivative(curve, t)
+ if (Math.hypot(dx, dy) < 1e-9) {
+ dx = path.xs[hi] - path.xs[lo]
+ dy = path.ys[hi] - path.ys[lo]
+ }
+ if (Math.hypot(dx, dy) < 1e-9) {
+ dx = curve.p3.x - curve.p0.x
+ dy = curve.p3.y - curve.p0.y
+ }
+ const norm = Math.hypot(dx, dy) || 1
+ return { x: point.x, y: point.y, tx: dx / norm, ty: dy / norm, s }
}
/** Closest sampled/refined path point, used to calibrate imported glyph baselines. */
@@ -97,3 +178,31 @@ export function nearestArcPoint(path: SampledPath, px: number, py: number): Path
const along = (px - point.x) * point.tx + (py - point.y) * point.ty
return pointAtArc(path, point.s + along)
}
+
+/**
+ * How far along the sampled path the text starts: on the segment Figma marks as the start, at
+ * `tValue` along it as a curve parameter. Null when the start segment is missing.
+ */
+export function textPathStartDistance(data: TextPathData, path: SampledPath): number | null {
+ const startSegment = data.startSegment ?? 0
+ if (startSegment < 0 || startSegment >= path.curves.length) return null
+ const t = clamp(data.tValue, 0, 1)
+ const { cum, curveIndex, ts } = path
+ for (let index = 1; index < cum.length; index++) {
+ if (curveIndex[index] !== startSegment || ts[index] < t) continue
+ // Each curve's samples run from t = 0 to 1; its first one starts where the curve before ended.
+ const span = ts[index] - ts[index - 1]
+ const f = span > 0 ? (t - ts[index - 1]) / span : 0
+ return cum[index - 1] + (cum[index] - cum[index - 1]) * f
+ }
+ return null
+}
+
+/**
+ * How far along `path` the text path start sits: the marked start segment when the import read
+ * one, else `tValue` as a fraction of the whole path.
+ */
+export function textPathStartArc(data: TextPathData, path: SampledPath): number {
+ const start = data.startSegment === undefined ? null : textPathStartDistance(data, path)
+ return clamp(start ?? data.tValue * path.length, 0, path.length)
+}
diff --git a/packages/core/src/text/path/selection.ts b/packages/core/src/text/path/selection.ts
deleted file mode 100644
index d9cae52d7..000000000
--- a/packages/core/src/text/path/selection.ts
+++ /dev/null
@@ -1,127 +0,0 @@
-import type { DerivedTextGlyph, TextPathData } from '@open-pencil/scene-graph'
-import type { Rect } from '@open-pencil/scene-graph/primitives'
-
-import { nearestArcPoint, pointAtArc, sampleTextPath, type SampledPath } from './sampling'
-
-/**
- * A closed ribbon polygon (node-local, flat `[x0,y0,x1,y1,...]`) that hugs the
- * lettering along the path — the Figma-style "selection band" for text on a
- * path. It runs along the arc the glyphs occupy, offset out to ~cap height and
- * in to ~descender, so a filled/stroked polygon traces the text instead of the
- * flat axis-aligned selection rects (which float over the artwork). Returns null
- * with no glyphs or an unsampleable path.
- *
- * The outward side is chosen per-sample as the normal pointing away from the box
- * centre (correct for the common circular/arc case); the band straddles the
- * baseline so it covers the glyphs without needing per-font ascent metrics.
- */
-interface BandGlyph {
- s: number
- ux: number
- uy: number
-}
-
-/**
- * Arc-length span [start, end] the glyphs actually cover. On a closed path the
- * run can straddle the seam (s=0), so a plain [min,max] would trace the empty
- * COMPLEMENT arc ("huge empty band over the top of the circle"). Take the
- * complement of the largest inter-glyph gap (including the wrap gap through the
- * seam); `end` may exceed length and wraps via pointAtArc.
- */
-function glyphBandArc(gs: BandGlyph[], length: number, closed: boolean): [number, number] {
- const ss = gs.map((g) => g.s)
- if (!closed || ss.length <= 1) return [Math.min(...ss), Math.max(...ss)]
- ss.sort((a, b) => a - b)
- let maxGap = ss[0] + length - ss[ss.length - 1] // wrap gap (no straddle)
- let start = ss[0]
- let end = ss[ss.length - 1]
- for (let i = 0; i + 1 < ss.length; i++) {
- const gap = ss[i + 1] - ss[i]
- if (gap > maxGap) {
- maxGap = gap
- start = ss[i + 1]
- end = ss[i] + length // straddles: wrap forward through the seam
- }
- }
- return [start, end]
-}
-
-/** Up-vector of the glyph nearest arc position `s` (circular on closed paths). */
-function nearestGlyphUp(
- gs: BandGlyph[],
- s: number,
- length: number,
- closed: boolean
-): [number, number] {
- let ux = 0
- let uy = 0
- let best = Infinity
- for (const g of gs) {
- let ds = Math.abs(g.s - s)
- if (closed) ds = Math.min(ds, length - ds)
- if (ds < best) {
- best = ds
- ux = g.ux
- uy = g.uy
- }
- }
- return [ux, uy]
-}
-
-export function pathTextSelectionBand(
- data: TextPathData,
- box: Rect,
- glyphs: readonly Pick<DerivedTextGlyph, 'x' | 'y' | 'fontSize' | 'rotation'>[] | null | undefined,
- // Callers that already sampled this data/box (the selection overlay) pass it
- // in to avoid re-sampling the curve every repaint.
- presampled?: SampledPath | null
-): number[] | null {
- if (!glyphs?.length) return null
- const sampled = presampled ?? sampleTextPath(data, box)
- if (!sampled) return null
- const { length } = sampled
-
- // Each glyph → its arc-length position on the path + its ascender ("up")
- // direction (from the glyph rotation). Positions pick the arc the band spans;
- // up-vectors pick which side of the baseline to inflate toward.
- const gs: BandGlyph[] = []
- let fontSize = 0
- for (const g of glyphs) {
- const rot = g.rotation ?? 0
- gs.push({ s: nearestArcPoint(sampled, g.x, g.y).s, ux: -Math.sin(rot), uy: -Math.cos(rot) })
- fontSize = Math.max(fontSize, g.fontSize || 0)
- }
- if (!(fontSize > 0)) return null
-
- const [arcStart, arcEnd] = glyphBandArc(gs, length, sampled.closed)
- // Pad so the first/last glyph bodies are covered; clamp to one full loop so a
- // near-complete circle doesn't overlap itself at the seam.
- const sStart = arcStart - fontSize * 0.3
- const span = Math.min(arcEnd + fontSize * 0.3 - sStart, length)
- if (!(span > 0)) return null
-
- const capH = fontSize * 0.72 // out to ~cap height
- const descH = fontSize * 0.14 // in to ~descender
-
- const steps = 48
- const outer: number[] = []
- const inner: number[] = []
- for (let i = 0; i <= steps; i++) {
- const p = pointAtArc(sampled, sStart + (span * i) / steps)
- // Offset direction from the NEAREST glyph's up-vector — not a global average,
- // which for text wrapping most of a circle cancels to ~0 and flips the sign
- // test, spawning a stray detached quad.
- const [ux, uy] = nearestGlyphUp(gs, p.s, length, sampled.closed)
- let nx = -p.ty
- let ny = p.tx
- if (nx * ux + ny * uy < 0) {
- nx = -nx
- ny = -ny
- }
- outer.push(p.x + nx * capH, p.y + ny * capH)
- inner.push(p.x - nx * descH, p.y - ny * descH)
- }
- const poly = outer.slice()
- for (let i = inner.length - 2; i >= 0; i -= 2) poly.push(inner[i], inner[i + 1])
- return poly
-}
diff --git a/packages/core/tests/text/path/caret.test.ts b/packages/core/tests/text/path/caret.test.ts
new file mode 100644
index 000000000..9a1d0ca5d
--- /dev/null
+++ b/packages/core/tests/text/path/caret.test.ts
@@ -0,0 +1,91 @@
+import { describe, expect, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+
+import type { DerivedTextGlyph } from '@open-pencil/scene-graph'
+
+import { pathTextCaret, pathTextIndexAt, pathTextSelectionQuads } from '#core/text/path'
+
+const metrics = { ascent: 0.9, descent: 0.2 }
+
+/** Glyphs 10 px wide at 10 px, one per character, on a baseline from `origin` along `rotation`. */
+function run(count: number, rotation = 0, origin = { x: 0, y: 50 }): DerivedTextGlyph[] {
+ const along = { x: Math.cos(rotation), y: -Math.sin(rotation) }
+ return Array.from({ length: count }, (_, index) => ({
+ commandsBlob: new Uint8Array(4),
+ x: origin.x + along.x * 10 * index,
+ y: origin.y + along.y * 10 * index,
+ fontSize: 10,
+ rotation,
+ advance: 10
+ }))
+}
+
+describe('the caret on text on a path', () => {
+ test('stands square to the baseline before its character, from the descent to the ascent', () => {
+ const caret = expectDefined(pathTextCaret(run(3), 3, 1, metrics))
+ expect(caret.from.x).toBeCloseTo(10)
+ expect(caret.from.y).toBeCloseTo(52)
+ expect(caret.to.x).toBeCloseTo(10)
+ expect(caret.to.y).toBeCloseTo(41)
+ })
+
+ test('stands after the last glyph at the end of the text', () => {
+ const caret = expectDefined(pathTextCaret(run(3), 3, 3, metrics))
+ expect(caret.from.x).toBeCloseTo(30)
+ })
+
+ test('turns with a glyph running down the path', () => {
+ // Text running down: the baseline points down and the ascender to the right.
+ const caret = expectDefined(pathTextCaret(run(2, -Math.PI / 2), 2, 1, metrics))
+ expect(caret.from.x).toBeCloseTo(-2)
+ expect(caret.from.y).toBeCloseTo(60)
+ expect(caret.to.x).toBeCloseTo(9)
+ expect(caret.to.y).toBeCloseTo(60)
+ })
+
+ test('stays after the last drawn glyph for characters cut off the path', () => {
+ const caret = expectDefined(pathTextCaret(run(3), 10, 7, metrics))
+ expect(caret.from.x).toBeCloseTo(30)
+ })
+})
+
+describe('the character a point on text on a path hits', () => {
+ test('is the boundary on the side of the character the point is on', () => {
+ expect(pathTextIndexAt(run(3), 3, { x: 14, y: 45 }, metrics)).toBe(1)
+ expect(pathTextIndexAt(run(3), 3, { x: 16, y: 45 }, metrics)).toBe(2)
+ })
+
+ test('is the nearest glyph’s for a point off the lettering', () => {
+ expect(pathTextIndexAt(run(3), 3, { x: 80, y: 50 }, metrics)).toBe(3)
+ expect(pathTextIndexAt(run(3), 3, { x: -20, y: 50 }, metrics)).toBe(0)
+ expect(pathTextIndexAt(run(3), 3, { x: 22, y: 10 }, metrics)).toBe(2)
+ })
+
+ test('follows a glyph turned with the path', () => {
+ // Running down from (0, 50): the second glyph spans y 60…70, its ascender to the right.
+ expect(pathTextIndexAt(run(3, -Math.PI / 2), 3, { x: 4, y: 67 }, metrics)).toBe(2)
+ expect(pathTextIndexAt(run(3, -Math.PI / 2), 3, { x: 4, y: 63 }, metrics)).toBe(1)
+ })
+
+ test('counts the characters a glyph draws, skipping those without one', () => {
+ // "A B": the space has no glyph, so the first glyph runs to the second's character.
+ const glyphs = run(2).map((glyph, index) => ({ ...glyph, firstCharacter: index * 2 }))
+ expect(pathTextIndexAt(glyphs, 3, { x: 2, y: 45 }, metrics)).toBe(0)
+ expect(pathTextIndexAt(glyphs, 3, { x: 7, y: 45 }, metrics)).toBe(1)
+ expect(pathTextIndexAt(glyphs, 3, { x: 12, y: 45 }, metrics)).toBe(2)
+ })
+})
+
+test('a selection on text on a path covers each glyph it touches, turned with it', () => {
+ const quads = pathTextSelectionQuads(run(3), 3, 1, 3, metrics)
+ expect(quads).toHaveLength(2)
+ const [first] = quads
+ expect(first.map(({ x, y }) => [Math.round(x), Math.round(y)])).toEqual([
+ [10, 52],
+ [20, 52],
+ [20, 41],
+ [10, 41]
+ ])
+ expect(pathTextSelectionQuads(run(3), 3, 1, 1, metrics)).toEqual([])
+})
diff --git a/packages/fig/src/node-change/convert.ts b/packages/fig/src/node-change/convert.ts
index 465bf6c43..ec5f19548 100644
--- a/packages/fig/src/node-change/convert.ts
+++ b/packages/fig/src/node-change/convert.ts
@@ -45,7 +45,7 @@ import {
resolveVectorNetwork,
resolveVectorStyleOverrideFills
} from './vector/geometry'
-import { decodeVectorNetworkBlob, type StyleOverride } from './vector/network'
+import { decodeVectorNetworkBlob, textPathStartSegment, type StyleOverride } from './vector/network'
export { convertEffects, convertFills, convertStrokes, setVariableColorResolver } from './paint'
export { importStyleRuns } from './style/runs'
@@ -607,7 +607,8 @@ function convertTextPathData(nc: NodeChange, blobs: Uint8Array[]): SceneNode['te
network: decodeVectorNetworkBlob(blob, vectorData.styleOverrideTable),
normalizedSize: { x: normalizedSize.x, y: normalizedSize.y },
tValue: textPathStart?.tValue ?? 0,
- forward: textPathStart?.forward ?? true
+ forward: textPathStart?.forward ?? true,
+ startSegment: textPathStartSegment(blob)
}
} catch {
return null
diff --git a/packages/fig/src/node-change/export/node.ts b/packages/fig/src/node-change/export/node.ts
index 672289585..dff619a5c 100644
--- a/packages/fig/src/node-change/export/node.ts
+++ b/packages/fig/src/node-change/export/node.ts
@@ -752,6 +752,12 @@ function applyComponentMetadata(
}
}
+/** Whether the node is still saved in the box Figma gave it, not in its own. */
+function savedInFigmaBox(node: SceneNode): boolean {
+ const payload = effectiveFigmaSourcePayload(node)
+ return !!payload.rawSize && !!payload.rawTransform
+}
+
function exportNodeSize(node: SceneNode): Vector {
// rawSize and rawTransform are a matched pair describing the ORIGINAL Figma
// box. Once the transform no longer backs the node, exportNodeTransform
@@ -759,10 +765,8 @@ function exportNodeSize(node: SceneNode): Vector {
// an un-expanded rawSize disagrees about the box (for rotation, a different
// centre) and the node drifts on reimport. Use rawSize only while the
// transform still backs it.
- const payload = effectiveFigmaSourcePayload(node)
- return payload.rawSize && payload.rawTransform
- ? { ...payload.rawSize }
- : { x: node.width, y: node.height }
+ const { rawSize } = effectiveFigmaSourcePayload(node)
+ return rawSize && savedInFigmaBox(node) ? { ...rawSize } : { x: node.width, y: node.height }
}
function exportNodeTransform(context: SceneNodeToKiwiContext, node: SceneNode): Matrix {
@@ -1048,7 +1052,7 @@ export function sceneNodeToKiwiWithContext(
applyExportSettingsPluginData(node)
applyLibrarySourcePluginData(node)
serializeNodeStatus(node, nc)
- applyTextPathBoxPluginData(node)
+ applyTextPathBoxPluginData(node, savedInFigmaBox(node))
const pluginData = mergePluginData(node.pluginData)
if (pluginData.length > 0) nc.pluginData = pluginData
if (node.pluginRelaunchData.length > 0) {
diff --git a/packages/fig/src/node-change/plugin-data.ts b/packages/fig/src/node-change/plugin-data.ts
index 6c1e3b003..444c31d69 100644
--- a/packages/fig/src/node-change/plugin-data.ts
+++ b/packages/fig/src/node-change/plugin-data.ts
@@ -64,14 +64,23 @@ export function applyExportSettingsPluginData(
* layout path maps onto, after import-time box expansion and resize scaling).
* The Kiwi schema has no home for it, and reconstructing it from an expanded,
* resized node is ambiguous — persist it as plugin data so save/reopen keeps
- * reflow anchored correctly.
+ * reflow anchored correctly. A node still saved in its Figma box gets none: the
+ * reader rebuilds the box from that, and this one, in the expanded node's
+ * coordinates, would shift the path off the lettering a second time.
*/
-export function applyTextPathBoxPluginData(node: {
- textPathBox: Rect | null
- pluginData: PluginDataEntry[]
-}): void {
+export function applyTextPathBoxPluginData(
+ node: {
+ textPathBox: Rect | null
+ pluginData: PluginDataEntry[]
+ },
+ savedInFigmaBox: boolean
+): void {
if (!node.textPathBox) return
- node.pluginData = withPluginData(node.pluginData, textPathBox, node.textPathBox)
+ node.pluginData = withPluginData(
+ node.pluginData,
+ textPathBox,
+ savedInFigmaBox ? undefined : node.textPathBox
+ )
}
export function extractTextPathBox(nc: NodeChange): Rect | null {
diff --git a/packages/fig/src/node-change/vector/network.ts b/packages/fig/src/node-change/vector/network.ts
index 27a336c87..bececce83 100644
--- a/packages/fig/src/node-change/vector/network.ts
+++ b/packages/fig/src/node-change/vector/network.ts
@@ -21,6 +21,14 @@ export function decodeVectorNetworkBlob(
data: Uint8Array,
styleOverrideTable?: StyleOverride[]
): VectorNetwork {
+ return readVectorNetworkBlob(data, styleOverrideTable).network
+}
+
+/** The network a blob holds, with each segment's style word, which the network itself drops. */
+function readVectorNetworkBlob(
+ data: Uint8Array,
+ styleOverrideTable?: StyleOverride[]
+): { network: VectorNetwork; segmentStyles: number[] } {
const view = new DataView(data.buffer, data.byteOffset, data.byteLength)
let offset = 0
@@ -55,7 +63,9 @@ export function decodeVectorNetworkBlob(
}
const segments: VectorSegment[] = []
+ const segmentStyles: number[] = []
for (let index = 0; index < segmentCount; index++) {
+ segmentStyles.push(view.getUint32(offset, true))
offset += 4
const start = view.getUint32(offset, true)
offset += 4
@@ -99,7 +109,7 @@ export function decodeVectorNetworkBlob(
regions.push({ windingRule, loops })
}
- return { vertices, segments, regions }
+ return { network: { vertices, segments, regions }, segmentStyles }
}
function vertexStyleKey(vertex: VectorVertex): string {
@@ -206,3 +216,19 @@ export function encodeVectorNetworkBlob(
return new Uint8Array(buffer)
}
+
+/** The style word Figma writes on the one segment a text path starts on. */
+const TEXT_PATH_START_SEGMENT = 0x1ffffff
+
+/**
+ * The segment a text path starts on: Figma marks it by writing {@link TEXT_PATH_START_SEGMENT}
+ * as its style word, and `textPathStart.tValue` is the position within it. Segment 0 when none is
+ * marked, as in Figma.
+ */
+export function textPathStartSegment(blob: Uint8Array): number {
+ const { segmentStyles } = readVectorNetworkBlob(blob)
+ const index = segmentStyles.findIndex(
+ (word) => (word & TEXT_PATH_START_SEGMENT) === TEXT_PATH_START_SEGMENT
+ )
+ return Math.max(index, 0)
+}
diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.ts
index 559dbee16..6b8952642 100644
--- a/packages/scene-graph/src/types.ts
+++ b/packages/scene-graph/src/types.ts
@@ -423,8 +423,11 @@ export interface PluginRelaunchDataEntry {
export interface TextPathData {
network: VectorNetwork
normalizedSize: Vector
+ /** Where on the start segment the text starts, from 0 at its start to 1 at its end. */
tValue: number
forward: boolean
+ /** The segment the text starts on, which Figma marks in the network blob; 0 when unmarked. */
+ startSegment?: number
}
export interface DerivedTextGlyph {
diff --git a/packages/vue/src/shared/input/resize.ts b/packages/vue/src/shared/input/resize.ts
index faa8a8e0e..d3775f264 100644
--- a/packages/vue/src/shared/input/resize.ts
+++ b/packages/vue/src/shared/input/resize.ts
@@ -3,7 +3,7 @@ export { tryStartResize } from '#vue/shared/input/resize/start'
import { isEqual } from 'es-toolkit'
import { toRaw } from 'vue'
-import type { Editor } from '@open-pencil/core/editor'
+import { resizedPathTextGlyphs, type Editor } from '@open-pencil/core/editor'
import { computeAllLayouts } from '@open-pencil/core/layout'
import { calibratePathTextLayout, reflowPathTextGlyphs } from '@open-pencil/core/text'
import {
@@ -13,7 +13,12 @@ import {
recapturedAspectRatio,
recordInstanceOverride
} from '@open-pencil/scene-graph'
-import type { InstanceOverrideState, SceneNode } from '@open-pencil/scene-graph'
+import type {
+ DerivedTextGlyph,
+ InstanceOverrideState,
+ SceneNode,
+ TextPathData
+} from '@open-pencil/scene-graph'
import { copyDerivedGlyphs, copyGeometryPaths, copyStrokes } from '@open-pencil/scene-graph/copy'
import type { Rect } from '@open-pencil/scene-graph/primitives'
import {
@@ -37,28 +42,28 @@ import type { DragResize } from '#vue/shared/input/types'
*/
/**
* Figma resize semantics for imported text-on-path: constant font size,
- * glyphs re-placed along the scaled path (see core/text/path). Used
+ * text laid out again along the scaled path (resizedPathTextGlyphs). Used
* instead of geometric glyph/silhouette scaling whenever the node still has
* its layout path. Baked node-level silhouettes cannot follow re-placed
* glyphs, so strokeGeometry is cleared — the renderer rebuilds silhouettes
* per glyph — and stroke weight stays constant like the font size.
*/
function reflowedPathTextChanges(
+ node: SceneNode | undefined,
orig: Pick<ResizeSnapshot, 'textPathData' | 'textPathBox' | 'derivedTextGlyphs' | 'strokes'>,
sx: number,
sy: number
): Partial<SceneNode> | null {
if (!orig.textPathData || !orig.textPathBox || !orig.derivedTextGlyphs?.length) return null
- const data = orig.textPathData
- const layout = calibratePathTextLayout(orig.derivedTextGlyphs, data, orig.textPathBox)
- if (!layout) return null
const box = {
x: orig.textPathBox.x * sx,
y: orig.textPathBox.y * sy,
width: orig.textPathBox.width * sx,
height: orig.textPathBox.height * sy
}
- const glyphs = reflowPathTextGlyphs(orig.derivedTextGlyphs, data, layout, box)
+ const glyphs =
+ (node && resizedPathTextGlyphs(node, orig.derivedTextGlyphs, orig.textPathBox, box)) ??
+ movedPathTextGlyphs(orig.derivedTextGlyphs, orig.textPathData, orig.textPathBox, box)
if (!glyphs) return null
return {
derivedTextGlyphs: glyphs,
@@ -68,6 +73,17 @@ function reflowedPathTextChanges(
}
}
+/** Without the font, the old glyphs move along the path, keeping their spacing. */
+function movedPathTextGlyphs(
+ glyphs: DerivedTextGlyph[],
+ data: TextPathData,
+ origBox: Rect,
+ box: Rect
+): DerivedTextGlyph[] | null {
+ const layout = calibratePathTextLayout(glyphs, data, origBox)
+ return layout ? reflowPathTextGlyphs(glyphs, data, layout, box) : null
+}
+
/**
* The ratio a drag keeps, as Figma's handles keep it: a locked layer keeps its own unless Control
* frees it, and Shift keeps the ratio the drag started from.
@@ -145,7 +161,12 @@ function applyConstrainedChildren(
if (orig && orig.width > 0 && orig.height > 0) {
const width = childChanges.width ?? orig.width
const height = childChanges.height ?? orig.height
- const reflow = reflowedPathTextChanges(orig, width / orig.width, height / orig.height)
+ const reflow = reflowedPathTextChanges(
+ editor.graph.getNode(childId),
+ orig,
+ width / orig.width,
+ height / orig.height
+ )
if (reflow) Object.assign(childChanges, reflow)
}
editor.graph.updateNodePreview(childId, childChanges)
@@ -178,6 +199,7 @@ export function applyResize(
markResized(d, newRect, editor)
if (d.origRect.width > 0 && d.origRect.height > 0) {
const reflow = reflowedPathTextChanges(
+ node,
{
textPathData: d.origTextPathData,
textPathBox: d.origTextPathBox,
diff --git a/tests/e2e/canvas/text/path-visual.spec.ts b/tests/e2e/canvas/text/path-visual.spec.ts
index 846e5e487..47f92233d 100644
--- a/tests/e2e/canvas/text/path-visual.spec.ts
+++ b/tests/e2e/canvas/text/path-visual.spec.ts
@@ -26,3 +26,33 @@ test('renders imported text on a path with its selection overlay', async () => {
const buffer = await editor.canvas.screenshotCanvasRegion()
expect(buffer).toMatchSnapshot('text-path-rendering-and-selection.png')
})
+
+test('selects characters along text on a path while editing it', async () => {
+ test.setTimeout(90_000)
+ await editor.page.evaluate(() => window.openPencil?.openFile?.('/tests/fixtures/circle-text.fig'))
+ await editor.canvas.waitForRender()
+
+ const selection = await editor.page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const node = [...store.graph.getAllNodes()].find(
+ (candidate) => candidate.name === 'ArnoCoenen.art'
+ )
+ if (!node) return null
+ store.select([node.id])
+ store.zoomToSelection()
+ store.startTextEditing(node.id)
+ const text = store.textEditor
+ if (!text) return null
+ text.selectWord(0)
+ store.textSelectionChanged()
+ store.requestRender()
+ return text.getSelectionRange()
+ })
+ expect(selection).toEqual([0, 10])
+ await editor.canvas.waitForRender()
+ editor.canvas.assertNoErrors()
+
+ const buffer = await editor.canvas.screenshotCanvasRegion()
+ expect(buffer).toMatchSnapshot('text-path-editing-selection.png')
+})
diff --git a/tests/e2e/canvas/text/path-visual.spec.ts-snapshots/text-path-editing-selection-openpencil-darwin.png b/tests/e2e/canvas/text/path-visual.spec.ts-snapshots/text-path-editing-selection-openpencil-darwin.png
new file mode 100644
index 000000000..8cdaa0dd8
Binary files /dev/null and b/tests/e2e/canvas/text/path-visual.spec.ts-snapshots/text-path-editing-selection-openpencil-darwin.png differ
diff --git a/tests/e2e/canvas/text/path-visual.spec.ts-snapshots/text-path-rendering-and-selection-openpencil-darwin.png b/tests/e2e/canvas/text/path-visual.spec.ts-snapshots/text-path-rendering-and-selection-openpencil-darwin.png
index ba7bf415e..934d2f151 100644
Binary files a/tests/e2e/canvas/text/path-visual.spec.ts-snapshots/text-path-rendering-and-selection-openpencil-darwin.png and b/tests/e2e/canvas/text/path-visual.spec.ts-snapshots/text-path-rendering-and-selection-openpencil-darwin.png differ
diff --git a/tests/engine/core/editor/text/path-edit.test.ts b/tests/engine/core/editor/text/path-edit.test.ts
index dd2653eb1..e2025bc41 100644
--- a/tests/engine/core/editor/text/path-edit.test.ts
+++ b/tests/engine/core/editor/text/path-edit.test.ts
@@ -2,9 +2,10 @@ import { describe, expect, test } from 'bun:test'
import { SceneGraph } from '@open-pencil/scene-graph'
-import { pathTextEditChanges } from '#core/editor/text/path-edit'
+import { pathTextEditChanges, resizedPathTextGlyphs } from '#core/editor/text/path-edit'
import { fontManager } from '#core/text/fonts'
import { getGlyphOutlineMetricsSync } from '#core/text/opentype'
+import { nearestArcPoint, pointAtArc, sampleTextPath, textPathStartArc } from '#core/text/path'
import { expectDefined } from '#tests/helpers/assert'
@@ -194,3 +195,397 @@ describe('pathTextEditChanges — reflow on character edit', () => {
}
})
})
+
+describe('pathTextEditChanges — alignment', () => {
+ /** "OO" at 40px on a 400-long straight path, glyph 0 at x = 150, aligned as given. */
+ async function alignedText(align: 'LEFT' | 'CENTER' | 'RIGHT', forward = true) {
+ const font = await fontManager.fetchBundledFont('/Inter-Regular.ttf')
+ if (!font) throw new Error('missing bundled font')
+ fontManager.markLoaded('Inter', 'Regular', font)
+ const graph = new SceneGraph()
+ const page = expectDefined(graph.getPages()[0])
+ const node = graph.createNode('TEXT', page.id, {
+ width: 400,
+ height: 100,
+ text: 'OO',
+ fontFamily: 'Inter',
+ fontWeight: 400,
+ italic: false,
+ fontSize: 40,
+ textAlignHorizontal: align,
+ textPathBox: { x: 0, y: 0, width: 400, height: 100 },
+ derivedTextGlyphs: [
+ { commandsBlob: new Uint8Array(4), x: 150, y: 50, fontSize: 40, rotation: 0 },
+ {
+ commandsBlob: new Uint8Array(4),
+ x: forward ? 177 : 123,
+ y: 50,
+ fontSize: 40,
+ rotation: 0
+ }
+ ]
+ })
+ node.textPathData = {
+ network: straightLineNetwork(),
+ normalizedSize: { x: 400, y: 100 },
+ tValue: 0,
+ forward
+ }
+ return node
+ }
+
+ /**
+ * Where "OOOO"'s first glyph lands, and where the path puts a point `steps` glyph advances
+ * past "OO"'s, one advance being the distance between two of the new glyphs. Two more of the
+ * same glyph make the run two advances wider.
+ */
+ function firstGlyph(node: Awaited<ReturnType<typeof alignedText>>, steps: number) {
+ const glyphs = expectDefined(pathTextEditChanges(node, { text: 'OOOO' }).derivedTextGlyphs)
+ const path = expectDefined(
+ sampleTextPath(expectDefined(node.textPathData), expectDefined(node.textPathBox))
+ )
+ const [first, second] = glyphs
+ const advance = Math.abs(expectDefined(second).x - expectDefined(first).x)
+ const start = nearestArcPoint(path, 150, 50).s
+ return { x: expectDefined(first).x, expected: pointAtArc(path, start + steps * advance).x }
+ }
+
+ test('left-aligned text keeps its start', async () => {
+ const { x, expected } = firstGlyph(await alignedText('LEFT'), 0)
+ expect(x).toBeCloseTo(expected, 3)
+ })
+
+ test('centered text keeps its middle, growing both ways', async () => {
+ const { x, expected } = firstGlyph(await alignedText('CENTER'), -1)
+ expect(x).toBeCloseTo(expected, 3)
+ expect(x).toBeLessThan(140)
+ })
+
+ test('right-aligned text keeps its end', async () => {
+ const { x, expected } = firstGlyph(await alignedText('RIGHT'), -2)
+ expect(x).toBeCloseTo(expected, 3)
+ })
+
+ test('text running backwards along the path shifts the other way', async () => {
+ const { x, expected } = firstGlyph(await alignedText('RIGHT', false), 2)
+ expect(x).toBeCloseTo(expected, 3)
+ expect(x).toBeGreaterThan(170)
+ })
+})
+
+describe('aligned path text is laid out from the text path start, as in Figma', () => {
+ /** A straight 400-wide line in two segments; the text starts halfway along the second. */
+ function startedOnSecondSegment(
+ align: 'LEFT' | 'CENTER' | 'RIGHT' | 'JUSTIFIED',
+ forward = true
+ ) {
+ const graph = new SceneGraph()
+ const page = expectDefined(graph.getPages()[0])
+ const box = { x: 0, y: 0, width: 400, height: 100 }
+ const node = graph.createNode('TEXT', page.id, {
+ width: 400,
+ height: 100,
+ text: 'AB',
+ fontFamily: 'Inter',
+ fontWeight: 400,
+ italic: false,
+ fontSize: 40,
+ textAlignHorizontal: align,
+ textPathBox: { ...box },
+ derivedTextGlyphs: [
+ { commandsBlob: new Uint8Array(4), x: 10, y: 50, fontSize: 40, rotation: 0 },
+ { commandsBlob: new Uint8Array(4), x: 40, y: 50, fontSize: 40, rotation: 0 }
+ ]
+ })
+ const zero = { x: 0, y: 0 }
+ node.textPathData = {
+ network: {
+ vertices: [
+ { x: 0, y: 50 },
+ { x: 200, y: 50 },
+ { x: 400, y: 50 }
+ ],
+ segments: [
+ { start: 0, end: 1, tangentStart: zero, tangentEnd: zero },
+ { start: 1, end: 2, tangentStart: zero, tangentEnd: zero }
+ ],
+ regions: []
+ },
+ normalizedSize: { x: 400, y: 100 },
+ tValue: 0.5,
+ forward,
+ startSegment: 1
+ }
+ return node
+ }
+
+ async function edited(align: 'LEFT' | 'CENTER' | 'RIGHT' | 'JUSTIFIED', forward = true) {
+ const font = await fontManager.fetchBundledFont('/Inter-Regular.ttf')
+ if (!font) throw new Error('bundled font missing')
+ fontManager.markLoaded('Inter', 'Regular', font)
+ const text = 'Hello'
+ const width = expectDefined(getGlyphOutlineMetricsSync('Inter', 'Regular', text, 40)).reduce(
+ (sum, glyph) => sum + glyph.advance,
+ 0
+ )
+ const changes = pathTextEditChanges(startedOnSecondSegment(align, forward), { text })
+ const glyphs = expectDefined(changes.derivedTextGlyphs, 'reflowed glyphs')
+ return { first: glyphs[0].x, width }
+ }
+
+ // The start is halfway along the second segment: x = 300. Arc sampling of a straight cubic is
+ // within about 0.35 px, so positions are compared to the nearest pixel.
+ test('left-aligned text starts at it', async () => {
+ expect((await edited('LEFT')).first).toBeCloseTo(300, 0)
+ })
+
+ test('centered text is centered on it', async () => {
+ const { first, width } = await edited('CENTER')
+ expect(first).toBeCloseTo(300 - width / 2, 0)
+ })
+
+ test('right-aligned text ends at it', async () => {
+ const { first, width } = await edited('RIGHT')
+ expect(first).toBeCloseTo(300 - width, 0)
+ })
+
+ test('text running backwards is centered on it from the other side', async () => {
+ const { first, width } = await edited('CENTER', false)
+ expect(first).toBeCloseTo(300 + width / 2, 0)
+ })
+
+ test('justified text on an open path starts at the path’s start', async () => {
+ expect((await edited('JUSTIFIED')).first).toBeCloseTo(0, 0)
+ })
+
+ test('a new alignment in the same update lays the text out with it', async () => {
+ const { width } = await edited('RIGHT')
+ const node = startedOnSecondSegment('LEFT')
+ const changes = pathTextEditChanges(node, { text: 'Hello', textAlignHorizontal: 'RIGHT' })
+ expect(expectDefined(changes.derivedTextGlyphs)[0].x).toBeCloseTo(300 - width, 0)
+ })
+
+ test('changing only the alignment lays the text out again', async () => {
+ await edited('LEFT')
+ const width = expectDefined(getGlyphOutlineMetricsSync('Inter', 'Regular', 'AB', 40)).reduce(
+ (sum, glyph) => sum + glyph.advance,
+ 0
+ )
+ const changes = pathTextEditChanges(startedOnSecondSegment('LEFT'), {
+ textAlignHorizontal: 'CENTER'
+ })
+ expect(expectDefined(changes.derivedTextGlyphs)[0].x).toBeCloseTo(300 - width / 2, 0)
+ })
+})
+
+describe('path text that overflows its alignment’s part of the path, as in Figma', () => {
+ const text = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+
+ /** A straight 400-wide line in two segments; the text starts at x = 300. */
+ async function overflowing(align: 'LEFT' | 'CENTER' | 'RIGHT', tValue = 0.5) {
+ const font = await fontManager.fetchBundledFont('/Inter-Regular.ttf')
+ if (!font) throw new Error('bundled font missing')
+ fontManager.markLoaded('Inter', 'Regular', font)
+ const graph = new SceneGraph()
+ const page = expectDefined(graph.getPages()[0])
+ const node = graph.createNode('TEXT', page.id, {
+ width: 400,
+ height: 100,
+ text: 'AB',
+ fontFamily: 'Inter',
+ fontWeight: 400,
+ italic: false,
+ fontSize: 40,
+ textAlignHorizontal: align,
+ textPathBox: { x: 0, y: 0, width: 400, height: 100 },
+ derivedTextGlyphs: [
+ { commandsBlob: new Uint8Array(4), x: 10, y: 50, fontSize: 40, rotation: 0 },
+ { commandsBlob: new Uint8Array(4), x: 40, y: 50, fontSize: 40, rotation: 0 }
+ ]
+ })
+ const zero = { x: 0, y: 0 }
+ node.textPathData = {
+ network: {
+ vertices: [
+ { x: 0, y: 50 },
+ { x: 200, y: 50 },
+ { x: 400, y: 50 }
+ ],
+ segments: [
+ { start: 0, end: 1, tangentStart: zero, tangentEnd: zero },
+ { start: 1, end: 2, tangentStart: zero, tangentEnd: zero }
+ ],
+ regions: []
+ },
+ normalizedSize: { x: 400, y: 100 },
+ tValue,
+ forward: true,
+ startSegment: 1
+ }
+ const metrics = expectDefined(getGlyphOutlineMetricsSync('Inter', 'Regular', text, 40))
+ const glyphs = expectDefined(pathTextEditChanges(node, { text }).derivedTextGlyphs)
+ const kept = metrics.slice(0, glyphs.length)
+ const width = kept.reduce((sum, glyph) => sum + glyph.advance, 0)
+ const next = metrics.at(glyphs.length)?.advance ?? 0
+ return { glyphs, width, next, first: expectDefined(glyphs[0]).x }
+ }
+
+ // Each run keeps the leading glyphs that fit its part of the path and is aligned within it, so
+ // one more glyph would not fit. Positions are compared to the nearest pixel, as above.
+ test('left-aligned text keeps what fits between the start and the path’s end', async () => {
+ const { glyphs, width, next, first } = await overflowing('LEFT')
+ expect(glyphs.length).toBeLessThan(text.length)
+ expect(first).toBeCloseTo(300, 0)
+ expect(width).toBeLessThanOrEqual(100 + 0.5)
+ expect(width + next).toBeGreaterThan(100)
+ })
+
+ test('right-aligned text keeps what fits before the start and ends at it', async () => {
+ const { glyphs, width, next, first } = await overflowing('RIGHT')
+ expect(glyphs.length).toBeLessThan(text.length)
+ expect(first).toBeCloseTo(300 - width, 0)
+ expect(width + next).toBeGreaterThan(300)
+ })
+
+ test('centered text keeps what fits the widest span centered on the start', async () => {
+ // The start is 100 px from the end, so the span is x = 200…400.
+ const { glyphs, width, next, first } = await overflowing('CENTER')
+ expect(glyphs.length).toBeLessThan(text.length)
+ expect(first).toBeCloseTo(300 - width / 2, 0)
+ expect(width + next).toBeGreaterThan(200)
+ })
+
+ test('a lone first glyph stays even with no room, from where its part starts', async () => {
+ // At the path's end, centered text has no room either side.
+ const { glyphs, first } = await overflowing('CENTER', 1)
+ expect(glyphs.length).toBe(1)
+ expect(first).toBeCloseTo(400, 0)
+ })
+})
+
+test('overflowing text on a closed path keeps what fits one loop', async () => {
+ const font = await fontManager.fetchBundledFont('/Inter-Regular.ttf')
+ if (!font) throw new Error('bundled font missing')
+ fontManager.markLoaded('Inter', 'Regular', font)
+ const graph = new SceneGraph()
+ const page = expectDefined(graph.getPages()[0])
+ const node = graph.createNode('TEXT', page.id, {
+ width: 100,
+ height: 100,
+ text: 'AB',
+ fontFamily: 'Inter',
+ fontWeight: 400,
+ italic: false,
+ fontSize: 40,
+ textAlignHorizontal: 'CENTER',
+ textPathBox: { x: 0, y: 0, width: 100, height: 100 },
+ derivedTextGlyphs: [
+ { commandsBlob: new Uint8Array(4), x: 50, y: 0, fontSize: 40, rotation: 0 },
+ { commandsBlob: new Uint8Array(4), x: 80, y: 0, fontSize: 40, rotation: 0 }
+ ]
+ })
+ const zero = { x: 0, y: 0 }
+ const corners = [
+ { x: 0, y: 0 },
+ { x: 100, y: 0 },
+ { x: 100, y: 100 },
+ { x: 0, y: 100 }
+ ]
+ node.textPathData = {
+ network: {
+ vertices: corners,
+ segments: corners.map((_, index) => ({
+ start: index,
+ end: (index + 1) % corners.length,
+ tangentStart: zero,
+ tangentEnd: zero
+ })),
+ regions: []
+ },
+ normalizedSize: { x: 100, y: 100 },
+ tValue: 0.5,
+ forward: true,
+ startSegment: 0
+ }
+ const text = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+ const metrics = expectDefined(getGlyphOutlineMetricsSync('Inter', 'Regular', text, 40))
+ const glyphs = expectDefined(pathTextEditChanges(node, { text }).derivedTextGlyphs)
+ const width = metrics.slice(0, glyphs.length).reduce((sum, glyph) => sum + glyph.advance, 0)
+ const next = expectDefined(metrics.at(glyphs.length)).advance
+ // The loop is 400 long; the kept run is centered on the start at (50, 0) and doesn't lap.
+ expect(width).toBeLessThanOrEqual(400 + 0.5)
+ expect(width + next).toBeGreaterThan(400)
+ const path = expectDefined(
+ sampleTextPath(expectDefined(node.textPathData), expectDefined(node.textPathBox))
+ )
+ const firstArc = nearestArcPoint(path, glyphs[0].x, glyphs[0].y).s
+ expect(firstArc).toBeCloseTo((50 - width / 2 + 400) % 400, 0)
+})
+
+// A 100 × 100 square path in a Figma file, text starting halfway along its top side. Resizing
+// moved old glyphs by their distance along the path, which put letters near the corners on the
+// wrong side and scrambled the run once the sides changed length.
+describe('resizedPathTextGlyphs — resize lays the text out again', () => {
+ test('a squashed or stretched square keeps every letter on the path, in order', async () => {
+ const font = await fontManager.fetchBundledFont('/Inter-Regular.ttf')
+ if (!font) throw new Error('expected the bundled Inter font')
+ fontManager.markLoaded('Inter', 'Regular', font)
+
+ const corner = (x: number, y: number) => ({ x, y })
+ const side = (start: number, end: number) => ({
+ start,
+ end,
+ tangentStart: corner(0, 0),
+ tangentEnd: corner(0, 0)
+ })
+ const box = { x: 0, y: 0, width: 100, height: 100 }
+ const text = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+ const graph = new SceneGraph()
+ const node = graph.createNode('TEXT', expectDefined(graph.getPages()[0]).id, {
+ width: 100,
+ height: 100,
+ text,
+ fontFamily: 'Inter',
+ fontWeight: 400,
+ italic: false,
+ fontSize: 18,
+ textPathBox: { ...box },
+ derivedTextGlyphs: [
+ { commandsBlob: new Uint8Array(4), x: 50, y: 0, fontSize: 18, rotation: 0 }
+ ]
+ })
+ node.textPathData = {
+ network: {
+ vertices: [corner(0, 0), corner(100, 0), corner(100, 100), corner(0, 100)],
+ segments: [side(0, 1), side(1, 2), side(2, 3), side(3, 0)],
+ regions: []
+ },
+ normalizedSize: { x: 100, y: 100 },
+ tValue: 0.5,
+ forward: true,
+ startSegment: 0
+ }
+ const laidOut = expectDefined(pathTextEditChanges(node, { text }).derivedTextGlyphs)
+ node.derivedTextGlyphs = laidOut
+
+ for (const size of [
+ { width: 273, height: 126 },
+ { width: 167, height: 126 },
+ { width: 60, height: 300 }
+ ]) {
+ const resized = { x: 0, y: 0, ...size }
+ const glyphs = expectDefined(resizedPathTextGlyphs(node, laidOut, box, resized))
+ const path = expectDefined(sampleTextPath(node.textPathData, resized))
+ const start = textPathStartArc(node.textPathData, path)
+ let previous = -1
+ for (const glyph of glyphs) {
+ const point = nearestArcPoint(path, glyph.x, glyph.y)
+ expect(Math.hypot(point.x - glyph.x, point.y - glyph.y)).toBeLessThan(0.01)
+ const along = (point.s - start + path.length) % path.length
+ expect(along).toBeGreaterThan(previous)
+ previous = along
+ }
+ expect(glyphs.length).toBeGreaterThan(0)
+ }
+ })
+})
diff --git a/tests/engine/core/text/path-layout.test.ts b/tests/engine/core/text/path-layout.test.ts
index 2ae1bbf23..7c58cbc97 100644
--- a/tests/engine/core/text/path-layout.test.ts
+++ b/tests/engine/core/text/path-layout.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, test } from 'bun:test'
import { SceneGraph } from '@open-pencil/scene-graph'
-import type { SceneNode, VectorNetwork } from '@open-pencil/scene-graph'
+import type { SceneNode, TextPathData, VectorNetwork } from '@open-pencil/scene-graph'
import type { Vector } from '@open-pencil/scene-graph/primitives'
import {
@@ -9,10 +9,10 @@ import {
fitTextPathBoxToGlyphs,
getTextPathData,
layoutPathTextFromAdvances,
- pathTextSelectionBand,
pointAtArc,
reflowPathTextGlyphs,
- sampleTextPath
+ sampleTextPath,
+ textPathStartArc
} from '#core/text/path'
import { expectDefined } from '#tests/helpers/assert'
@@ -123,12 +123,10 @@ describe('path-text reflow — real fixture (optional local)', () => {
const path = expectDefined(sampleTextPath(data, fitted), 'fitted overlay path')
expect(maxGlyphToPath(path, glyphs)).toBeLessThan(12)
- // Start marker (overlay uses pointAtArc at tValue * length) lands on the
- // fitted curve near the first glyph.
- const start = pointAtArc(path, Math.min(Math.max(data.tValue, 0), 1) * path.length)
- expect(Math.hypot(start.x - glyphs[0].x, start.y - glyphs[0].y)).toBeLessThan(
- glyphs[0].fontSize
- )
+ // The start marker sits on the segment Figma marks, near arc 595 of 1540, not at
+ // tValue × length (845.7), where this centered run's first glyph happens to be.
+ expect(data.startSegment).toBe(1)
+ expect(textPathStartArc(data, rawPath)).toBeCloseTo(595, 0)
})
test('fitTextPathBoxToGlyphs returns null with no glyphs to fit', async () => {
@@ -306,6 +304,33 @@ describe('selection overlay — path helpers', () => {
expect(Math.hypot(mid.x - start.x, mid.y - start.y)).toBeGreaterThan(1)
})
+ test('the start marker sits on the marked start segment, or at tValue along an unmarked path', () => {
+ const zero = { x: 0, y: 0 }
+ const data: TextPathData = {
+ network: {
+ vertices: [
+ { x: 0, y: 50 },
+ { x: 200, y: 50 },
+ { x: 400, y: 50 }
+ ],
+ segments: [
+ { start: 0, end: 1, tangentStart: zero, tangentEnd: zero },
+ { start: 1, end: 2, tangentStart: zero, tangentEnd: zero }
+ ],
+ regions: []
+ },
+ normalizedSize: { x: 400, y: 100 },
+ tValue: 0.5,
+ forward: true,
+ startSegment: 1
+ }
+ const box = { x: 0, y: 0, width: 400, height: 100 }
+ const path = expectDefined(sampleTextPath(data, box), 'path')
+
+ expect(textPathStartArc(data, path)).toBeCloseTo(300, 0)
+ expect(textPathStartArc({ ...data, startSegment: undefined }, path)).toBeCloseTo(200, 0)
+ })
+
test('eligible node samples the curve (not a rectangle); dataless node falls back', () => {
const node = makeCircleTextPathNode()
// Overlay eligibility seam: retained data + a node-local box are both present.
@@ -338,38 +363,6 @@ describe('selection overlay — path helpers', () => {
})
expect(getTextPathData(bare)).toBeNull()
})
-
- test('selection band hugs a glyph run that straddles the path seam', () => {
- const node = makeCircleTextPathNode()
- const data = expectDefined(getTextPathData(node), 'data')
- const box = expectDefined(node.textPathBox, 'box')
-
- // Seam s=0 sits at 3 o'clock (228,128). A run at angles −30°..+30° straddles
- // it: min/max arc-length would trace the whole opposite (empty) arc, so the
- // band must instead hug this right-side cluster.
- const glyphs = [-30, -20, -10, 10, 20, 30].map((deg) => {
- const a = (deg * Math.PI) / 180
- return { x: 128 + 100 * Math.cos(a), y: 128 + 100 * Math.sin(a), fontSize: 40, rotation: 0 }
- })
-
- const poly = expectDefined(pathTextSelectionBand(data, box, glyphs), 'band')
- expect(poly.length).toBeGreaterThanOrEqual(6)
-
- // Centroid on the glyph side (right of centre); the old complement arc gave
- // a centroid near 9 o'clock (x < 128).
- let bx = 0
- for (let i = 0; i < poly.length; i += 2) bx += poly[i]
- bx /= poly.length / 2
- expect(bx).toBeGreaterThan(140)
-
- // Every band vertex hugs some glyph; the complement arc would sit ~2·radius
- // (~200px) away.
- for (let i = 0; i < poly.length; i += 2) {
- let best = Infinity
- for (const g of glyphs) best = Math.min(best, Math.hypot(poly[i] - g.x, poly[i + 1] - g.y))
- expect(best).toBeLessThan(60)
- }
- })
})
describe('pen-walked glyph rotation', () => {
diff --git a/tests/engine/io/fig/import/text-path.test.ts b/tests/engine/io/fig/import/text-path.test.ts
index 7f66fe565..c6dcc6e28 100644
--- a/tests/engine/io/fig/import/text-path.test.ts
+++ b/tests/engine/io/fig/import/text-path.test.ts
@@ -6,6 +6,7 @@ import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import { SceneGraph } from '@open-pencil/scene-graph'
import type { Vector } from '@open-pencil/scene-graph/primitives'
+import { importClipboardNodes } from '#core/clipboard'
import { exportFigFile } from '#core/io/formats/fig/export'
import { encodeVectorNetworkBlob } from '#core/vector'
@@ -261,6 +262,67 @@ describe('TEXT_PATH raw payload round-trip (synthetic)', () => {
})
})
+describe('TEXT_PATH save and reopen', () => {
+ // Figma places a 100 × 100 square path in the layer's own box and sets the baselines on it.
+ // The lettering sticks out above the box, so import grows the layer and moves the path down
+ // to keep it under the letters; saving and reopening must not move it a second time.
+ test('an untouched pasted layer keeps its path under the lettering', async () => {
+ const corner = (x: number, y: number) => ({ x, y })
+ const side = (start: number, end: number) => ({
+ start,
+ end,
+ tangentStart: corner(0, 0),
+ tangentEnd: corner(0, 0)
+ })
+ const networkBlob = encodeVectorNetworkBlob({
+ vertices: [corner(0, 0), corner(100, 0), corner(100, 100), corner(0, 100)],
+ segments: [side(0, 1), side(1, 2), side(2, 3), side(3, 0)],
+ regions: []
+ })
+ const glyph = (x: number, firstCharacter: number) => ({
+ position: { x, y: 0 },
+ fontSize: 18,
+ firstCharacter,
+ advance: 0.6,
+ rotation: 0,
+ commandsBlob: 1
+ })
+ const record: NodeChange = {
+ guid: { sessionID: 1, localID: 2 },
+ phase: 'CREATED',
+ type: 'TEXT_PATH',
+ name: 'Around the square',
+ fontSize: 18,
+ textData: { characters: 'AB' },
+ size: { x: 100, y: 100 },
+ transform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 },
+ vectorData: { vectorNetworkBlob: 0, normalizedSize: { x: 100, y: 100 } },
+ textPathStart: { tValue: 0.5, forward: true },
+ derivedTextData: { glyphs: [glyph(50, 0), glyph(61, 1)] }
+ }
+ const pasted = new SceneGraph()
+ const [id] = importClipboardNodes([record], pasted, pasted.getPages()[0].id, 0, 0, [
+ networkBlob,
+ unitSquareBlob()
+ ])
+ const box = expectDefined(pasted.getNode(id)?.textPathBox, 'pasted path box')
+ expect(box.y).toBeGreaterThan(0)
+
+ const reparsed = reparse(await exportFigFile(pasted))
+ const reopened = new SceneGraph()
+ const saved = reparsed.nodeChanges.filter((nc) => nc.type === 'TEXT_PATH')
+ const [reopenedId] = importClipboardNodes(
+ saved,
+ reopened,
+ reopened.getPages()[0].id,
+ 0,
+ 0,
+ reparsed.blobs
+ )
+ expect(reopened.getNode(reopenedId)?.textPathBox).toEqual(box)
+ })
+})
+
describe('TEXT_PATH edit invalidation', () => {
test('clears format-neutral path data when text content is edited', () => {
const graph = new SceneGraph()
diff --git a/tests/engine/vector/blob/roundtrip.test.ts b/tests/engine/vector/blob/roundtrip.test.ts
index 707a9c26d..5d9ed7f87 100644
--- a/tests/engine/vector/blob/roundtrip.test.ts
+++ b/tests/engine/vector/blob/roundtrip.test.ts
@@ -6,6 +6,7 @@ import {
decodeVectorNetworkBlob,
type VectorNetwork
} from '@open-pencil/core'
+import { textPathStartSegment } from '@open-pencil/fig/node-change'
import {
lineNetwork,
@@ -183,3 +184,21 @@ describe('region style words', () => {
expect(decodeVectorNetworkBlob(regionBlob((3 << 1) | 1)).regions[0].windingRule).toBe('NONZERO')
})
})
+
+describe('the text path start segment', () => {
+ test('is the segment Figma marks with style word 0x1ffffff, else the first', () => {
+ const network = vectorNetwork(
+ [vectorVertex(0, 0), vectorVertex(100, 0), vectorVertex(100, 100)],
+ [vectorSegment(0, 1), vectorSegment(1, 2)]
+ )
+ const blob = encodeVectorNetworkBlob(network)
+ expect(textPathStartSegment(blob)).toBe(0)
+ // Header 12 bytes and three 12-byte vertices come before the 28-byte segments.
+ new DataView(blob.buffer).setUint32(12 + 3 * 12 + 28, 0x1ffffff, true)
+ expect(textPathStartSegment(blob)).toBe(1)
+ // The marker is a style word, so the network itself decodes unchanged.
+ expect(decodeVectorNetworkBlob(blob)).toEqual(
+ decodeVectorNetworkBlob(encodeVectorNetworkBlob(network))
+ )
+ })
+})
diff --git a/tests/engine/vue/input/resize/path-text/reflow.test.ts b/tests/engine/vue/input/resize/path-text/reflow.test.ts
index 9087fe80d..0f3bad3d5 100644
--- a/tests/engine/vue/input/resize/path-text/reflow.test.ts
+++ b/tests/engine/vue/input/resize/path-text/reflow.test.ts
@@ -107,6 +107,7 @@ describe('group resize reflows path text instead of squashing it', () => {
width: 256,
height: 256,
text: 'abc',
+ fontSize: 40,
fills: [BLACK],
strokes: [WHITE_STROKE],
strokeGeometry: [{ windingRule: 'NONZERO', commandsBlob: squareGeometryBlob(256) }],
@@ -226,6 +227,7 @@ describe('direct (non-group) resize reflows path text instead of squashing it',
width: 256,
height: 256,
text: 'abc',
+ fontSize: 40,
fills: [BLACK],
strokes: [WHITE_STROKE],
strokeGeometry: [{ windingRule: 'NONZERO', commandsBlob: squareGeometryBlob(256) }],
@@ -331,6 +333,7 @@ describe('resize + export integration: real commit path clears stale raw payload
width: 256,
height: 256,
text: 'abc',
+ fontSize: 40,
fills: [BLACK],
strokes: [WHITE_STROKE],
strokeGeometry: [{ windingRule: 'NONZERO', commandsBlob: squareGeometryBlob(256) }],