AI-native design editor. Open-source Figma alternative.
feat(fig): support text on path
rcoenenbe272dc4dc20
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 01efbc54e..4c871af44 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,8 @@### Added+- Import, render, edit, resize, select, and export Figma text-on-path layers while preserving their curved glyph layout.+- Add tested pane-registry and recursive split-tree models for independently viewed same-document canvases, capped at four visible panes.- Add explicit shared/view editor-state ownership and canvas render-state hooks as a foundation for independent same-document canvas panes.diff --git a/bun.lock b/bun.lockindex 8853e684c..91e9da7bc 100644--- a/bun.lock+++ b/bun.lock@@ -185,6 +185,7 @@"opentype.js": "^2.0.0","pptxgenjs": "^4.0.1","sucrase": "^3.35.1",+ "svg-path-properties": "^2.0.2","svg2pdf.js": "^2.7.0","svgpath": "^2.6.0","twirlwind": "^0.3.0",@@ -3381,6 +3382,8 @@"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-nXK4Wx28H0KtOktanm5nsphl1KMEoLNMelAT/776qxPAj9DshwYcqgdpKuBnY1nrcYOriQFHVQLE4tIag+aDJA=="],diff --git a/packages/core/package.json b/packages/core/package.jsonindex 3093ffc0b..5f02d41bd 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -197,6 +197,7 @@"opentype.js": "^2.0.0","pptxgenjs": "^4.0.1","sucrase": "^3.35.1",+ "svg-path-properties": "^2.0.2","svg2pdf.js": "^2.7.0","svgpath": "^2.6.0","twirlwind": "^0.3.0",diff --git a/packages/core/src/canvas/overlays/selection.ts b/packages/core/src/canvas/overlays/selection.tsindex 69579a4c9..3d6031e6c 100644--- a/packages/core/src/canvas/overlays/selection.ts+++ b/packages/core/src/canvas/overlays/selection.ts@@ -8,6 +8,13 @@ import type { Vector } from '@open-pencil/scene-graph/primitives'import type { RenderOverlays, SkiaRenderer } from '#core/canvas/renderer'import { HANDLE_HALF_SIZE, SELECTION_DASH_ALPHA } from '#core/constants'+import {+ fitTextPathBoxToGlyphs,+ getTextPathData,+ pathTextSelectionBand,+ pointAtArc,+ sampleTextPath+} from '#core/text/path'function getNodeTransformChain(graph: SceneGraph, node: SceneNode): SceneNode[] {const chain: SceneNode[] = []@@ -86,6 +93,45 @@ export function drawEnteredContainer(r.auxStroke.setPathEffect(null)}+/** Single-node selection overlay: path-text curve/band for imported TEXT_PATH,+ * the standard rect+handles otherwise. */+function drawSingleSelection(+ r: SkiaRenderer,+ canvas: Canvas,+ graph: SceneGraph,+ id: string,+ selectedIds: Set<string>,+ overlays: RenderOverlays+): void {+ const node = graph.getNode(id)+ if (!node) return++ // Imported text-on-path node → path curve overlay. The cheap two-field check+ // is the gate; drawTextPathSelection re-checks the retained data and falls+ // back to the plain rectangle if it can't be sampled.+ 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.+ if (editing && !isPathText) return++ const useComponentColor = r.isComponentType(node.type)+ r.selectionPaint.setColor(useComponentColor ? r.compColor() : r.selColor())+ r.selectionPaint.setStrokeWidth(1 / r.zoom)++ const rotation =+ overlays.rotationPreview?.nodeId === id ? overlays.rotationPreview.angle : node.rotation+ if (isPathText) {+ drawTextPathSelection(r, canvas, node, rotation, graph)+ if (!editing) r.drawSelectionLabels(canvas, graph, selectedIds, overlays)+ } else {+ r.drawNodeSelection(canvas, node, rotation, graph)+ r.drawSelectionLabels(canvas, graph, selectedIds, overlays)+ }+ r.selectionPaint.setColor(r.selColor())+}+export function drawSelection(r: SkiaRenderer,canvas: Canvas,@@ -100,21 +146,7 @@ export function drawSelection(if (selectedIds.size === 1) {const id = [...selectedIds][0]- if (overlays.editingTextId === id) return- if (nodeEditId === id) return- const node = graph.getNode(id)- if (!node) return-- const useComponentColor = r.isComponentType(node.type)- r.selectionPaint.setColor(useComponentColor ? r.compColor() : r.selColor())- r.selectionPaint.setStrokeWidth(1 / r.zoom)-- const rotation =- overlays.rotationPreview?.nodeId === id ? overlays.rotationPreview.angle : node.rotation- r.drawNodeSelection(canvas, node, rotation, graph)- r.drawSelectionLabels(canvas, graph, selectedIds, overlays)-- r.selectionPaint.setColor(r.selColor())+ if (nodeEditId !== id) drawSingleSelection(r, canvas, graph, id, selectedIds, overlays)return}@@ -163,6 +195,94 @@ function withNodeBounds(canvas.restore()}+/**+ * Text-on-path selection overlay: the sampled path curve the lettering+ * 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.+ */+function drawTextPathSelection(+ r: SkiaRenderer,+ canvas: Canvas,+ node: SceneNode,+ rotation: number,+ graph: SceneGraph+): void {+ const data = getTextPathData(node)+ // Prefer the box fit to the glyph baselines; fall back to textPathBox when+ // there are no glyphs to fit against.+ const box =+ (data &&+ node.textPathBox &&+ fitTextPathBoxToGlyphs(data, node.textPathBox, node.derivedTextGlyphs)) ??+ node.textPathBox+ // Eligibility gated data/box, but sampleTextPath can still fail (bad vertex /+ // zero length) — any null falls back to the standard rectangle, no throw.+ const sampled = data && box ? sampleTextPath(data, box) : null+ if (!data || !box || !sampled) {+ r.drawNodeSelection(canvas, node, rotation, graph)+ return+ }++ withNodeBounds(r, canvas, node, 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.Path()+ band.moveTo(bandPoly[0], bandPoly[1])+ for (let i = 2; i < bandPoly.length; i += 2) band.lineTo(bandPoly[i], bandPoly[i + 1])+ band.close()+ r.auxFill.setColor(r.selColor(0.16))+ canvas.drawPath(band, r.auxFill)+ r.auxStroke.setStrokeWidth(1 / r.zoom)+ r.auxStroke.setColor(r.selColor())+ r.auxStroke.setPathEffect(null)+ canvas.drawPath(band, r.auxStroke)+ band.delete()+ }++ // Faint dashed bounds + resize/rotate handles from the fitted path box.+ r.auxStroke.setStrokeWidth(1 / r.zoom)+ r.auxStroke.setColor(r.selColor(SELECTION_DASH_ALPHA))+ // MakeDash allocates a WASM PathEffect the JS GC won't reclaim; this runs+ // every repaint while a TEXT_PATH node is selected, so free it explicitly.+ const dash = r.ck.PathEffect.MakeDash([4 / r.zoom, 4 / r.zoom], 0)+ r.auxStroke.setPathEffect(dash)+ canvas.drawRect(r.ck.LTRBRect(box.x, box.y, box.x + box.width, box.y + box.height), r.auxStroke)+ r.auxStroke.setPathEffect(null) // auxStroke is shared — never leave a dash effect on it.+ dash.delete()+ drawBoundsHandles(r, canvas, box.x, box.y, box.x + box.width, box.y + box.height)++ // The path curve itself, sampled from the headless path metrics only for drawing.+ const path = new r.ck.Path()+ const overlaySteps = Math.max(64, Math.min(1024, Math.ceil(sampled.length)))+ const first = pointAtArc(sampled, 0)+ path.moveTo(first.x, first.y)+ for (let index = 1; index <= overlaySteps; index++) {+ const point = pointAtArc(sampled, (sampled.length * index) / overlaySteps)+ path.lineTo(point.x, point.y)+ }+ if (sampled.closed) path.close()+ canvas.drawPath(path, r.selectionPaint)+ path.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)++ // Start-point marker on the curve at textPathStart.tValue (arc fraction).+ // 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)+ drawHandle(r, canvas, start.x, start.y)+ })+}+function drawBoundsHandles(r: SkiaRenderer,canvas: Canvas,diff --git a/packages/core/src/canvas/overlays/text-edit.ts b/packages/core/src/canvas/overlays/text-edit.tsindex 3a468e1be..8c968cc9c 100644--- a/packages/core/src/canvas/overlays/text-edit.ts+++ b/packages/core/src/canvas/overlays/text-edit.ts@@ -12,6 +12,16 @@ export function drawTextEditOverlay(node: SceneNode,editor: TextEditor): void {+ // Path text lays the paragraph out flat and then maps each glyph onto the+ // path. The flat caret / selection rects are in that flat space, so painting+ // them drops axis-aligned boxes over the artwork that have nothing to do with+ // the on-path glyphs. Draw an on-path caret instead (the curved selection band+ // + path stay visible via drawSelection).+ if (node.textPathData !== null) {+ drawPathTextCaret(r, canvas, node, editor)+ return+ }+r.auxStroke.setStrokeWidth(1 / r.zoom)r.auxStroke.setColor(r.selColor())r.auxStroke.setPathEffect(null)@@ -46,3 +56,31 @@ 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`.+ */+function drawPathTextCaret(+ r: SkiaRenderer,+ canvas: Canvas,+ node: SceneNode,+ editor: TextEditor+): void {+ 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())+ r.auxStroke.setPathEffect(null)+ canvas.drawLine(g.x, g.y, g.x + ux * fontSize * 0.72, g.y + uy * fontSize * 0.72, r.auxStroke)+}diff --git a/packages/core/src/canvas/renderer.ts b/packages/core/src/canvas/renderer.tsindex 1f855905e..991f104c4 100644--- a/packages/core/src/canvas/renderer.ts+++ b/packages/core/src/canvas/renderer.ts@@ -98,6 +98,8 @@ export class SkiaRenderer {vectorStrokeOutlineCache = new Map<string, Path[]>()fillGeometryCache = new Map<string, Path[]>()strokeGeometryCache = new Map<string, Path[]>()+ /** Path-text glyph silhouettes (stroke-and-union, font units) keyed by blob hash + relative weight. */+ glyphSilhouetteCache = new Map<string, Path>()scenePicture: SkPicture | null = nullscenePictureVersion = -1scenePictureFontGeneration = -1diff --git a/packages/core/src/canvas/renderer/lifecycle.ts b/packages/core/src/canvas/renderer/lifecycle.tsindex 65a48d09e..2b6ff7c1d 100644--- a/packages/core/src/canvas/renderer/lifecycle.ts+++ b/packages/core/src/canvas/renderer/lifecycle.ts@@ -10,12 +10,7 @@ function clearRetainedSceneState(r: SkiaRenderer): void {r.sceneBackingBuild = null}-export function destroyRenderer(r: SkiaRenderer): void {- if (r.destroyed) return- r.destroyed = true-- for (const img of r.imageCache.values()) img.delete()- r.imageCache.clear()+function disposePathCaches(r: SkiaRenderer): void {for (const cache of [r.vectorPathCache,r.vectorStrokePathCache,@@ -28,6 +23,18 @@ export function destroyRenderer(r: SkiaRenderer): void {}cache.clear()}+ // glyphSilhouetteCache maps to a single Path per entry (not an array).+ for (const p of r.glyphSilhouetteCache.values()) p.delete()+ r.glyphSilhouetteCache.clear()+}++export function destroyRenderer(r: SkiaRenderer): void {+ if (r.destroyed) return+ r.destroyed = true++ for (const img of r.imageCache.values()) img.delete()+ r.imageCache.clear()+ disposePathCaches(r)r.fillPaint.delete()r.strokePaint.delete()r.selectionPaint.delete()diff --git a/packages/core/src/canvas/scene.ts b/packages/core/src/canvas/scene.tsindex 516ba7d41..03d81e75f 100644--- a/packages/core/src/canvas/scene.ts+++ b/packages/core/src/canvas/scene.ts@@ -29,7 +29,11 @@ import {getStrokeCapEntity,getStrokeJoinEntity} from './strokes'-import { drawFigmaDerivedText } from './text/derived'+import {+ drawDerivedText,+ drawReflowedPathTextSilhouettes,+ isReflowedPathText+} from './text/derived'import { textNodeToOutlinePath } from './text/outlines'function drawVisibleFills(@@ -45,6 +49,14 @@ function hasNodeTransform(node: SceneNode): boolean {return node.rotation !== 0 || node.flipX || node.flipY}+function hasOverflowPathTextPaint(node: SceneNode): boolean {+ return (+ node.textPathData != null &&+ ((node.derivedTextGlyphs?.length ?? 0) > 0 ||+ (Array.isArray(node.strokeGeometry) && node.strokeGeometry.length > 0))+ )+}+function isCulled(r: SkiaRenderer,graph: SceneGraph,@@ -57,7 +69,7 @@ function isCulled(node.childIds.length === 0 ||((node.type === 'FRAME' || node.type === 'COMPONENT' || node.type === 'INSTANCE') &&node.clipsContent)- if (!canCull) return false+ if (!canCull || hasOverflowPathTextPaint(node)) return falseconst vp = r.worldViewportif (hasTransformedAncestor) {@@ -576,8 +588,9 @@ function drawNodeStroke(return}if (stroke.align !== 'INSIDE') {- if (node.type === 'VECTOR') drawVectorStrokeGeometry(r, canvas, sg, sc, stroke.opacity)- else drawRegularStroke(r, canvas, node, rect, hasRadius, stroke, sc)+ if (node.type === 'VECTOR' || node.type === 'TEXT') {+ drawVectorStrokeGeometry(r, canvas, sg, sc, stroke.opacity)+ } else drawRegularStroke(r, canvas, node, rect, hasRadius, stroke, sc)return}@@ -597,25 +610,26 @@ function drawNodeStroke(canvas.restore()}-export function renderShapeUncached(+function isPathTextWithStrokeGeometry(node: SceneNode): boolean {+ return (+ node.type === 'TEXT' &&+ node.textPathData !== null &&+ (node.derivedTextGlyphs?.length ?? 0) > 0 &&+ node.strokeGeometry.length > 0+ )+}++function paintNodeStrokes(r: SkiaRenderer,canvas: Canvas,node: SceneNode,- graph: SceneGraph+ graph: SceneGraph,+ rect: Float32Array,+ hasRadius: boolean,+ sg: Path[] | null,+ vectorPaths: Path[] | null,+ vectorStroke: Path[] | null): void {- const rect = r.ck.LTRBRect(0, 0, node.width, node.height)- const hasRadius = nodeHasRadius(node)-- const shadowChild = getShadowShapeChild(node, graph)- r.renderEffects(canvas, node, rect, hasRadius, 'behind', shadowChild)-- if (!drawVectorMultiStyleFills(r, canvas, node, graph)) {- drawVisibleFills(r, node, graph, (fill) => r.drawNodeFill(canvas, node, rect, hasRadius, fill))- }-- const sg = node.strokeGeometry.length > 0 ? r.getStrokeGeometry(node) : null- const vectorPaths = node.type === 'VECTOR' ? r.getVectorPaths(node) : null- const vectorStroke = node.type === 'VECTOR' ? vectorStrokePaths(r, node) : nullforVisibleStrokes(r, node, graph, (stroke, color) => {if (stroke.dashPattern &&@@ -630,6 +644,42 @@ export function renderShapeUncached(}drawNodeStroke(r, canvas, node, rect, hasRadius, stroke, color, sg, vectorPaths, vectorStroke)})+}++export function renderShapeUncached(+ r: SkiaRenderer,+ canvas: Canvas,+ node: SceneNode,+ graph: SceneGraph+): void {+ const rect = r.ck.LTRBRect(0, 0, node.width, node.height)+ const hasRadius = nodeHasRadius(node)++ const shadowChild = getShadowShapeChild(node, graph)+ r.renderEffects(canvas, node, rect, hasRadius, 'behind', shadowChild)++ const sg = node.strokeGeometry.length > 0 ? r.getStrokeGeometry(node) : null+ const vectorPaths = node.type === 'VECTOR' ? r.getVectorPaths(node) : null+ const vectorStroke = node.type === 'VECTOR' ? vectorStrokePaths(r, node) : null+ const pathTextStrokeFirst = isPathTextWithStrokeGeometry(node)+ const reflowedPathText = isReflowedPathText(node)++ if (pathTextStrokeFirst) {+ paintNodeStrokes(r, canvas, node, graph, rect, hasRadius, sg, vectorPaths, vectorStroke)+ }+ if (reflowedPathText) {+ forVisibleStrokes(r, node, graph, (stroke, color) =>+ drawReflowedPathTextSilhouettes(r, canvas, node, stroke, color)+ )+ }++ if (!drawVectorMultiStyleFills(r, canvas, node, graph)) {+ drawVisibleFills(r, node, graph, (fill) => r.drawNodeFill(canvas, node, rect, hasRadius, fill))+ }++ if (!pathTextStrokeFirst && !reflowedPathText) {+ paintNodeStrokes(r, canvas, node, graph, rect, hasRadius, sg, vectorPaths, vectorStroke)+ }r.renderEffects(canvas, node, rect, hasRadius, 'front', shadowChild)}@@ -697,13 +747,19 @@ function drawGradientText(r: SkiaRenderer, canvas: Canvas, node: SceneNode): boo}}+function shouldClipTextToLayoutBox(node: SceneNode): boolean {+ return (+ !hasOverflowPathTextPaint(node) &&+ (node.textAutoResize === 'NONE' || node.textAutoResize === 'TRUNCATE')+ )+}+export function renderText(r: SkiaRenderer, canvas: Canvas, node: SceneNode, fill?: Fill): void {const text = node.textif (!text) returncanvas.save()- const shouldClipText = node.textAutoResize === 'NONE' || node.textAutoResize === 'TRUNCATE'- if (shouldClipText) {+ if (shouldClipTextToLayoutBox(node)) {canvas.clipRect(r.ck.LTRBRect(0, 0, node.width, node.height), r.ck.ClipOp.Intersect, false)}@@ -719,7 +775,7 @@ export function renderText(r: SkiaRenderer, canvas: Canvas, node: SceneNode, filreturn}}- if (drawFigmaDerivedText(r, canvas, node)) {+ if (drawDerivedText(r, canvas, node)) {canvas.restore()return}diff --git a/packages/core/src/canvas/text/derived.ts b/packages/core/src/canvas/text/derived.tsindex 216dd6a03..3fcc3e01a 100644--- a/packages/core/src/canvas/text/derived.ts+++ b/packages/core/src/canvas/text/derived.ts@@ -1,7 +1,16 @@-import type { Canvas, Paint } from 'canvaskit-wasm'+import type { Canvas, Paint, Path } from 'canvaskit-wasm'-import type { Fill, SceneNode, StyleRun, TextDecorationStyle } from '@open-pencil/scene-graph'+import type {+ Color,+ Fill,+ DerivedTextGlyph,+ SceneNode,+ Stroke,+ StyleRun,+ TextDecorationStyle+} from '@open-pencil/scene-graph'+import { encodeBase64 } from '#core/bytes'import type { SkiaRenderer } from '#core/canvas/renderer'import { geometryBlobToPath } from '#core/vector'@@ -17,11 +26,11 @@ interface DecorationSpan extends DecorationRange {fills: Fill[]}-export function snapFigmaDerivedGlyphBaseline(y: number): number {+export function snapDerivedGlyphBaseline(y: number): number {return Math.round(y)}-export function shouldUseHardFigmaDerivedGlyphCoverage(+export function shouldUseHardDerivedGlyphCoverage(node: Pick<SceneNode, 'fontSize' | 'fontWeight'>): boolean {return node.fontSize === 20 && node.fontWeight === 400@@ -37,7 +46,7 @@ export function derivedUnderlineRect(node: Pick<SceneNode, 'width'>, baselineY:}function styleRunX(node: SceneNode, index: number): number {- const glyph = node.figmaDerivedTextGlyphs?.[index]+ const glyph = node.derivedTextGlyphs?.[index]if (glyph) return glyph.xif (index >= node.text.length) return node.widthif (node.text.length === 0) return 0@@ -212,17 +221,169 @@ function drawDerivedDecorations(}}-export function drawFigmaDerivedText(r: SkiaRenderer, canvas: Canvas, node: SceneNode): boolean {- if (!node.figmaDerivedTextGlyphs?.length) return false+/**+ * Path-text glyphs carry non-zero Figma `Glyph.rotation` (radians). Used to+ * disable axis-aligned assumptions (baseline snap, underline decorations).+ */+export function hasRotatedDerivedGlyphs(node: Pick<SceneNode, 'derivedTextGlyphs'>): boolean {+ return node.derivedTextGlyphs?.some((glyph) => (glyph.rotation ?? 0) !== 0) === true+}++/**+ * Resize-reflowed TEXT_PATH node: glyphs were re-laid along the path and the+ * baked node-level strokeGeometry was cleared — strokes must be re-derived+ * per glyph (see drawReflowedPathTextSilhouettes).+ */+export function isReflowedPathText(node: SceneNode): boolean {+ return (+ node.type === 'TEXT' &&+ (node.derivedTextGlyphs?.length ?? 0) > 0 &&+ node.textPathBox !== null &&+ node.strokeGeometry.length === 0 &&+ node.textPathData !== null+ )+}++interface GlyphSilhouette {+ path: Path+ cached: boolean+}++/**+ * Silhouette = glyph outline dilated by the stroke weight, unioned with the+ * glyph itself (font units, so one cache entry serves every placement).+ * Cached paths are never deleted — the cache is content-keyed and bounded by+ * the number of distinct glyph outlines.+ *+ * ponytail: approximates every stroke.align as OUTSIDE (full-weight band+ * outside the glyph, backfilled by the union). Matches the baked path-text+ * stroke pipeline, which is OUTSIDE-oriented too, so it's consistent — but+ * CENTER sits too far out and INSIDE shows a band the fill should cover. Full+ * parity means per-align geometry (+ align in the cache key); deferred as the+ * reflow fallback only fires on resized stroked path text.+ */+function getGlyphSilhouette(+ r: SkiaRenderer,+ glyph: DerivedTextGlyph,+ stroke: Stroke+): GlyphSilhouette {+ const blob = glyph.commandsBlob+ const relativeWeight = stroke.weight / glyph.fontSize+ const key = `${encodeBase64(blob)}:${relativeWeight.toFixed(5)}`+ const cached = r.glyphSilhouetteCache.get(key)+ if (cached) return { path: cached, cached: true }++ const base = geometryBlobToPath(r.ck, blob, 'NONZERO')+ const outline = base.copy()+ // Round join/cap: miter spikes on glyph cusps (e.g. 'A' apex) shoot far+ // outside the letterform. Width doubles because half the band is swallowed+ // by the union with the glyph body (OUTSIDE-stroke look).+ const stroked = outline.stroke({+ width: relativeWeight * 2,+ join: r.ck.StrokeJoin.Round,+ cap: r.ck.StrokeCap.Round+ })+ // stroke()/op() mutate `outline` in place; both report failure, not a new path.+ const merged = stroked?.op(base, r.ck.PathOp.Union)+ if (!merged) {+ // Degenerate outline — draw the bare glyph, uncached so callers free it.+ outline.delete()+ return { path: base, cached: false }+ }+ base.delete()+ // ponytail: crude bound — a live stroke-weight drag mints a key per tick;+ // wholesale clear beats an LRU here since rebuild is cheap.+ if (r.glyphSilhouetteCache.size >= 512) {+ for (const path of r.glyphSilhouetteCache.values()) path.delete()+ r.glyphSilhouetteCache.clear()+ }+ r.glyphSilhouetteCache.set(key, outline)+ return { path: outline, cached: true }+}++/**+ * Push a glyph's on-path transform: baseline → non-uniform scale → rotate →+ * font-units→px (Y-flipped). The fill and silhouette passes share it so they+ * stay registered; see drawDerivedText for the order rationale.+ */+function applyGlyphEmTransform(canvas: Canvas, glyph: DerivedTextGlyph, glyphY: number): void {+ canvas.translate(glyph.x, glyphY)+ const scaleX = glyph.scaleX ?? 1+ const scaleY = glyph.scaleY ?? 1+ if (scaleX !== 1 || scaleY !== 1) canvas.scale(scaleX, scaleY)+ const rotation = glyph.rotation ?? 0+ if (rotation !== 0) canvas.rotate((-rotation * 180) / Math.PI, 0, 0)+ canvas.scale(glyph.fontSize, -glyph.fontSize)+}++/**+ * Paint per-glyph stroke silhouettes under a reflowed path-text node.+ * Transform chain mirrors drawDerivedText exactly so silhouettes and+ * fills stay registered.+ */+export function drawReflowedPathTextSilhouettes(+ r: SkiaRenderer,+ canvas: Canvas,+ node: SceneNode,+ stroke: Stroke,+ color: Color+): void {+ const glyphs = node.derivedTextGlyphs+ if (!glyphs?.length || stroke.weight <= 0) return++ const snapBaselines = !hasRotatedDerivedGlyphs(node)+ const paint = new r.ck.Paint()+ paint.setAntiAlias(true)+ paint.setStyle(r.ck.PaintStyle.Fill)+ paint.setColor(r.ck.Color4f(color.r, color.g, color.b, color.a))+ paint.setAlphaf(stroke.opacity)+ try {+ for (const glyph of glyphs) {+ if (glyph.fontSize <= 0) continue+ const silhouette = getGlyphSilhouette(r, glyph, stroke)+ canvas.save()+ applyGlyphEmTransform(+ canvas,+ glyph,+ snapBaselines ? snapDerivedGlyphBaseline(glyph.y) : glyph.y+ )+ canvas.drawPath(silhouette.path, paint)+ canvas.restore()+ if (!silhouette.cached) silhouette.path.delete()+ }+ } finally {+ paint.delete()+ }+}++/**+ * Paint Figma-baked glyph outlines (missing-font / path-text fidelity path).+ *+ * Transform order is intentional and matched against real TEXT_PATH fixtures+ * (e.g. DomeSticker circular lettering):+ *+ * 1. translate(x, y) — baseline on the path (already resize-scaled)+ * 2. scale(scaleX,Y) — non-uniform resize (must be *outside* rotation;+ * S and R do not commute — see resize scaleX/Y)+ * 3. rotate(-θ°) — negate: CanvasKit degrees + following Y-flip;+ * positive Figma radians would otherwise misalign+ * black fills vs white strokeGeometry+ * 4. scale(fontSize,-fs) — font units → px; Y flip (font space is up-positive)+ */+export function drawDerivedText(r: SkiaRenderer, canvas: Canvas, node: SceneNode): boolean {+ if (!node.derivedTextGlyphs?.length) return false+ // Pixel-snap is for horizontal Figma baselines only — on a curve it stair-steps+ // letter positions and breaks registration with strokeGeometry.+ const snapBaselines = !hasRotatedDerivedGlyphs(node)let underlineBaselineY = 0- for (const glyph of node.figmaDerivedTextGlyphs) {- underlineBaselineY = Math.max(underlineBaselineY, snapFigmaDerivedGlyphBaseline(glyph.y))+ for (const glyph of node.derivedTextGlyphs) {+ const glyphY = snapBaselines ? snapDerivedGlyphBaseline(glyph.y) : glyph.y+ underlineBaselineY = Math.max(underlineBaselineY, glyphY)const path = geometryBlobToPath(r.ck, glyph.commandsBlob, 'NONZERO')canvas.save()- canvas.translate(glyph.x, snapFigmaDerivedGlyphBaseline(glyph.y))- canvas.scale(glyph.fontSize, -glyph.fontSize)- const shouldUseHardCoverage = shouldUseHardFigmaDerivedGlyphCoverage(node)+ applyGlyphEmTransform(canvas, glyph, glyphY)+ const shouldUseHardCoverage = shouldUseHardDerivedGlyphCoverage(node)if (shouldUseHardCoverage) r.fillPaint.setAntiAlias(false)canvas.drawPath(path, r.fillPaint)if (shouldUseHardCoverage) r.fillPaint.setAntiAlias(true)@@ -230,6 +391,7 @@ export function drawFigmaDerivedText(r: SkiaRenderer, canvas: Canvas, node: Scenpath.delete()}- drawDerivedDecorations(r, canvas, node, underlineBaselineY)+ // Underline math assumes a single horizontal baseline — skip for path text.+ if (snapBaselines) drawDerivedDecorations(r, canvas, node, underlineBaselineY)return true}diff --git a/packages/core/src/editor/nodes.ts b/packages/core/src/editor/nodes.tsindex ce19f306d..45576ee0f 100644--- a/packages/core/src/editor/nodes.ts+++ b/packages/core/src/editor/nodes.ts@@ -5,6 +5,7 @@ import { styleDetachmentChanges, type SceneNode } from '@open-pencil/scene-graphimport { createLayoutModeActions } from './layout-mode'import { createNudgeActions } from './nudge'import { textAutoResizeChanges } from './text/auto-resize'+import { pathTextEditChanges } from './text/path-edit'import type { EditorContext } from './types'import { createVariableBindingActions } from './variable-bindings'@@ -25,9 +26,12 @@ export function createNodeActions(ctx: EditorContext) {function updateNode(id: string, changes: Partial<SceneNode>) {const node = ctx.graph.getNode(id)if (!node) return+ // Path-edit last so its reflowed glyphs win over auto-resize's glyph clear+ // (path text is textAutoResize NONE so they don't collide today).const nextChanges = styleDetachmentChanges(node, {...changes,- ...textAutoResizeChanges(node, changes)+ ...textAutoResizeChanges(node, changes),+ ...pathTextEditChanges(node, changes)})ctx.graph.updateNode(id, nextChanges)ctx.runLayoutForNode(id)@@ -36,9 +40,11 @@ export function createNodeActions(ctx: EditorContext) {function updateNodeWithUndo(id: string, changes: Partial<SceneNode>, label = 'Update') {const node = ctx.graph.getNode(id)if (!node) return+ // Same ordering rationale as updateNode: reflowed path-text glyphs win.const nextChanges = styleDetachmentChanges(node, {...changes,- ...textAutoResizeChanges(node, changes)+ ...textAutoResizeChanges(node, changes),+ ...pathTextEditChanges(node, changes)})const previous = pick(node,diff --git a/packages/core/src/editor/text.ts b/packages/core/src/editor/text.tsindex 0dbab466f..e25184e11 100644--- a/packages/core/src/editor/text.ts+++ b/packages/core/src/editor/text.ts@@ -1,3 +1,10 @@+import type { SceneNode } from '@open-pencil/scene-graph'+import { copyDerivedGlyphs, copyGeometryPaths } from '@open-pencil/scene-graph/copy'++import { weightToStyle } from '#core/text/fonts'+import { hasGlyphOutlines } from '#core/text/opentype'++import { pathTextEditChanges } from './text/path-edit'import {createTextEditSession,resizeTextNodeForEdit,@@ -7,6 +14,38 @@ import {} from './text/session'import type { EditorContext } from './types'+/**+ * Path text is edited by re-flowing glyph OUTLINES along its path. When the font+ * is unavailable we can't produce new glyphs, so editing would corrupt the baked+ * lettering — treat it as a baked graphic and refuse to enter edit mode. Non-path+ * text still edits (system-font fallback); path text with the font available+ * edits fully (add/remove characters reflow). "Available" is deliberately broad:+ * today that means loaded locally, but a future remote provider (e.g. Google+ * Fonts) would extend hasGlyphOutlines without changing this gate.+ */+function isPathTextEditable(node: SceneNode): boolean {+ if (!node.textPathData) return true+ return hasGlyphOutlines(node.fontFamily, weightToStyle(node.fontWeight, node.italic))+}++type PathTextEditSnapshot = Pick<+ SceneNode,+ 'derivedTextGlyphs' | 'strokeGeometry' | 'textPathData' | 'textPathBox'+>++function snapshotPathText(+ node: SceneNode | undefined,+ includeClearedPathState = false+): PathTextEditSnapshot | null {+ if (!node || (!includeClearedPathState && !node.textPathData)) return null+ return {+ derivedTextGlyphs: copyDerivedGlyphs(node.derivedTextGlyphs),+ strokeGeometry: copyGeometryPaths(node.strokeGeometry),+ textPathData: node.textPathData ? structuredClone(node.textPathData) : null,+ textPathBox: node.textPathBox ? { ...node.textPathBox } : null+ }+}+type InstanceOverridesSnapshot = {instanceId: stringoverrides: Record<string, unknown>@@ -60,11 +99,19 @@ function applyTextInstanceOverride(export function createTextActions(ctx: EditorContext) {let activeSession: TextEditSession | null = null+ function updateTextEditNode(nodeId: string, changes: Partial<SceneNode>) {+ const node = ctx.graph.getNode(nodeId)+ if (!node) return+ ctx.graph.updateNode(nodeId, { ...changes, ...pathTextEditChanges(node, changes) })+ }+function startTextEditing(nodeId: string) {const te = ctx.getTextEditor()if (ctx.state.editingTextId) commitTextEdit()const node = ctx.graph.getNode(nodeId)if (!node) return+ // Font-gated: unavailable-font path text stays a non-editable baked graphic.+ if (!isPathTextEditable(node)) returnactiveSession = createTextEditSession(node)ctx.state.editingTextId = nodeIdif (te) {@@ -91,6 +138,7 @@ export function createTextActions(ctx: EditorContext) {}const result = { nodeId: textState.nodeId, text: textState.text }const before = activeSession?.before ?? { text: '', styleRuns: [], size: {} }+ const beforePathText = activeSession?.beforePathText ?? nullconst node = ctx.graph.getNode(result.nodeId)const after = snapshotTextNode(node, result.text)after.text = result.text@@ -110,11 +158,15 @@ export function createTextActions(ctx: EditorContext) {return}- ctx.graph.updateNode(result.nodeId, {+ updateTextEditNode(result.nodeId, {text: after.text,styleRuns: after.styleRuns,...sizeChanges})+ const afterPathText = snapshotPathText(+ ctx.graph.getNode(result.nodeId),+ beforePathText !== null+ )if (before.text !== after.text) {applyTextInstanceOverride(ctx, containingInstances, result.nodeId, after.text)}@@ -128,7 +180,8 @@ export function createTextActions(ctx: EditorContext) {ctx.graph.updateNode(result.nodeId, {text: after.text,styleRuns: after.styleRuns,- ...after.size+ ...after.size,+ ...afterPathText})restoreInstanceOverrides(ctx, instanceOverridesAfter)},@@ -136,12 +189,13 @@ export function createTextActions(ctx: EditorContext) {ctx.graph.updateNode(result.nodeId, {text: before.text,styleRuns: before.styleRuns,- ...before.size+ ...before.size,+ ...beforePathText})restoreInstanceOverrides(ctx, instanceOverridesBefore)}})}- return { startTextEditing, commitTextEdit }+ return { startTextEditing, updateTextEditNode, commitTextEdit }}diff --git a/packages/core/src/editor/text/auto-resize.ts b/packages/core/src/editor/text/auto-resize.tsindex 4fa38d0ff..dbbeeceb1 100644--- a/packages/core/src/editor/text/auto-resize.ts+++ b/packages/core/src/editor/text/auto-resize.ts@@ -42,8 +42,15 @@ function hasTextAutoWidthChange(changes: Partial<SceneNode>): boolean {export function textAutoResizeChanges(node: SceneNode | undefined,changes: Partial<SceneNode>-): Partial<Pick<SceneNode, 'width' | 'height' | 'figmaDerivedLayout' | 'figmaDerivedTextGlyphs'>> {+): Partial<Pick<SceneNode, 'width' | 'height' | 'derivedLayout' | 'derivedTextGlyphs'>> {if (node?.type !== 'TEXT' || !hasTextAutoResizeChange(changes)) return {}+ // Path text is laid out along its path (derivedTextGlyphs on textPathBox),+ // not by paragraph auto-resize. Running the measurement here would null the+ // derived glyphs — destroying the on-path lettering — whenever an imported+ // TEXT_PATH carries textAutoResize HEIGHT/WIDTH_AND_HEIGHT and a keystroke+ // can't reflow (font outlines or the layout path unavailable). pathTextEditChanges+ // owns path-text reflow; leave its glyphs alone.+ if (node.textPathData) return {}const next = { ...node, ...changes }const mode = next.textAutoResize@@ -52,11 +59,8 @@ export function textAutoResizeChanges(const maxWidth = mode === 'HEIGHT' ? next.width : undefinedconst measured = getTextMeasurer()?.(next, maxWidth) ?? estimateTextSize(next, maxWidth)const resized: Partial<- Pick<SceneNode, 'width' | 'height' | 'figmaDerivedLayout' | 'figmaDerivedTextGlyphs'>- > = {- figmaDerivedLayout: null,- figmaDerivedTextGlyphs: null- }+ Pick<SceneNode, 'width' | 'height' | 'derivedLayout' | 'derivedTextGlyphs'>+ > = { derivedLayout: null, derivedTextGlyphs: null }if (mode === 'WIDTH_AND_HEIGHT' && hasTextAutoWidthChange(changes) && measured.width > 0)resized.width = measured.widthdiff --git a/packages/core/src/editor/text/path-edit.ts b/packages/core/src/editor/text/path-edit.tsnew file mode 100644index 000000000..81bc7cff1--- /dev/null+++ b/packages/core/src/editor/text/path-edit.ts@@ -0,0 +1,71 @@+import { encodePathCommandsBlob } from '@open-pencil/fig/node-change'+import type { SceneNode } from '@open-pencil/scene-graph'++import { weightToStyle } from '#core/text/fonts'+import { getGlyphOutlineMetricsSync } from '#core/text/opentype'+import {+ calibratePathTextLayout,+ getTextPathData,+ layoutPathTextFromAdvances+} from '#core/text/path'++/**+ * Re-flow imported path text when its characters 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+ * scene graph then falls back to clearing the baked glyphs (today's+ * plain-text editing behavior).+ */+export function pathTextEditChanges(+ node: SceneNode | undefined,+ 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) {+ 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 = layout.offsets.reduce((sum, o) => sum + o, 0) / layout.offsets.length++ const glyphs = layoutPathTextFromAdvances(+ 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+ }))+ )+ // 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: [] } : {}+}diff --git a/packages/core/src/editor/text/session.ts b/packages/core/src/editor/text/session.tsindex 4e4b96b82..911caebf6 100644--- a/packages/core/src/editor/text/session.ts+++ b/packages/core/src/editor/text/session.ts@@ -2,7 +2,7 @@ import type { Paragraph } from 'canvaskit-wasm'import { isEqual } from 'es-toolkit/predicate'import type { SceneNode, StyleRun } from '@open-pencil/scene-graph'-import { copyStyleRuns } from '@open-pencil/scene-graph/copy'+import { copyDerivedGlyphs, copyGeometryPaths, copyStyleRuns } from '@open-pencil/scene-graph/copy'export type TextEditSizeSnapshot = Partial<Pick<SceneNode, 'width' | 'height'>>@@ -15,6 +15,10 @@ export type TextEditSnapshot = {export type TextEditSession = {nodeId: stringbefore: TextEditSnapshot+ beforePathText: Pick<+ SceneNode,+ 'derivedTextGlyphs' | 'strokeGeometry' | 'textPathData' | 'textPathBox'+ > | null}export function createTextEditSession(node: SceneNode): TextEditSession {@@ -24,7 +28,15 @@ export function createTextEditSession(node: SceneNode): TextEditSession {text: node.text,styleRuns: copyStyleRuns(node.styleRuns),size: { width: node.width, height: node.height }- }+ },+ beforePathText: node.textPathData+ ? {+ derivedTextGlyphs: copyDerivedGlyphs(node.derivedTextGlyphs),+ strokeGeometry: copyGeometryPaths(node.strokeGeometry),+ textPathData: structuredClone(node.textPathData),+ textPathBox: node.textPathBox ? { ...node.textPathBox } : null+ }+ : null}}diff --git a/packages/core/src/editor/undo.ts b/packages/core/src/editor/undo.tsindex c8963d839..938b48bc0 100644--- a/packages/core/src/editor/undo.ts+++ b/packages/core/src/editor/undo.ts@@ -1,8 +1,8 @@import { pick } from 'es-toolkit/object'-import { cloneVectorNetwork, type SceneNode } from '@open-pencil/scene-graph'-import { copyGeometryPaths } from '@open-pencil/scene-graph/copy'+import type { SceneNode } from '@open-pencil/scene-graph'import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'+import { createResizeSnapshot, type ResizeSnapshot } from '@open-pencil/scene-graph/resize'import type { UndoEntry } from '@open-pencil/scene-graph/undo'import { assertNodeEditable } from './capabilities'@@ -16,24 +16,19 @@ import {import { textAutoResizeChanges } from './text/auto-resize'import type { EditorContext } from './types'-type ResizeSnapshot = Pick<- SceneNode,- 'x' | 'y' | 'width' | 'height' | 'vectorNetwork' | 'fillGeometry' | 'strokeGeometry'->type ResizeOriginal = Rect &- Partial<Pick<SceneNode, 'vectorNetwork' | 'fillGeometry' | 'strokeGeometry'>>--function createResizeSnapshot(node: SceneNode): ResizeSnapshot {- return {- x: node.x,- y: node.y,- width: node.width,- height: node.height,- vectorNetwork: node.vectorNetwork ? cloneVectorNetwork(node.vectorNetwork) : null,- fillGeometry: copyGeometryPaths(node.fillGeometry),- strokeGeometry: copyGeometryPaths(node.strokeGeometry)- }-}+ Partial<+ Pick<+ SceneNode,+ | 'vectorNetwork'+ | 'fillGeometry'+ | 'strokeGeometry'+ | 'derivedTextGlyphs'+ | 'strokes'+ | 'textPathData'+ | 'textPathBox'+ >+ >export function createUndoActions(ctx: EditorContext) {function commitMove(originals: Map<string, Vector>) {@@ -105,19 +100,30 @@ export function createUndoActions(ctx: EditorContext) {assertNodeEditable(ctx.graph, nodeId)const node = ctx.graph.getNode(nodeId)if (!node) return- const includesGeometry =- 'vectorNetwork' in original || 'fillGeometry' in original || 'strokeGeometry' in original- const final: ResizeOriginal = includesGeometry+ // Snapshot full geometry when the inverse payload carries any of it+ // (vector/path-text resize); plain rect-only resize stays lightweight.+ const hasGeometry =+ 'vectorNetwork' in original ||+ 'fillGeometry' in original ||+ 'strokeGeometry' in original ||+ 'derivedTextGlyphs' in original ||+ 'strokes' in original ||+ 'textPathData' in original ||+ 'textPathBox' in original+ const final: ResizeOriginal = hasGeometry? createResizeSnapshot(node): { x: node.x, y: node.y, width: node.width, height: node.height }ctx.undo.push({label: 'Resize',forward: () => {- ctx.graph.updateNode(nodeId, final)+ assertNodeEditable(ctx.graph, nodeId)+ // Geometric replay — keep the raw Figma payload (see commitResizePreview).+ ctx.graph.preserveSourceMetadataDuring(() => ctx.graph.updateNode(nodeId, final))ctx.runLayoutForNode(nodeId)},inverse: () => {- ctx.graph.updateNode(nodeId, original)+ assertNodeEditable(ctx.graph, nodeId)+ ctx.graph.preserveSourceMetadataDuring(() => ctx.graph.updateNode(nodeId, original))ctx.runLayoutForNode(nodeId)}})@@ -143,15 +149,20 @@ export function createUndoActions(ctx: EditorContext) {forward: () => {assertNodeEditable(ctx.graph, nodeId)for (const childId of finalChildren.keys()) assertNodeEditable(ctx.graph, childId)- ctx.graph.updateNode(nodeId, finalRect)- for (const [childId, final] of finalChildren) ctx.graph.updateNode(childId, final)+ // Geometric replay — keep the raw Figma payload (see commitResizePreview).+ ctx.graph.preserveSourceMetadataDuring(() => {+ ctx.graph.updateNode(nodeId, finalRect)+ for (const [childId, final] of finalChildren) ctx.graph.updateNode(childId, final)+ })ctx.runLayoutForNode(nodeId)},inverse: () => {assertNodeEditable(ctx.graph, nodeId)for (const childId of origChildren.keys()) assertNodeEditable(ctx.graph, childId)- ctx.graph.updateNode(nodeId, origRect)- for (const [childId, orig] of origChildren) ctx.graph.updateNode(childId, orig)+ ctx.graph.preserveSourceMetadataDuring(() => {+ ctx.graph.updateNode(nodeId, origRect)+ for (const [childId, orig] of origChildren) ctx.graph.updateNode(childId, orig)+ })ctx.runLayoutForNode(nodeId)}})diff --git a/packages/core/src/layout.ts b/packages/core/src/layout.tsindex d93476c8c..eb51a631c 100644--- a/packages/core/src/layout.ts+++ b/packages/core/src/layout.ts@@ -268,10 +268,10 @@ function derivedMainAxisFitsParent(.filter((candidate) => candidate.visible && candidate.layoutPositioning !== 'ABSOLUTE')if (children.length === 0) return false- const sizes = children.map((candidate) => candidate.figmaDerivedLayout?.[axis])+ const sizes = children.map((candidate) => candidate.derivedLayout?.[axis])return (sizesFitParent(parent, children.length, sizes, axis) &&- child.figmaDerivedLayout?.[axis] !== undefined+ child.derivedLayout?.[axis] !== undefined)}@@ -279,14 +279,12 @@ function usesAuthoritativeGeneratedStretch(parent: SceneNode, child: SceneNode):if (child.layoutAlignSelf !== 'STRETCH' ||parent.source.format === 'fig' ||- !parent.figmaDerivedLayout+ !parent.derivedLayout) {return false}const derivedCrossSize =- parent.layoutMode === 'HORIZONTAL'- ? parent.figmaDerivedLayout.height- : parent.figmaDerivedLayout.width+ parent.layoutMode === 'HORIZONTAL' ? parent.derivedLayout.height : parent.derivedLayout.widthconst parentCrossSize = parent.layoutMode === 'HORIZONTAL' ? parent.height : parent.widthreturn derivedCrossSize !== undefined && Math.abs(derivedCrossSize - parentCrossSize) < 0.001}@@ -306,7 +304,7 @@ function configureAutoLayoutChildSizing(const stretchesAuthoritativeCrossAxis = usesAuthoritativeGeneratedStretch(parent, child)if (isParentRow) {- if (fixedDerivedMainAxis) yogaChild.setWidth(child.figmaDerivedLayout?.width ?? child.width)+ if (fixedDerivedMainAxis) yogaChild.setWidth(child.derivedLayout?.width ?? child.width)else setMainAxisSizing(yogaChild, 'width', widthSizing, child.width, child.layoutGrow)if (!stretchesAuthoritativeCrossAxis) {setCrossAxisSizing(yogaChild, 'height', heightSizing, child.height)@@ -317,7 +315,7 @@ function configureAutoLayoutChildSizing(if (!stretchesAuthoritativeCrossAxis) {setCrossAxisSizing(yogaChild, 'width', widthSizing, child.width)}- if (fixedDerivedMainAxis) yogaChild.setHeight(child.figmaDerivedLayout?.height ?? child.height)+ if (fixedDerivedMainAxis) yogaChild.setHeight(child.derivedLayout?.height ?? child.height)else setMainAxisSizing(yogaChild, 'height', heightSizing, child.height, child.layoutGrow)}@@ -339,7 +337,7 @@ function configureChildAsAutoLayout(if (selfAlign != null) yogaChild.setAlignSelf(selfAlign)if (usesDetachedDerivedLayout(child)) {- const derived = child.figmaDerivedLayout+ const derived = child.derivedLayoutif (widthSizing === 'HUG') yogaChild.setWidth(derived?.width ?? child.width)if (heightSizing === 'HUG') yogaChild.setHeight(derived?.height ?? child.height)applyMinMaxConstraints(yogaChild, child)@@ -372,18 +370,14 @@ function derivedGrowingLeafFitsParent(child: SceneNode,axis: 'width' | 'height'): boolean {- if (- child.type !== 'TEXT' ||- child.layoutGrow <= 0 ||- child.figmaDerivedLayout?.[axis] === undefined- ) {+ if (child.type !== 'TEXT' || child.layoutGrow <= 0 || child.derivedLayout?.[axis] === undefined) {return false}const children = graph.getChildren(parent.id).filter((candidate) => candidate.visible && candidate.layoutPositioning !== 'ABSOLUTE')const sizes = children.map((candidate) => {- if (candidate.layoutGrow > 0) return candidate.figmaDerivedLayout?.[axis]+ if (candidate.layoutGrow > 0) return candidate.derivedLayout?.[axis]return axis === 'width' ? candidate.width : candidate.height})return sizesFitParent(parent, children.length, sizes, axis)@@ -413,7 +407,7 @@ function configureTextLeafWithoutMeasurer(const isRow = parent.layoutMode === 'HORIZONTAL'const measurementWidth = fixedDerivedMainAxis- ? (child.figmaDerivedLayout?.width ?? child.width)+ ? (child.derivedLayout?.width ?? child.width): child.widthconst stretches =child.layoutAlignSelf === 'STRETCH' ||@@ -444,8 +438,8 @@ function configureChildAsLeaf(: derivedGrowingLeafFitsParent(graph, parent, child, 'height')if (fixedDerivedMainAxis) {- if (isRow) yogaChild.setWidth(child.figmaDerivedLayout?.width ?? child.width)- else yogaChild.setHeight(child.figmaDerivedLayout?.height ?? child.height)+ if (isRow) yogaChild.setWidth(child.derivedLayout?.width ?? child.width)+ else yogaChild.setHeight(child.derivedLayout?.height ?? child.height)}if (needsMeasureFunc) {@@ -479,7 +473,7 @@ function configureTextLeaf(const UNCONSTRAINED_KEY = -1if (autoResize === 'WIDTH_AND_HEIGHT') {- const importedSize = child.figmaDerivedLayout+ const importedSize = child.derivedLayoutif (importedSize?.width !== undefined && importedSize.height !== undefined) {yogaChild.setWidth(child.width)yogaChild.setHeight(child.height)@@ -504,7 +498,7 @@ function configureTextLeaf(// Let Yoga stretch fill-width text instead of fixing its stored width.const fillsWidth = !isRow && stretchesCrossconst fixedWidth = fixedDerivedMainAxis- ? (child.figmaDerivedLayout?.width ?? child.width)+ ? (child.derivedLayout?.width ?? child.width): child.widthif (child.layoutGrow <= 0 && !fillsWidth) {yogaChild.setWidth(fixedWidth)diff --git a/packages/core/src/layout/apply.ts b/packages/core/src/layout/apply.tsindex 218ffd536..0e627ed5e 100644--- a/packages/core/src/layout/apply.ts+++ b/packages/core/src/layout/apply.ts@@ -17,8 +17,7 @@ function preservesImportedHugCrossSize(return graph.getChildren(frame.id).some(- (child) =>- child.layoutAlignSelf === 'STRETCH' && child.figmaDerivedLayout?.[axis] !== undefined+ (child) => child.layoutAlignSelf === 'STRETCH' && child.derivedLayout?.[axis] !== undefined)}@@ -36,7 +35,7 @@ function applyFrameSize(graph: SceneGraph, frame: SceneNode, yogaNode: YogaNode)const computedH = yogaNode.getComputedHeight()const updates: Partial<SceneNode> = {}- const derived = frame.figmaDerivedLayout+ const derived = frame.derivedLayoutif (frame.primaryAxisSizing === 'HUG') {if (frame.layoutMode === 'HORIZONTAL') updates.width = derived?.width ?? computedWelse updates.height = derived?.height ?? computedH@@ -69,11 +68,11 @@ function computedChildPosition(if (preservesImportedGeometry) return child[axis]const computed = axis === 'x' ? yogaChild.getComputedLeft() : yogaChild.getComputedTop()if (child.type === 'INSTANCE') return computed- return child.figmaDerivedLayout?.[axis] ?? computed+ return child.derivedLayout?.[axis] ?? computed}function preservesStaleImportedTextSize(child: SceneNode, axis: 'width' | 'height'): boolean {- const derivedSize = child.figmaDerivedLayout?.[axis]+ const derivedSize = child.derivedLayout?.[axis]return (child.type === 'TEXT' &&child.source.format === 'fig' &&@@ -95,7 +94,7 @@ function computedChildSize(if (child.type === 'TEXT' && child.source.format === 'fig') {return computed > 0 ? computed : child[axis]}- return child.figmaDerivedLayout?.[axis] ?? computed+ return child.derivedLayout?.[axis] ?? computed}function updateChildFromYoga(graph: SceneGraph, child: SceneNode, yogaChild: YogaNode): void {diff --git a/packages/core/src/layout/derived.ts b/packages/core/src/layout/derived.tsindex 3b9ec64a3..3ec5a6971 100644--- a/packages/core/src/layout/derived.ts+++ b/packages/core/src/layout/derived.ts@@ -1,7 +1,7 @@import type { SceneNode } from '@open-pencil/scene-graph'export function usesDetachedDerivedLayout(child: SceneNode): boolean {- const derived = child.figmaDerivedLayout+ const derived = child.derivedLayoutif (!derived || child.layoutMode === 'NONE' || child.layoutGrow > 0) return falseconst isRow = child.layoutMode === 'HORIZONTAL'const widthSizing = isRow ? child.primaryAxisSizing : child.counterAxisSizingdiff --git a/packages/core/src/layout/effective-generated-text.ts b/packages/core/src/layout/effective-generated-text.tsindex 883ca4357..09133797e 100644--- a/packages/core/src/layout/effective-generated-text.ts+++ b/packages/core/src/layout/effective-generated-text.ts@@ -18,7 +18,7 @@ function axisSizing(node: SceneNode, axis: LayoutAxis): SceneNode['primaryAxisSifunction canResizeIntrinsicAxis(node: SceneNode, axis: LayoutAxis): boolean {return (axisSizing(node, axis) === 'HUG' ||- (node.source.format === 'fig' && node.figmaDerivedLayout?.[axis] === undefined)+ (node.source.format === 'fig' && node.derivedLayout?.[axis] === undefined))}@@ -53,9 +53,9 @@ function canShapeGeneratedText(graph: SceneGraph, node: SceneNode): boolean {node.type !== 'TEXT' ||node.source.format === 'fig' ||!node.componentId ||- !node.figmaDerivedLayout ||- node.figmaDerivedLayout.width !== node.width ||- node.figmaDerivedLayout.height !== node.height+ !node.derivedLayout ||+ node.derivedLayout.width !== node.width ||+ node.derivedLayout.height !== node.height) {return false}@@ -162,8 +162,8 @@ function stretchChildrenToEffectiveWidth(continue}const updates: Partial<SceneNode> = { width: nextContentWidth }- if (child.figmaDerivedLayout) {- updates.figmaDerivedLayout = { ...child.figmaDerivedLayout, width: nextContentWidth }+ if (child.derivedLayout) {+ updates.derivedLayout = { ...child.derivedLayout, width: nextContentWidth }}graph.updateNode(child.id, updates)currentSizes.set(child.id, { width: nextContentWidth, height: child.height })@@ -206,7 +206,7 @@ function updateGeneratedTextWidths(graph.updateNode(node.id, {width: measured.width,- figmaDerivedLayout: { ...node.figmaDerivedLayout, width: measured.width }+ derivedLayout: { ...node.derivedLayout, width: measured.width }})currentSizes.set(node.id, { width: measured.width, height: node.height })affected.add(node.id)@@ -249,9 +249,9 @@ function propagateIntrinsicSizes(}if (Object.keys(updates).length === 0) continue- if (node.figmaDerivedLayout) {- updates.figmaDerivedLayout = {- ...node.figmaDerivedLayout,+ if (node.derivedLayout) {+ updates.derivedLayout = {+ ...node.derivedLayout,...(updates.width === undefined ? {} : { width: nextWidth }),...(updates.height === undefined ? {} : { height: nextHeight })}diff --git a/packages/core/src/library/snapshot.ts b/packages/core/src/library/snapshot.tsindex e837299e5..c7bec2b79 100644--- a/packages/core/src/library/snapshot.ts+++ b/packages/core/src/library/snapshot.ts@@ -13,8 +13,8 @@ const VOLATILE_NODE_FIELDS = new Set(['overrides','componentPropertyAssignments','textPicture',- 'figmaDerivedTextGlyphs',- 'figmaDerivedLayout',+ 'derivedTextGlyphs',+ 'derivedLayout','librarySource','pluginData'])diff --git a/packages/core/src/text/editor.ts b/packages/core/src/text/editor.tsindex 1892c8af7..3cc126de3 100644--- a/packages/core/src/text/editor.ts+++ b/packages/core/src/text/editor.ts@@ -129,6 +129,11 @@ export class TextEditor {return s !== null && s.selectionAnchor !== null && s.selectionAnchor !== s.cursor}+ /** Character index of the caret, or null when not editing. */+ get caretIndex(): number | null {+ return this._state?.cursor ?? null+ }+getSelectionRange(): [number, number] | null {const s = this._stateif (!s || s.selectionAnchor === null || s.selectionAnchor === s.cursor) return nulldiff --git a/packages/core/src/text/index.ts b/packages/core/src/text/index.tsindex a7ec848c5..7dea36259 100644--- a/packages/core/src/text/index.ts+++ b/packages/core/src/text/index.ts@@ -10,3 +10,4 @@ export * from './resolver'export * from './requirements'export * from './resolved-requirements'export * from './web-fonts'+export * from './path'diff --git a/packages/core/src/text/opentype.ts b/packages/core/src/text/opentype.tsindex add0f0748..268970f76 100644--- a/packages/core/src/text/opentype.ts+++ b/packages/core/src/text/opentype.ts@@ -29,6 +29,14 @@ interface OutlineFont {tables: { os2?: { sTypoLineGap?: number } }charToGlyphIndex(char: string): numbercharToGlyph(char: string): OutlineGlyph+ forEachGlyph(+ text: string,+ x: number,+ y: number,+ fontSize: number,+ options: undefined,+ callback: (glyph: OutlineGlyph, x: number) => void+ ): number}export interface GlyphOutlineProbe {@@ -66,6 +74,17 @@ function getParsedFont(family: string, style: string): OutlineFont | null {}}+/**+ * True when the font is available AND parseable for glyph-outline extraction —+ * i.e. getGlyphOutlineMetricsSync can produce outlines for it. Availability is+ * currently local (fontManager), but the contract is provider-agnostic so a+ * future remote source can satisfy it. Path-text editing needs this to reflow;+ * without it the text is a baked graphic.+ */+export function hasGlyphOutlines(family: string, style: string): boolean {+ return getParsedFont(family, style) !== null+}+function glyphsForCodePoints(font: OutlineFont, text: string): OutlineGlyph[] {return Array.from(text, (character) => font.charToGlyph(character))}@@ -134,15 +153,32 @@ export function getGlyphOutlineMetricsSync(const font = getParsedFont(family, style)if (!font) return null- const glyphs = glyphsForCodePoints(font, text)- let x = 0- return glyphs.map((glyph) => {- const commands = glyph.getPath(0, 0, fontSize).commands- const advance = glyphAdvanceWidth(font, glyph, fontSize)- const metrics = { commands, x, advance }- x += advance- return metrics- })+ try {+ const positioned: Array<{ glyph: OutlineGlyph; x: number }> = []+ const endX = font.forEachGlyph(text, 0, 0, fontSize, undefined, (glyph, x) => {+ positioned.push({ glyph, x })+ })+ return positioned.map(({ glyph, x }, index) => ({+ commands: glyph.getPath(0, 0, fontSize).commands,+ x,+ // opentype.js applies substitutions, ligatures, GPOS kerning, and default+ // render features in forEachGlyph. Derive each shaped advance from those+ // positions rather than reconstructing it from raw code points.+ advance: (positioned[index + 1]?.x ?? endX) - x+ }))+ } catch {+ // Some fonts use OpenType lookup formats that opentype.js cannot shape yet.+ // Preserve outline editing with the dependency's basic glyph/advance APIs.+ const glyphs = glyphsForCodePoints(font, text)+ let x = 0+ return glyphs.map((glyph) => {+ const commands = glyph.getPath(0, 0, fontSize).commands+ const advance = glyphAdvanceWidth(font, glyph, fontSize)+ const metrics = { commands, x, advance }+ x += advance+ return metrics+ })+ }}export async function probeGlyphOutlineCommands(diff --git a/packages/core/src/text/path/fitting.ts b/packages/core/src/text/path/fitting.tsnew file mode 100644index 000000000..ebbaaa728--- /dev/null+++ b/packages/core/src/text/path/fitting.ts@@ -0,0 +1,116 @@+import type { DerivedTextGlyph, TextPathData } from '@open-pencil/scene-graph'+import type { Rect } from '@open-pencil/scene-graph/primitives'++import { sampleTextPath } from './sampling'++/**+ * Node-local box that maps the layout path onto the glyph baselines.+ *+ * `SceneNode.textPathBox` is ~4% too small (import maps the path onto the node's+ * ORIGINAL Figma box, not its own normalizedSize space), so a path sampled from+ * it sits ~30px off the lettering. This recovers the box that lands the path ON+ * the glyphs, for display (the selection overlay) without disturbing the+ * import/reflow use of textPathBox.+ *+ * It fits from `box0` (the node's current textPathBox) so the box **aspect ratio+ * is preserved** — after a non-uniform resize textPathBox is an oval, and the+ * overlay must oval with it (using normalizedSize would force a circle). Only a+ * uniform scale (about box0's centre) + translation are fit — a 3-DOF similarity+ * that corrects the ~4% and repositions without over-fitting the arc. Returns+ * null with no glyphs, a degenerate box, or an unsampleable path.+ */+const fittedBoxCache = new WeakMap<object, { box0: Rect; result: Rect | null }>()++export function fitTextPathBoxToGlyphs(+ data: TextPathData,+ box0: Rect,+ glyphs: readonly Pick<DerivedTextGlyph, 'x' | 'y'>[] | null | undefined+): Rect | null {+ if (!glyphs?.length) return null+ // The selection overlay calls this every repaint (pan/zoom) with the node's+ // stable textPathBox/glyphs references, but the 8-iteration fit is unchanged+ // until resize/reflow produces new objects. Memoize on the glyphs array (the+ // WeakMap entry drops when that array is replaced) and re-check box0 identity.+ const memo = fittedBoxCache.get(glyphs)+ if (memo && memo.box0 === box0) return memo.result+ const result = computeFittedBox(data, box0, glyphs)+ fittedBoxCache.set(glyphs, { box0, result })+ return result+}++function computeFittedBox(+ data: TextPathData,+ box0: Rect,+ glyphs: readonly Pick<DerivedTextGlyph, 'x' | 'y'>[]+): Rect | null {+ const bw = box0.width+ const bh = box0.height+ if (!(bw > 0) || !(bh > 0)) return null+ const ref = sampleTextPath(data, box0)+ if (!ref) return null++ const cx0 = box0.x + bw / 2+ const cy0 = box0.y + bh / 2+ let c = 1+ let tx = 0+ let ty = 0+ for (let iter = 0; iter < 8; iter++) {+ // Least-squares uniform-scale + translation over the current correspondence:+ // a transformed ref point is P = centre + c·(ref − centre) + t, so minimising+ // |g − P|² gives c = cov(a,b)/var(a), t = mean(b) − c·mean(a).+ let saa = 0+ let sab = 0+ let sax = 0+ let say = 0+ let sbx = 0+ let sby = 0+ for (const g of glyphs) {+ let bestD = Infinity+ let ai = 0+ let aj = 0+ for (let i = 0; i < ref.xs.length; i++) {+ const px = cx0 + c * (ref.xs[i] - cx0) + tx+ const py = cy0 + c * (ref.ys[i] - cy0) + ty+ const d = (px - g.x) ** 2 + (py - g.y) ** 2+ if (d < bestD) {+ bestD = d+ ai = ref.xs[i] - cx0+ aj = ref.ys[i] - cy0+ }+ }+ const bx = g.x - cx0+ const by = g.y - cy0+ saa += ai * ai + aj * aj+ sab += ai * bx + aj * by+ sax += ai+ say += aj+ sbx += bx+ sby += by+ }+ const n = glyphs.length+ const aBarX = sax / n+ const aBarY = say / n+ const bBarX = sbx / n+ const bBarY = sby / n+ const varA = saa - n * (aBarX * aBarX + aBarY * aBarY)+ const covAB = sab - n * (aBarX * bBarX + aBarY * bBarY)+ // Clamp before deriving translation so a degenerate fit can't pair an+ // unbounded scale's tx/ty with the clamped scale and shift the box.+ const fittedC = varA > 1e-6 ? covAB / varA : c+ const newC = Math.min(Math.max(fittedC, 0.5), 2)+ const newTx = bBarX - newC * aBarX+ const newTy = bBarY - newC * aBarY+ const converged =+ Math.abs(newC - c) < 1e-4 && Math.abs(newTx - tx) < 0.05 && Math.abs(newTy - ty) < 0.05+ c = newC+ tx = newTx+ ty = newTy+ if (converged) break+ }+ return {+ x: cx0 - (bw * c) / 2 + tx,+ y: cy0 - (bh * c) / 2 + ty,+ width: bw * c,+ height: bh * c+ }+}diff --git a/packages/core/src/text/path/index.ts b/packages/core/src/text/path/index.tsnew file mode 100644index 000000000..0d9eee27b--- /dev/null+++ b/packages/core/src/text/path/index.ts@@ -0,0 +1,10 @@+import type { SceneNode, TextPathData } from '@open-pencil/scene-graph'++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.tsnew file mode 100644index 000000000..d076f64d0--- /dev/null+++ b/packages/core/src/text/path/layout.ts@@ -0,0 +1,133 @@+import type { DerivedTextGlyph, TextPathData } from '@open-pencil/scene-graph'+import type { Rect } from '@open-pencil/scene-graph/primitives'++import { nearestArcPoint, pointAtArc, sampleTextPath, type PathPoint } from './sampling'++// --- Calibrated layout ---++export interface PathTextLayout {+ /** Arc position of glyph 0 as a fraction of total length. */+ anchor: number+ /** Per-glyph arc offset from glyph 0, px (constant at constant font size). */+ deltas: number[]+ /** Per-glyph signed offset along the left normal (-ty, tx), px. */+ offsets: number[]+ /** Per-glyph rotation minus the tangent-derived base rotation, radians. */+ phases: number[]+}++const TWO_PI = Math.PI * 2++function normalizeAngle(a: number): number {+ let r = a % TWO_PI+ if (r > Math.PI) r -= TWO_PI+ if (r < -Math.PI) r += TWO_PI+ return r+}++/** Rotation implied by the path direction at a point (paint negates it). */+function baseRotation(p: PathPoint, forward: boolean): number {+ const tx = forward ? p.tx : -p.tx+ const ty = forward ? p.ty : -p.ty+ return -Math.atan2(ty, tx)+}++/**+ * Measure layout parameters from the node's current baked glyph baselines.+ * Reflowing with these on the same box reproduces the input exactly.+ */+export function calibratePathTextLayout(+ glyphs: DerivedTextGlyph[],+ data: TextPathData,+ box: Rect+): PathTextLayout | null {+ if (glyphs.length === 0) return null+ const path = sampleTextPath(data, box)+ if (!path) return null++ const positions: PathPoint[] = []+ const offsets: number[] = []+ const phases: number[] = []+ for (const g of glyphs) {+ const p = nearestArcPoint(path, g.x, g.y)+ // Signed distance along the left normal (-ty, tx).+ const off = (g.x - p.x) * -p.ty + (g.y - p.y) * p.tx+ positions.push(p)+ offsets.push(off)+ phases.push(normalizeAngle((g.rotation ?? 0) - baseRotation(p, data.forward)))+ }++ const s0 = positions[0].s+ const deltas = positions.map((p) => {+ let d = p.s - s0+ // On closed paths pick the wrap that matches travel direction.+ if (path.closed) {+ if (data.forward && d < -path.length / 2) d += path.length+ if (!data.forward && d > path.length / 2) d -= path.length+ }+ return d+ })+ return { anchor: s0 / path.length, deltas, offsets, phases }+}++/**+ * Re-place glyphs along the path scaled into `box` at constant font size:+ * the anchor keeps its normalized arc position, per-glyph arc deltas and+ * normal offsets are preserved, rotation follows the new local tangent.+ */+/**+ * Lay out fresh glyph outlines along the path with a pen walk: glyph 0 sits+ * 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.+ */+export function layoutPathTextFromAdvances(+ data: TextPathData,+ box: Rect,+ anchor: number,+ offset: number,+ glyphSources: Array<{ commandsBlob: Uint8Array; fontSize: number; advance: number }>+): DerivedTextGlyph[] | null {+ const path = sampleTextPath(data, box)+ if (!path) return null+ const dir = data.forward ? 1 : -1+ let s = anchor * path.length+ return glyphSources.map((src) => {+ const p = pointAtArc(path, s)+ s += dir * src.advance * src.fontSize+ return {+ commandsBlob: src.commandsBlob,+ x: p.x + -p.ty * offset,+ y: p.y + p.tx * offset,+ fontSize: src.fontSize,+ rotation: normalizeAngle(baseRotation(p, data.forward))+ }+ })+}++export function reflowPathTextGlyphs(+ glyphs: DerivedTextGlyph[],+ data: TextPathData,+ layout: PathTextLayout,+ box: Rect+): DerivedTextGlyph[] | null {+ if (glyphs.length !== layout.deltas.length) return null+ const path = sampleTextPath(data, box)+ if (!path) return null+ const s0 = layout.anchor * path.length+ return glyphs.map((g, i) => {+ const p = pointAtArc(path, s0 + layout.deltas[i])+ const off = layout.offsets[i]+ return {+ ...g,+ commandsBlob: new Uint8Array(g.commandsBlob),+ x: p.x + -p.ty * off,+ y: p.y + p.tx * off,+ rotation: normalizeAngle(baseRotation(p, data.forward) + layout.phases[i]),+ // Reflow replaces geometric scaling entirely.+ scaleX: undefined,+ scaleY: undefined+ }+ })+}diff --git a/packages/core/src/text/path/sampling.ts b/packages/core/src/text/path/sampling.tsnew file mode 100644index 000000000..2ed1c7999--- /dev/null+++ b/packages/core/src/text/path/sampling.ts@@ -0,0 +1,99 @@+import { svgPathProperties } from 'svg-path-properties'++import type { TextPathData } from '@open-pencil/scene-graph'+import type { Rect } from '@open-pencil/scene-graph/primitives'++type PathProperties = InstanceType<typeof svgPathProperties>++export interface SampledPath {+ properties: PathProperties+ xs: Float64Array+ ys: Float64Array+ /** Arc lengths corresponding to the sampled points. */+ cum: Float64Array+ length: number+ closed: boolean+}++export interface PathPoint {+ x: number+ y: number+ /** Unit tangent along increasing arc length. */+ tx: number+ ty: number+ s: number+}++function svgPath(data: TextPathData, box: Rect): string | 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++ 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+ }++ return commands.length > 0 ? commands.join(' ') : null+}++/** Build headless SVG path metrics for the vector network mapped into `box`. */+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+ }+ return { properties, xs, ys, cum, length, closed }+}++/** Node-local point and unit tangent at absolute arc length `sIn`. */+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 }+}++/** Closest sampled/refined path point, used to calibrate imported glyph baselines. */+export function nearestArcPoint(path: SampledPath, px: number, py: number): PathPoint {+ let best = 0+ let bestD = Infinity+ for (let index = 0; index < path.xs.length; index++) {+ const d = (path.xs[index] - px) ** 2 + (path.ys[index] - py) ** 2+ if (d < bestD) {+ bestD = d+ best = index+ }+ }+ const point = pointAtArc(path, path.cum[best])+ const along = (px - point.x) * point.tx + (py - point.y) * point.ty+ return pointAtArc(path, point.s + along)+}diff --git a/packages/core/src/text/path/selection.ts b/packages/core/src/text/path/selection.tsnew file mode 100644index 000000000..d9cae52d7--- /dev/null+++ b/packages/core/src/text/path/selection.ts@@ -0,0 +1,127 @@+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/docs/reference/figma-compatibility.md b/packages/docs/reference/figma-compatibility.mdindex 23baa74de..41fa8311e 100644--- a/packages/docs/reference/figma-compatibility.md+++ b/packages/docs/reference/figma-compatibility.md@@ -80,6 +80,7 @@ Feature-by-feature comparison of Figma Design capabilities with Open Pencil's cu| Feature | Status | Notes ||---------|--------|-------|| Text tool & inline editing | ✅ | Canvas-native editing, phantom textarea, cursor/selection/word select, drag to select, double/triple-click, rich text style runs (<kbd>⌘</kbd><kbd>B</kbd> / <kbd>I</kbd> / <kbd>U</kbd>, **S** button) |+| Text on a path | 🟡 | Imports, renders, selects, resizes, edits, and exports Figma `TEXT_PATH`; character editing requires the referenced font's outlines to be available locally || Text rendering (Paragraph API) | ✅ | CanvasKit Paragraph for shaping, line-breaking, metrics || Font loading (system fonts) | ✅ | Inter default, font-kit in Tauri with OnceLock cache + preloading, queryLocalFonts in browser || Font family & weight | ✅ | FontPicker with virtual scroll, search, CSS preview; weight selection in properties panel |diff --git a/packages/fig/src/instance-overrides/component-props/apply.ts b/packages/fig/src/instance-overrides/component-props/apply.tsindex ae3048bfb..4c6540a25 100644--- a/packages/fig/src/instance-overrides/component-props/apply.ts+++ b/packages/fig/src/instance-overrides/component-props/apply.ts@@ -46,8 +46,8 @@ function applyTextProp(props.height = source.heightprops.fills = copyFills(source.fills)props.styleRuns = copyStyleRuns(source.styleRuns)- props.figmaDerivedTextGlyphs = source.figmaDerivedTextGlyphs- ? structuredClone(source.figmaDerivedTextGlyphs)+ props.derivedTextGlyphs = source.derivedTextGlyphs+ ? structuredClone(source.derivedTextGlyphs): undefined}applyPatchAndMark(ctx, childId, { targetId: childId, source: 'component-prop', props }, modified)diff --git a/packages/fig/src/instance-overrides/constraints.ts b/packages/fig/src/instance-overrides/constraints.tsindex d14a06c1e..a32afb7e7 100644--- a/packages/fig/src/instance-overrides/constraints.ts+++ b/packages/fig/src/instance-overrides/constraints.ts@@ -122,7 +122,7 @@ function pinnedPositionUpdates(const verticalPinned = child.verticalConstraint === 'MAX' || child.verticalConstraint === 'CENTER'if (horizontalPinned &&- child.figmaDerivedLayout?.x === undefined &&+ child.derivedLayout?.x === undefined &&!isFieldProtected(ctx.protectedFields, child.id, 'x') &&child.x !== resized.x) {@@ -130,7 +130,7 @@ function pinnedPositionUpdates(}if (verticalPinned &&- child.figmaDerivedLayout?.y === undefined &&+ child.derivedLayout?.y === undefined &&!isFieldProtected(ctx.protectedFields, child.id, 'y') &&child.y !== resized.y) {@@ -147,7 +147,7 @@ function stretchedChildSizeUpdates(const updates: Partial<SceneNode> = {}if (child.horizontalConstraint === 'STRETCH' &&- child.figmaDerivedLayout?.width === undefined &&+ child.derivedLayout?.width === undefined &&!isFieldProtected(ctx.protectedFields, child.id, 'width') &&child.width !== resized.width) {@@ -155,7 +155,7 @@ function stretchedChildSizeUpdates(}if (child.verticalConstraint === 'STRETCH' &&- child.figmaDerivedLayout?.height === undefined &&+ child.derivedLayout?.height === undefined &&!isFieldProtected(ctx.protectedFields, child.id, 'height') &&child.height !== resized.height) {diff --git a/packages/fig/src/instance-overrides/derived-symbol-data/layout.ts b/packages/fig/src/instance-overrides/derived-symbol-data/layout.tsindex bfd3415bf..cb3a84201 100644--- a/packages/fig/src/instance-overrides/derived-symbol-data/layout.ts+++ b/packages/fig/src/instance-overrides/derived-symbol-data/layout.ts@@ -79,8 +79,8 @@ function buildDsdTextUpdates(weight: d.strokeWeight as number}))}- const figmaDerivedTextGlyphs = convertFigmaDerivedTextGlyphs(d.derivedTextData, blobs)- if (figmaDerivedTextGlyphs.length > 0) updates.figmaDerivedTextGlyphs = figmaDerivedTextGlyphs+ const derivedTextGlyphs = convertFigmaDerivedTextGlyphs(d.derivedTextData, blobs)+ if (derivedTextGlyphs.length > 0) updates.derivedTextGlyphs = derivedTextGlyphsreturn updates}@@ -91,13 +91,13 @@ export function buildDsdLayoutUpdates(target: SceneNode): { updates: Partial<SceneNode>; hasSize: boolean } {const updates: Partial<SceneNode> = buildDsdTextUpdates(d, ctx.blobs, target)- const figmaDerivedLayout: NonNullable<SceneNode['figmaDerivedLayout']> = {}+ const derivedLayout: NonNullable<SceneNode['derivedLayout']> = {}if (d.size) {updates.width = d.size.xupdates.height = d.size.y- figmaDerivedLayout.width = d.size.x- figmaDerivedLayout.height = d.size.y+ derivedLayout.width = d.size.x+ derivedLayout.height = d.size.y}if (d.transform) {const transformed = convertFigmaTransformProps({@@ -109,8 +109,8 @@ export function buildDsdLayoutUpdates(updates.rotation = transformed.rotationupdates.flipX = transformed.flipXupdates.flipY = transformed.flipY- figmaDerivedLayout.x = transformed.x- figmaDerivedLayout.y = transformed.y+ derivedLayout.x = transformed.x+ derivedLayout.y = transformed.y} else if (d.size) {const position =preserveTransformedPositionAfterResize(target, d.size.x, d.size.y) ??@@ -118,11 +118,11 @@ export function buildDsdLayoutUpdates(if (position) {updates.x = position.xupdates.y = position.y- figmaDerivedLayout.x = position.x- figmaDerivedLayout.y = position.y+ derivedLayout.x = position.x+ derivedLayout.y = position.y}}- if (Object.keys(figmaDerivedLayout).length > 0) updates.figmaDerivedLayout = figmaDerivedLayout+ if (Object.keys(derivedLayout).length > 0) updates.derivedLayout = derivedLayoutObject.assign(updates, resolveDsdGeometry(d, target, ctx.blobs))return { updates, hasSize: d.size !== undefined }}diff --git a/packages/fig/src/instance-overrides/derived-symbol-data/propagate.ts b/packages/fig/src/instance-overrides/derived-symbol-data/propagate.tsindex 2ba088cb9..98415789a 100644--- a/packages/fig/src/instance-overrides/derived-symbol-data/propagate.ts+++ b/packages/fig/src/instance-overrides/derived-symbol-data/propagate.ts@@ -6,16 +6,16 @@ import type { OverrideContext } from '../types'import { overrideCandidates } from '../utils'function buildSizeOverriddenCloneUpdates(source: SceneNode, clone: SceneNode): Partial<SceneNode> {- if (clone.type !== 'INSTANCE' || !source.figmaDerivedLayout) return {}- const sourceLayout = source.figmaDerivedLayout+ if (clone.type !== 'INSTANCE' || !source.derivedLayout) return {}+ const sourceLayout = source.derivedLayoutreturn {...(sourceLayout.x === undefined ? {} : { x: sourceLayout.x }),...(sourceLayout.y === undefined ? {} : { y: sourceLayout.y }),- figmaDerivedLayout: {+ derivedLayout: {...sourceLayout,- ...clone.figmaDerivedLayout,- x: sourceLayout.x ?? clone.figmaDerivedLayout?.x,- y: sourceLayout.y ?? clone.figmaDerivedLayout?.y+ ...clone.derivedLayout,+ x: sourceLayout.x ?? clone.derivedLayout?.x,+ y: sourceLayout.y ?? clone.derivedLayout?.y}}}@@ -39,11 +39,11 @@ function buildCloneUpdates(if (source.strokeGeometry !== clone.strokeGeometry)updates.strokeGeometry = copyGeometryPaths(source.strokeGeometry)}- if (source.text === clone.text && source.figmaDerivedTextGlyphs) {- updates.figmaDerivedTextGlyphs = structuredClone(source.figmaDerivedTextGlyphs)+ if (source.text === clone.text && source.derivedTextGlyphs) {+ updates.derivedTextGlyphs = structuredClone(source.derivedTextGlyphs)}- if (source.text === clone.text && source.figmaDerivedLayout) {- updates.figmaDerivedLayout = { ...source.figmaDerivedLayout }+ if (source.text === clone.text && source.derivedLayout) {+ updates.derivedLayout = { ...source.derivedLayout }}return updates}@@ -72,8 +72,8 @@ function restoreScaledInstanceLeafBounds() {continue}- const width = child.figmaDerivedLayout?.width- const height = child.figmaDerivedLayout?.height+ const width = child.derivedLayout?.width+ const height = child.derivedLayout?.heightconst restoresDerivedBounds = width !== undefined && height !== undefinedconst restoresImageBounds =!restoresDerivedBounds &&@@ -108,14 +108,14 @@ function thinCloneCrossPosition(!clone.componentId ||!clone.name.endsWith('Divider') ||!clone.parentId ||- clone.figmaDerivedLayout?.x !== undefined ||- clone.figmaDerivedLayout?.y !== undefined+ clone.derivedLayout?.x !== undefined ||+ clone.derivedLayout?.y !== undefined) {return null}const parent = graph.getNode(clone.parentId)const source = graph.getNode(clone.componentId)- const sourceLayout = source?.figmaDerivedLayout+ const sourceLayout = source?.derivedLayoutif (!parent || !source || sourceLayout?.x === undefined || sourceLayout.y === undefined)return nullif (clone.width !== source.width || clone.height !== source.height) return null@@ -130,8 +130,8 @@ function restoreThinCloneCrossPositions(ctx: OverrideContext): void {const crossPosition = thinCloneCrossPosition(ctx.graph, clone)if (!crossPosition) continuectx.graph.updateNode(clone.id, {- figmaDerivedLayout: {- ...clone.figmaDerivedLayout,+ derivedLayout: {+ ...clone.derivedLayout,[crossPosition.axis]: crossPosition.position}})@@ -142,7 +142,7 @@ export function applyGeneratedFreeformStretch(ctx: OverrideContext): void {for (const node of overrideCandidates(ctx.graph, ctx.activeNodeIds)) {if (node.source.format === 'fig' ||- !node.figmaDerivedLayout ||+ !node.derivedLayout ||!node.parentId ||node.layoutPositioning === 'ABSOLUTE') {@@ -153,24 +153,24 @@ export function applyGeneratedFreeformStretch(ctx: OverrideContext): void {!parent ||parent.source.format === 'fig' ||parent.layoutMode !== 'NONE' ||- !parent.figmaDerivedLayout+ !parent.derivedLayout) {continue}const updates: Partial<SceneNode> = {}if (node.horizontalConstraint === 'STRETCH' &&- node.figmaDerivedLayout.width !== undefined &&- node.figmaDerivedLayout.width === parent.figmaDerivedLayout.width+ node.derivedLayout.width !== undefined &&+ node.derivedLayout.width === parent.derivedLayout.width) {- updates.width = node.figmaDerivedLayout.width+ updates.width = node.derivedLayout.width}if (node.verticalConstraint === 'STRETCH' &&- node.figmaDerivedLayout.height !== undefined &&- node.figmaDerivedLayout.height === parent.figmaDerivedLayout.height+ node.derivedLayout.height !== undefined &&+ node.derivedLayout.height === parent.derivedLayout.height) {- updates.height = node.figmaDerivedLayout.height+ updates.height = node.derivedLayout.height}if (Object.keys(updates).length > 0) ctx.graph.updateNode(node.id, updates)}diff --git a/packages/fig/src/instance-overrides/index.ts b/packages/fig/src/instance-overrides/index.tsindex 1bff16baa..b6c49cfab 100644--- a/packages/fig/src/instance-overrides/index.ts+++ b/packages/fig/src/instance-overrides/index.ts@@ -166,8 +166,8 @@ function propagateResolvedChildPlacementClones(}function sameDerivedGlyphSource(- source: SceneNode['figmaDerivedTextGlyphs'],- target: SceneNode['figmaDerivedTextGlyphs']+ source: SceneNode['derivedTextGlyphs'],+ target: SceneNode['derivedTextGlyphs']): boolean {if (source === target) return trueif (!source || !target) return false@@ -200,7 +200,7 @@ function propagateResolvedTextClones(graph: SceneGraph, activeNodeIds?: Set<strisource.height === node.height &&isEqual(source.fills, node.fills) &&isEqual(source.styleRuns, node.styleRuns) &&- sameDerivedGlyphSource(source.figmaDerivedTextGlyphs, node.figmaDerivedTextGlyphs)+ sameDerivedGlyphSource(source.derivedTextGlyphs, node.derivedTextGlyphs)) {continue}@@ -209,11 +209,8 @@ function propagateResolvedTextClones(graph: SceneGraph, activeNodeIds?: Set<striheight: source.height,fills: copyFills(source.fills),styleRuns: copyStyleRuns(source.styleRuns),- figmaDerivedTextGlyphs: source.figmaDerivedTextGlyphs- ? markCopySource(- source.figmaDerivedTextGlyphs,- structuredClone(source.figmaDerivedTextGlyphs)- )+ derivedTextGlyphs: source.derivedTextGlyphs+ ? markCopySource(source.derivedTextGlyphs, structuredClone(source.derivedTextGlyphs)): undefined})}diff --git a/packages/fig/src/instance-overrides/patches/protection.ts b/packages/fig/src/instance-overrides/patches/protection.tsindex 098d18d2e..8a98a2f0f 100644--- a/packages/fig/src/instance-overrides/patches/protection.ts+++ b/packages/fig/src/instance-overrides/patches/protection.ts@@ -15,7 +15,7 @@ export type ProtectedField =| 'y'| 'width'| 'height'- | 'figmaDerivedLayout'+ | 'derivedLayout'| 'fontSize'| 'lineHeight'| 'letterSpacing'@@ -40,7 +40,7 @@ const PROP_TO_PROTECTED_FIELD: Partial<Record<keyof SceneNode, ProtectedField>>y: 'y',width: 'width',height: 'height',- figmaDerivedLayout: 'figmaDerivedLayout',+ derivedLayout: 'derivedLayout',fontSize: 'fontSize',lineHeight: 'lineHeight',letterSpacing: 'letterSpacing',diff --git a/packages/fig/src/instance-overrides/sync/clone-update.ts b/packages/fig/src/instance-overrides/sync/clone-update.tsindex ac39be9fd..3eacdaf77 100644--- a/packages/fig/src/instance-overrides/sync/clone-update.ts+++ b/packages/fig/src/instance-overrides/sync/clone-update.ts@@ -8,7 +8,7 @@ export function cloneInstanceUpdate(return {...copyInstanceComponentProps(source),componentId,- figmaDerivedLayout: source.figmaDerivedLayout ? { ...source.figmaDerivedLayout } : null,+ derivedLayout: source.derivedLayout ? { ...source.derivedLayout } : null,...extra}}diff --git a/packages/fig/src/node-change/basics.ts b/packages/fig/src/node-change/basics.tsindex 72baed541..2483bd0a8 100644--- a/packages/fig/src/node-change/basics.ts+++ b/packages/fig/src/node-change/basics.ts@@ -1,4 +1,5 @@import type { SceneNode } from '@open-pencil/scene-graph'+import type { Matrix } from '@open-pencil/scene-graph/primitives'export function mapToFigmaType(type: SceneNode['type']): string {switch (type) {@@ -50,3 +51,25 @@ export function fractionalPosition(index: number): string {const lastChar = String.fromCharCode(FIRST + (index % BASE))return String.fromCharCode(TILDE).repeat(numTildes) + lastChar}++export function computeExportTransform(node: SceneNode): Matrix {+ const sx = node.flipX ? -1 : 1+ const cos = Math.cos((node.rotation * Math.PI) / 180)+ const sin = Math.sin((node.rotation * Math.PI) / 180)++ const m00 = cos * sx+ const m01 = -sin * sx+ const m10 = sin+ const m11 = cos+ const centerX = node.width / 2+ const centerY = node.height / 2++ return {+ m00,+ m01,+ m02: node.x + centerX - m00 * centerX - m01 * centerY,+ m10,+ m11,+ m12: node.y + centerY - m10 * centerX - m11 * centerY+ }+}diff --git a/packages/fig/src/node-change/convert.ts b/packages/fig/src/node-change/convert.tsindex b2240c90f..cb00def55 100644--- a/packages/fig/src/node-change/convert.ts+++ b/packages/fig/src/node-change/convert.ts@@ -11,10 +11,12 @@ import { convertFigmaDerivedTextGlyphs } from './derived-text-glyphs'import { convertFontFeatures } from './font/features'import { convertFontVariations } from './font/variations'import { convertEffects, convertFills, convertStrokes } from './paint'+import { expandPathTextLayoutBox } from './path/text-layout'import {extractBoundVariables,extractExportSettings,extractLibrarySource,+ extractTextPathBox,extractPluginData,extractPluginRelaunchData,getOpenPencilPluginValue,@@ -30,6 +32,7 @@ import {resolveVectorNetwork,resolveVectorStyleOverrideFills} from './vector-geometry'+import { decodeVectorNetworkBlob, type StyleOverride } from './vector-network'export { convertEffects, convertFills, convertStrokes, setVariableColorResolver } from './paint'export { importStyleRuns } from './style-runs'@@ -61,7 +64,8 @@ import type {ComponentPropertyType,SymbolLink,VariantPropSpec,- VariableModeMap+ VariableModeMap,+ Vector} from '@open-pencil/scene-graph'import type { GUID } from '@open-pencil/scene-graph/primitives'@@ -108,7 +112,9 @@ const NODE_TYPE_MAP: Record<string, NodeType | 'DOCUMENT' | 'VARIABLE'> = {INSTANCE: 'INSTANCE',SYMBOL: 'COMPONENT',CONNECTOR: 'CONNECTOR',- SHAPE_WITH_TEXT: 'SHAPE_WITH_TEXT'+ SHAPE_WITH_TEXT: 'SHAPE_WITH_TEXT',+ // Map to TEXT while retaining a format-neutral text path for rendering/editing.+ TEXT_PATH: 'TEXT'}function mapNodeType(type?: string): NodeType | 'DOCUMENT' | 'VARIABLE' {@@ -314,8 +320,8 @@ type TextProps = Pick<| 'fontFeatures'| 'textTruncation'| 'textDirection'- | 'figmaDerivedLayout'- | 'figmaDerivedTextGlyphs'+ | 'derivedLayout'+ | 'derivedTextGlyphs'>function convertTextDecorationProps(@@ -367,13 +373,13 @@ function convertTextProps(nc: NodeChange, blobs: Uint8Array[]): TextProps {(getOpenPencilPluginValue(nc, TEXT_DIRECTION_PLUGIN_KEY) as| SceneNode['textDirection']| null) || 'AUTO',- figmaDerivedLayout: nc.derivedTextData?.layoutSize+ derivedLayout: nc.derivedTextData?.layoutSize? {width: nc.derivedTextData.layoutSize.x,height: nc.derivedTextData.layoutSize.y}: null,- figmaDerivedTextGlyphs: convertFigmaDerivedTextGlyphs(nc.derivedTextData, blobs)+ derivedTextGlyphs: convertFigmaDerivedTextGlyphs(nc.derivedTextData, blobs)}}@@ -394,7 +400,7 @@ function visibleContainerDerivedLayout(layoutMode: SceneNode['layoutMode'],primaryAxisSizing: SceneNode['primaryAxisSizing'],counterAxisSizing: SceneNode['counterAxisSizing']-): SceneNode['figmaDerivedLayout'] | undefined {+): SceneNode['derivedLayout'] | undefined {const hasHugAxis = primaryAxisSizing === 'HUG' || counterAxisSizing === 'HUG'const hasVisiblePaint =(nc.fillPaints?.some((paint) => paint.visible !== false) ?? false) ||@@ -443,11 +449,11 @@ function convertLayoutProps(| 'strokesIncludedInLayout'| 'layoutDirection'> &- Partial<Pick<SceneNode, 'figmaDerivedLayout'>> {+ Partial<Pick<SceneNode, 'derivedLayout'>> {const layoutMode = mapStackMode(nc.stackMode)const primaryAxisSizing = mapStackSizing(nc.stackPrimarySizing)const counterAxisSizing = mapStackSizing(nc.stackCounterSizing)- const figmaDerivedLayout = visibleContainerDerivedLayout(+ const derivedLayout = visibleContainerDerivedLayout(nc,layoutMode,primaryAxisSizing,@@ -475,7 +481,7 @@ function convertLayoutProps((getOpenPencilPluginValue(nc, LAYOUT_DIRECTION_PLUGIN_KEY) as| SceneNode['layoutDirection']| null) || 'AUTO',- ...(figmaDerivedLayout ? { figmaDerivedLayout } : {})+ ...(derivedLayout ? { derivedLayout } : {})}}@@ -507,6 +513,39 @@ function convertLayoutGrids(value: unknown): LayoutGrid[] {return Array.isArray(value) ? structuredClone(value as LayoutGrid[]) : []}+function convertTextPathData(nc: NodeChange, blobs: Uint8Array[]): SceneNode['textPathData'] {+ if (nc.type !== 'TEXT_PATH') return null+ const vectorData = nc.vectorData as+ | {+ vectorNetworkBlob?: number+ normalizedSize?: Vector+ styleOverrideTable?: StyleOverride[]+ }+ | undefined+ const blobIndex = vectorData?.vectorNetworkBlob+ const normalizedSize = vectorData?.normalizedSize+ if (+ typeof blobIndex !== 'number' ||+ !normalizedSize ||+ normalizedSize.x <= 0 ||+ normalizedSize.y <= 0+ ) {+ return null+ }+ const blob = blobs[blobIndex]+ const textPathStart = nc.textPathStart as { tValue?: number; forward?: boolean } | undefined+ try {+ return {+ network: decodeVectorNetworkBlob(blob, vectorData.styleOverrideTable),+ normalizedSize: { x: normalizedSize.x, y: normalizedSize.y },+ tValue: textPathStart?.tValue ?? 0,+ forward: textPathStart?.forward ?? true+ }+ } catch {+ return null+ }+}+function convertVectorAndStrokeProps(nc: NodeChange, blobs: Uint8Array[]) {const vectorNetwork = resolveVectorNetwork(nc, blobs)const strokeCap = getVectorStrokeCap(nc, vectorNetwork)@@ -578,8 +617,9 @@ export function nodeChangeToProps(const nodeType = resolveNodeType(nc)const vectorAndStrokeProps = convertVectorAndStrokeProps(nc, blobs)+ const textPathData = convertTextPathData(nc, blobs)- return {+ const props: Partial<SceneNode> & { nodeType: NodeType | 'DOCUMENT' | 'VARIABLE' } = {nodeType,name: nc.name ?? nodeType,source: extractSourceMetadata(nc, blobs),@@ -635,6 +675,24 @@ export function nodeChangeToProps(componentPropertyValues: extractComponentPropertyValues(nc),...extractComponentMetadata(nc)}++ // See path/text-layout.ts — expand the layout box before node creation so+ // clipsContent parents don't shave overflowing path lettering at first paint.+ expandPathTextLayoutBox(props, textPathData)+ // A saved OpenPencil doc carries the true textPathBox (reflow may have+ // scaled it); the expand-time reconstruction is only right for pristine+ // Figma exports. Plugin box is in pre-expansion local coords — expand's+ // shift is textPathBox.x/y by construction, so re-home it.+ const pluginBox = extractTextPathBox(nc)+ if (pluginBox && props.textPathBox) {+ props.textPathBox = {+ x: pluginBox.x + props.textPathBox.x,+ y: pluginBox.y + props.textPathBox.y,+ width: pluginBox.width,+ height: pluginBox.height+ }+ }+ return props}const COMPONENT_PROP_TYPE_MAP: Record<string, ComponentPropertyType> = {diff --git a/packages/fig/src/node-change/derived-text-glyphs.ts b/packages/fig/src/node-change/derived-text-glyphs.tsindex 7a55bc48f..5b000fe14 100644--- a/packages/fig/src/node-change/derived-text-glyphs.ts+++ b/packages/fig/src/node-change/derived-text-glyphs.ts@@ -1,10 +1,15 @@import type { NodeChange } from '@open-pencil/kiwi/fig/codec'-import type { FigmaDerivedTextGlyph } from '@open-pencil/scene-graph'+import type { DerivedTextGlyph } from '@open-pencil/scene-graph'+/**+ * Resolve Figma derivedTextData.glyphs into scene glyphs.+ * Dropping `rotation` used to flatten path text to axis-aligned scribbles;+ * units are radians (schema `float`, DomeSticker values ≈ -1.75…-0.5).+ */export function convertFigmaDerivedTextGlyphs(derivedTextData: NodeChange['derivedTextData'],blobs: Uint8Array[]-): FigmaDerivedTextGlyph[] {+): DerivedTextGlyph[] {return (derivedTextData?.glyphs ?? []).map((glyph) => {if (glyph.commandsBlob === undefined) return null@@ -12,7 +17,8 @@ export function convertFigmaDerivedTextGlyphs(commandsBlob: blobs[glyph.commandsBlob],x: glyph.position.x,y: glyph.position.y,- fontSize: glyph.fontSize+ fontSize: glyph.fontSize,+ rotation: glyph.rotation}}).filter((glyph): glyph is NonNullable<typeof glyph> => !!glyph)diff --git a/packages/fig/src/node-change/export-node.ts b/packages/fig/src/node-change/export-node.tsindex de9101bdc..1596b9547 100644--- a/packages/fig/src/node-change/export-node.ts+++ b/packages/fig/src/node-change/export-node.ts@@ -15,6 +15,7 @@ import { bytesToHex } from './bytes'import {applyExportSettingsPluginData,applyLibrarySourcePluginData,+ applyTextPathBoxPluginData,mergePluginData,NODE_TYPE_PLUGIN_KEY,serializePluginRelaunchData,@@ -436,7 +437,6 @@ const RAW_FIELDS_OVERRIDE_BLOCKLIST = new Set(['derivedSymbolData','derivedSymbolDataLayoutVersion','sourceLibraryKey',- // Normalized constraints are authoritative, including when an edit clears them.'minSize','maxSize',// Variable consumption maps: explicit serialization always sets these when@@ -446,12 +446,66 @@ const RAW_FIELDS_OVERRIDE_BLOCKLIST = new Set(['parameterConsumptionMap'])+/**+ * Resize reflowed this path-text node (glyphs regenerated, strokeGeometry+ * cleared). The raw strokeGeometry silhouettes are still at the pre-resize+ * size, so exporting them would paint stale full-size outlines.+ */+function isReflowedStrokedPathText(node: SceneNode): boolean {+ if (node.type !== 'TEXT' || node.textPathData === null) return false+ if ((node.derivedTextGlyphs?.length ?? 0) === 0 || node.textPathBox === null) return false+ if (node.strokeGeometry.length !== 0) return false+ // Only when the node has stroke paint but its baked silhouettes were+ // cleared by reflow (see resize.ts). Fill-only path text (no stroke paint,+ // so strokeGeometry is always empty) is untouched and keeps its raw+ // derivedTextData verbatim.+ //+ // This must key off live node.strokes, not rawNodeFields.strokeGeometry:+ // clearResizedRawGeometry (resize.ts) deletes that raw field on every+ // resize commit, so it's already gone by the time a reflowed node reaches+ // export and can never be used to detect reflow here.+ return node.strokes.length > 0+}++/**+ * An imported path-text node that was edited after import — moving/rotating+ * clears rawTransform (see clearEditedSourceMetadata), so the transform + size+ * are recomputed from the node's post-expand box (exportNodeTransform /+ * exportNodeSize). But the raw derivedTextData + baked silhouettes are still the+ * PRE-expand (un-shifted) payload — exporting them against the shifted box+ * re-triggers the import expand on reimport and drifts the node. Rebuild+ * derivedTextData from the live (shifted) glyphs and re-derive silhouettes,+ * exactly like the reflow path. rawTransform === null is the "edited" signal;+ * pristine nodes keep rawTransform and their raw payload verbatim.+ */+function isEditedPathText(node: SceneNode): boolean {+ return (+ node.type === 'TEXT' &&+ node.textPathData !== null &&+ // "Edited" = the raw transform no longer backs the node. Editing does not+ // clear source.fig.rawTransform directly; effectiveFigmaSourcePayload+ // derives it from source.editedFields, so ask that, not the raw field.+ effectiveFigmaSourcePayload(node).rawTransform === null &&+ (node.derivedTextGlyphs?.length ?? 0) > 0+ )+}+function applyRawFigmaNodeFields(context: SceneNodeToKiwiContext,node: SceneNode,nc: KiwiNodeChange): void {- const materialized = materializeFigmaPayload(effectiveFigmaRawNodeFields(node), context.blobs, {+ let rawFields = effectiveFigmaRawNodeFields(node)+ if (isReflowedStrokedPathText(node) || isEditedPathText(node)) {+ // Strip before materializing so the stale blobs never enter the file:+ // silhouettes are re-derived from glyphs by Figma/reimport, and+ // derivedTextData was rebuilt from the reflowed glyphs by+ // serializeTextProps (raw would clobber the new positions).+ rawFields = { ...rawFields }+ delete rawFields.strokeGeometry+ delete rawFields.derivedTextData+ }+ const materialized = materializeFigmaPayload(rawFields, context.blobs, {blobIndexByHex: context.blobIndexByHex,includePaintVariables: true,includeVariableMaps: true@@ -691,8 +745,16 @@ function applyComponentMetadata(}function exportNodeSize(node: SceneNode): Vector {- const rawSize = effectiveFigmaSourcePayload(node).rawSize- return rawSize ? { ...rawSize } : { x: node.width, y: node.height }+ // rawSize and rawTransform are a matched pair describing the ORIGINAL Figma+ // box. Once the transform no longer backs the node, exportNodeTransform+ // recomputes it from node dims via computeExportTransform; pairing that with+ // 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 }}function exportNodeTransform(context: SceneNodeToKiwiContext, node: SceneNode): Matrix {@@ -823,6 +885,17 @@ function applyNodeVisualProps(if (!node.autoRename) nc.autoRename = false}+/**+ * Import maps TEXT_PATH → TEXT. Re-emit Kiwi type 41 only while path fidelity+ * remains (materialized path data + baked glyphs). After an edit that cannot+ * reflow glyphs, invalidation clears the path data so export falls back to TEXT.+ */+function exportKiwiNodeType(node: SceneNode, context: SceneNodeToKiwiContext): string {+ const isPathText =+ node.textPathData !== null && node.type === 'TEXT' && (node.derivedTextGlyphs?.length ?? 0) > 0+ return isPathText ? 'TEXT_PATH' : context.mapToFigmaType(node.type)+}+export function sceneNodeToKiwiWithContext(node: SceneNode,parentGuid: GUID,@@ -837,13 +910,15 @@ export function sceneNodeToKiwiWithContext(const strokePaints = createStrokePaints(context, node)+ const exportType = exportKiwiNodeType(node, context)+const nc: KiwiNodeChange = {guid,parentIndex: {guid: parentGuid,position: node.source.orderKey ?? context.fractionalPosition(childIndex)},- type: context.mapToFigmaType(node.type),+ type: exportType,name: node.name,visible: node.visible,opacity: node.opacity,@@ -887,6 +962,7 @@ export function sceneNodeToKiwiWithContext(applyExportSettingsPluginData(node)applyLibrarySourcePluginData(node)+ applyTextPathBoxPluginData(node)const pluginData = mergePluginData(node.pluginData)if (pluginData.length > 0) nc.pluginData = pluginDataif (node.pluginRelaunchData.length > 0) {diff --git a/packages/fig/src/node-change/export-runtime.ts b/packages/fig/src/node-change/export-runtime.tsindex 48879195a..c94591d6a 100644--- a/packages/fig/src/node-change/export-runtime.ts+++ b/packages/fig/src/node-change/export-runtime.ts@@ -1,4 +1,4 @@-import type { OutlineCommand } from './path-commands'+import type { OutlineCommand } from './path/commands'export interface FigGlyphOutlineMetric {commands: OutlineCommand[]diff --git a/packages/fig/src/node-change/index.ts b/packages/fig/src/node-change/index.tsindex a7792438f..899f30b77 100644--- a/packages/fig/src/node-change/index.ts+++ b/packages/fig/src/node-change/index.ts@@ -8,7 +8,7 @@ export * from './font/features'export * from './font/style'export * from './font/variations'export * from './paint'-export * from './path-commands'+export * from './path/commands'export * from './plugin-data'export * from './serialize'export * from './style-refs'diff --git a/packages/fig/src/node-change/path-commands.ts b/packages/fig/src/node-change/path/commands.tssimilarity index 66%rename from packages/fig/src/node-change/path-commands.tsrename to packages/fig/src/node-change/path/commands.tsindex 782a87e10..ba9729bf4 100644--- a/packages/fig/src/node-change/path-commands.ts+++ b/packages/fig/src/node-change/path/commands.ts@@ -1,3 +1,4 @@+import { transformGeometryBlob } from '@open-pencil/scene-graph/copy'export interface OutlineCommand {type: stringx?: number@@ -76,3 +77,26 @@ export function encodePathCommandsBlob(commands: OutlineCommand[], scale = 1): Ureturn new Uint8Array(bytes)}++/**+ * Bake accumulated resize scale into a glyph blob (font units). The Kiwi+ * Glyph schema has no scaleX/scaleY, so exporting them any other way loses+ * the scale on reload — positions and strokeGeometry persist scaled while+ * glyph shapes revert, garbling path text (DomeSticker save/reopen bug).+ * Paint order is T·S·R(-theta)·F (see drawDerivedText); rewriting points as+ * p' = F^-1·R(theta)·S·R(-theta)·F·p lets the same world transform hold without S.+ */+export function bakeGlyphScale(+ blob: Uint8Array,+ scaleX: number,+ scaleY: number,+ rotation: number+): Uint8Array {+ if (scaleX === 1 && scaleY === 1) return blob+ const cos = Math.cos(rotation)+ const sin = Math.sin(rotation)+ const m00 = scaleX * cos * cos + scaleY * sin * sin+ const m01 = (scaleY - scaleX) * sin * cos+ const m11 = scaleX * sin * sin + scaleY * cos * cos+ return transformGeometryBlob(blob, m00, m01, m01, m11)+}diff --git a/packages/fig/src/node-change/path/text-layout.ts b/packages/fig/src/node-change/path/text-layout.tsnew file mode 100644index 000000000..1b8e9cc60--- /dev/null+++ b/packages/fig/src/node-change/path/text-layout.ts@@ -0,0 +1,119 @@+import type {+ DerivedTextGlyph,+ GeometryPath,+ SceneNode,+ TextPathData+} from '@open-pencil/scene-graph'+import { transformGeometryPaths } from '@open-pencil/scene-graph/copy'+import { geometryBlobBounds } from '@open-pencil/scene-graph/geometry'++/**+ * Shift geometry command blobs in node space. Used when we grow the layout box+ * left/top so content must move with the new origin (parent-space art stays put).+ *+ * Delegates to transformGeometryPaths so CLOSE (command 0) and path-level paint+ * metadata stay intact — a hand-rolled walker that broke on CLOSE left stroke+ * silhouettes only partially shifted (DomeSticker white outline desynced).+ */+function translateGeometryPaths(paths: GeometryPath[], dx: number, dy: number): GeometryPath[] {+ if (dx === 0 && dy === 0) return paths+ return transformGeometryPaths(paths, 1, 0, 0, 1, dx, dy)+}++interface BoxOverflow {+ left: number+ top: number+ right: number+ bottom: number+}++/** How far painted geometry + glyph pads spill past the width×height box. */+function measurePathTextOverflow(+ props: Partial<SceneNode>,+ width: number,+ height: number+): BoxOverflow {+ const paths: GeometryPath[] = [...(props.fillGeometry ?? []), ...(props.strokeGeometry ?? [])]+ const geom = paths.length > 0 ? geometryBlobBounds(paths) : null++ let minX = geom?.x ?? 0+ let minY = geom?.y ?? 0+ let maxX = geom ? geom.x + geom.width : width+ let maxY = geom ? geom.y + geom.height : height++ // Baselines only — pad with fontSize so ascent/side-bearings are covered.+ for (const g of (props.derivedTextGlyphs as DerivedTextGlyph[] | null) ?? []) {+ const pad = g.fontSize || 0+ minX = Math.min(minX, g.x - pad * 0.25)+ minY = Math.min(minY, g.y - pad)+ maxX = Math.max(maxX, g.x + pad)+ maxY = Math.max(maxY, g.y + pad * 0.35)+ }++ const pad = 1+ return {+ left: Math.max(0, -minX + (minX < 0 ? pad : 0)),+ top: Math.max(0, -minY + (minY < 0 ? pad : 0)),+ right: Math.max(0, maxX - width + (maxX > width ? pad : 0)),+ bottom: Math.max(0, maxY - height + (maxY > height ? pad : 0))+ }+}++/** Shift local geometry + glyph baselines by (dx, dy) after the origin moved. */+function shiftPathTextGeometry(props: Partial<SceneNode>, dx: number, dy: number): void {+ if (props.strokeGeometry && props.strokeGeometry.length > 0) {+ props.strokeGeometry = translateGeometryPaths(props.strokeGeometry, dx, dy)+ }+ if (props.fillGeometry && props.fillGeometry.length > 0) {+ props.fillGeometry = translateGeometryPaths(props.fillGeometry, dx, dy)+ }+ if (props.derivedTextGlyphs?.length) {+ props.derivedTextGlyphs = props.derivedTextGlyphs.map((g) => ({+ ...g,+ x: g.x + dx,+ y: g.y + dy+ }))+ }+}++/**+ * Figma often sizes the TEXT_PATH layout box tighter than the painted outlines+ * (DomeSticker strokeGeometry minX ≈ -37). That is fine inside Figma's own+ * painter, but our frames honor `clipsContent` against child *layout* extents+ * during resize/cull — overflowing lettering on the left/bottom got clipped.+ *+ * Grow width/height to cover strokeGeometry + glyph pads, then shift local+ * geometry by (dx, dy) and compensate with x/y so the design does not jump.+ */+export function expandPathTextLayoutBox(+ props: Partial<SceneNode> & { nodeType: string },+ data: TextPathData | null+): void {+ if (props.nodeType !== 'TEXT' || !data) return+ props.textPathData = data++ const width = props.width ?? 0+ const height = props.height ?? 0+ // The layout path (rawNodeFields vectorData) maps onto the ORIGINAL Figma+ // box; anchor it before the box grows so reflow can evaluate the path in+ // current node-local coordinates.+ props.textPathBox = { x: 0, y: 0, width, height }+ const overflow = measurePathTextOverflow(props, width, height)+ if (overflow.left === 0 && overflow.top === 0 && overflow.right === 0 && overflow.bottom === 0) {+ return+ }++ // New origin is (oldOrigin - (overflowLeft, overflowTop)) in parent space;+ // add the same delta to local geometry so world positions are unchanged.+ const dx = overflow.left+ const dy = overflow.top+ props.x = (props.x ?? 0) - dx+ props.y = (props.y ?? 0) - dy+ props.width = width + overflow.left + overflow.right+ props.height = height + overflow.top + overflow.bottom++ if (dx !== 0 || dy !== 0) {+ props.textPathBox = { x: dx, y: dy, width, height }+ shiftPathTextGeometry(props, dx, dy)+ }+}diff --git a/packages/fig/src/node-change/plugin-data.ts b/packages/fig/src/node-change/plugin-data.tsindex 166557b5c..7457a2f67 100644--- a/packages/fig/src/node-change/plugin-data.ts+++ b/packages/fig/src/node-change/plugin-data.ts@@ -8,6 +8,7 @@ import {type PluginRelaunchDataEntry,type SceneNode} from '@open-pencil/scene-graph'+import type { Rect } from '@open-pencil/scene-graph/primitives'import { readEffectiveFigmaRawField } from '../source-metadata'import { resolveVariableConsumptionEntry } from './variable-bindings'@@ -18,6 +19,7 @@ export const LAYOUT_DIRECTION_PLUGIN_KEY = 'layoutDirection'export const NODE_TYPE_PLUGIN_KEY = 'nodeType'export const BOUND_VARIABLES_PLUGIN_KEY = 'boundVariables'export const EXPORT_SETTINGS_PLUGIN_KEY = 'exportSettings'+export const TEXT_PATH_BOX_PLUGIN_KEY = 'textPathBox'export const LIBRARY_SOURCE_PLUGIN_KEY = 'librarySource'export const ENABLED_LIBRARIES_PLUGIN_KEY = 'enabledLibraries'@@ -53,6 +55,43 @@ export function applyExportSettingsPluginData(upsertPluginData(node, EXPORT_SETTINGS_PLUGIN_KEY, JSON.stringify(node.exportSettings))}+/**+ * textPathBox is OpenPencil-only state (the node-local rect the TEXT_PATH+ * 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.+ */+export function applyTextPathBoxPluginData(node: {+ textPathBox: Rect | null+ pluginData: PluginDataEntry[]+}): void {+ if (!node.textPathBox) return+ upsertPluginData(node, TEXT_PATH_BOX_PLUGIN_KEY, JSON.stringify(node.textPathBox))+}++export function extractTextPathBox(nc: NodeChange): Rect | null {+ const value = getOpenPencilPluginValue(nc, TEXT_PATH_BOX_PLUGIN_KEY)+ if (!value) return null+ try {+ const parsed = JSON.parse(value) as Partial<Rect> | null+ if (!parsed || typeof parsed !== 'object') return null+ const { x, y, width, height } = parsed+ if (+ typeof x !== 'number' ||+ typeof y !== 'number' ||+ typeof width !== 'number' ||+ typeof height !== 'number'+ ) {+ return null+ }+ if (!Number.isFinite(x + y + width + height) || width <= 0 || height <= 0) return null+ return { x, y, width, height }+ } catch {+ return null+ }+}+function hasOpenPencilExportSettingsPluginData(pluginData: PluginDataEntry[]): boolean {return pluginData.some((entry) => entry.pluginId === OPEN_PENCIL_PLUGIN_ID && entry.key === EXPORT_SETTINGS_PLUGIN_KEYdiff --git a/packages/fig/src/node-change/serialize.ts b/packages/fig/src/node-change/serialize.tsindex b0ab2918e..084933a2f 100644--- a/packages/fig/src/node-change/serialize.ts+++ b/packages/fig/src/node-change/serialize.ts@@ -1,7 +1,7 @@import { normalizeFontFamily, weightToStyle } from '@open-pencil/scene-graph'import { effectiveFigmaRawNodeFields } from '../source-metadata'-import { fractionalPosition, mapToFigmaType } from './basics'+import { computeExportTransform, fractionalPosition, mapToFigmaType } from './basics'import { bytesToHex } from './bytes'import { VARIABLE_BINDING_FIELDS } from './convert'import { buildDerivedTextData as buildSharedDerivedTextData } from './derived-text-data'@@ -9,7 +9,7 @@ import { EMPTY_EXPORT_RUNTIME, type FigNodeChangeExportRuntime } from './export-import { applyFontFeaturesToKiwi } from './font/features'import { weightToFigmaStyle } from './font/style'import { fillToKiwiPaint, safeColor } from './paint'-import { encodePathCommandsBlob } from './path-commands'+import { bakeGlyphScale, encodePathCommandsBlob } from './path/commands'import {BOUND_VARIABLES_PLUGIN_KEY,LAYOUT_DIRECTION_PLUGIN_KEY,@@ -31,7 +31,7 @@ export {import type { NodeChange, VariableConsumptionEntry } from '@open-pencil/kiwi/fig/codec'import { guidToString, stringToGuid } from '@open-pencil/kiwi/fig/guid'import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'-import type { GUID, JSONObject, Matrix } from '@open-pencil/scene-graph/primitives'+import type { GUID, JSONObject } from '@open-pencil/scene-graph/primitives'import {buildAssetRefToVarGuidMap,@@ -96,11 +96,20 @@ function buildDerivedTextData(const lineHeight = node.lineHeight ?? Math.ceil(node.fontSize * 1.2)const glyphAdvance = node.text.length > 0 ? node.width / Math.max(node.text.length, 1) : 0- const derivedGlyphs = node.figmaDerivedTextGlyphs ?? []+ const derivedGlyphs = node.derivedTextGlyphs ?? []const glyphs =derivedGlyphs.length > 0? derivedGlyphs.map((glyph, index) => ({- commandsBlob: appendGlyphBlob(blobs, glyphBlobMap, glyph.commandsBlob),+ commandsBlob: appendGlyphBlob(+ blobs,+ glyphBlobMap,+ bakeGlyphScale(+ glyph.commandsBlob,+ glyph.scaleX ?? 1,+ glyph.scaleY ?? 1,+ glyph.rotation ?? 0+ )+ ),position: { x: glyph.x, y: glyph.y },fontSize: glyph.fontSize,firstCharacter: index,@@ -108,7 +117,8 @@ function buildDerivedTextData(index + 1 < derivedGlyphs.length? Math.max(derivedGlyphs[index + 1].x - glyph.x, 0): glyphAdvance,- rotation: 0+ // Preserve path-text radians; hardcoding 0 used to flatten circular text on re-export.+ rotation: glyph.rotation ?? 0})): (runtime.getGlyphOutlineMetrics(@@ -468,37 +478,6 @@ function serializeVariableBindings(if (entries.length > 0) nc.variableConsumptionMap = { entries }}-function computeExportTransform(node: SceneNode): Matrix {- const sx = node.flipX ? -1 : 1- const cos = Math.cos((node.rotation * Math.PI) / 180)- const sin = Math.sin((node.rotation * Math.PI) / 180)-- const m00 = cos * sx- const m01 = -sin * sx- const m10 = sin- const m11 = cos- const corners = [- { x: 0, y: 0 },- { x: node.width, y: 0 },- { x: 0, y: node.height },- { x: node.width, y: node.height }- ].map((point) => ({- x: m00 * point.x + m01 * point.y,- y: m10 * point.x + m11 * point.y- }))- const offsetX = Math.min(...corners.map((point) => point.x))- const offsetY = Math.min(...corners.map((point) => point.y))-- return {- m00,- m01,- m02: node.x - offsetX,- m10,- m11,- m12: node.y - offsetY- }-}-export function sceneNodeToKiwi(node: SceneNode,parentGuid: GUID,diff --git a/packages/fig/tests/instance-overrides.test.ts b/packages/fig/tests/instance-overrides.test.tsindex 015ca2480..3e84cd080 100644--- a/packages/fig/tests/instance-overrides.test.ts+++ b/packages/fig/tests/instance-overrides.test.ts@@ -291,7 +291,7 @@ describe('@open-pencil/fig instance interpretation', () => {y: 13.5,width: 112,height: 1,- figmaDerivedLayout: { x: 0, y: 13.5, width: 112, height: 1 }+ derivedLayout: { x: 0, y: 13.5, width: 112, height: 1 }})const dividerInstance = graph.createNode('INSTANCE', pageId, {componentId: dividerComponent.id,@@ -307,7 +307,7 @@ describe('@open-pencil/fig instance interpretation', () => {expect(avatarLeaf).toMatchObject({ width: 14, height: 14 })const divider = graph.getChildren(dividerInstance.id)[0]expect(divider.componentId).toBe(dividerSource.id)- expect(divider.figmaDerivedLayout).toMatchObject({ x: 0, y: 13.5 })+ expect(divider.derivedLayout).toMatchObject({ x: 0, y: 13.5 })})test('leaves unrelated scaled vector and multi-child instance geometry unchanged', () => {diff --git a/packages/kiwi/src/fig/codec.ts b/packages/kiwi/src/fig/codec.tsindex c6ac1a8e8..1c070f41b 100644--- a/packages/kiwi/src/fig/codec.ts+++ b/packages/kiwi/src/fig/codec.ts@@ -377,7 +377,8 @@ export interface NodeChange {fontSize: numberfirstCharacter: numberadvance: number- rotation: number+ /** Radians along the text path; kiwi omits the field for axis-aligned text. */+ rotation?: number}>fontMetaData?: Array<{key: { family: string; style: string; postscript?: string }diff --git a/packages/scene-graph/src/coordinate.ts b/packages/scene-graph/src/coordinate.tsindex b9896212c..2bd953e38 100644--- a/packages/scene-graph/src/coordinate.ts+++ b/packages/scene-graph/src/coordinate.ts@@ -1,6 +1,6 @@import type { SceneGraph, SceneNode } from './index'import Matrix, { type Mat3 } from './matrix'-import type { Vector } from './primitives'+import type { Rect, Vector } from './primitives'export function getWorldMatrix(node: SceneNode, graph: SceneGraph): Mat3 {const chain: SceneNode[] = []@@ -180,29 +180,42 @@ export function getNodeWorldBounds(node: SceneNode) {}}-export function getWorldHandles(node: SceneNode, graph: SceneGraph) {+/**+ * World-space positions of the 8 selection handles. `localRect` overrides the+ * node-local box the handles sit on — text-on-path draws its handles on the+ * glyph-fitted path box, not node bounds, so its hit-test must pass that box+ * or the visible handles are ~25px off and unclickable. Defaults to full node+ * bounds.+ */+export function getWorldHandles(node: SceneNode, graph: SceneGraph, localRect?: Rect) {const matrix = getWorldMatrix(node, graph)- const w = node.width- const h = node.height+ const x0 = localRect?.x ?? 0+ const y0 = localRect?.y ?? 0+ const w = localRect?.width ?? node.width+ const h = localRect?.height ?? node.height+ const mx = x0 + w / 2+ const my = y0 + h / 2+ const x1 = x0 + w+ const y1 = y0 + hconst localPts = [- 0,- 0, // nw- w / 2,- 0, // n- w,- 0, // ne- w,- h / 2, // e- w,- h, // se- w / 2,- h, // s- 0,- h, // sw- 0,- h / 2 // w+ x0,+ y0, // nw+ mx,+ y0, // n+ x1,+ y0, // ne+ x1,+ my, // e+ x1,+ y1, // se+ mx,+ y1, // s+ x0,+ y1, // sw+ x0,+ my // w]const pts = Matrix.mapPoints(matrix, localPts)diff --git a/packages/scene-graph/src/copy.ts b/packages/scene-graph/src/copy.tsindex c031213bc..dd7e0143f 100644--- a/packages/scene-graph/src/copy.ts+++ b/packages/scene-graph/src/copy.ts@@ -12,7 +12,7 @@ import type {ArcData,ComponentPropertyDefinition,Effect,- FigmaDerivedTextGlyph,+ DerivedTextGlyph,Fill,GeometryPath,GradientStop,@@ -21,6 +21,7 @@ import type {Stroke,StyleRun} from './'+import { geometryCommandCoordCount } from './geometry'import { createDefaultSourceMetadata } from './node-defaults'import { cloneVectorNetwork } from './vector-network'@@ -105,44 +106,74 @@ export function copyStyleRuns(runs: StyleRun[]): StyleRun[] {return runs.map(copyStyleRun)}-export function copyGeometryPaths(paths: GeometryPath[]): GeometryPath[] {- return paths.map((p) => ({- windingRule: p.windingRule,- commandsBlob: p.commandsBlob.slice(),- fills: p.fills ? copyFills(p.fills) : undefined- }))+/** Keep path-level fills across copy/scale/transform (resize snapshots). */+function withPathPaintMeta(path: GeometryPath, commandsBlob: Uint8Array): GeometryPath {+ return {+ windingRule: path.windingRule,+ commandsBlob,+ ...(path.fills ? { fills: copyFills(path.fills) } : {})+ }}-/** Scale geometry path coordinates while preserving independent path fills. */-export function scaleGeometryPaths(paths: GeometryPath[], scaleX: number, scaleY: number) {- const copies = copyGeometryPaths(paths)- if (scaleX === 1 && scaleY === 1) return copies-- for (const path of copies) {- const view = new DataView(- path.commandsBlob.buffer,- path.commandsBlob.byteOffset,- path.commandsBlob.byteLength- )- let offset = 0- while (offset < path.commandsBlob.length) {- const command = path.commandsBlob[offset]- offset += 1- if (command === 0) continue+export function copyGeometryPaths(paths: GeometryPath[]): GeometryPath[] {+ return paths.map((p) => withPathPaintMeta(p, p.commandsBlob.slice()))+}- let coordinateCount = 0- if (command === 1 || command === 2) coordinateCount = 1- else if (command === 3) coordinateCount = 2- else if (command === 4) coordinateCount = 3- if (coordinateCount === 0 || offset + coordinateCount * 8 > path.commandsBlob.length) break- for (let index = 0; index < coordinateCount; index++) {- view.setFloat32(offset, view.getFloat32(offset, true) * scaleX, true)- view.setFloat32(offset + 4, view.getFloat32(offset + 4, true) * scaleY, true)- offset += 8- }+/**+ * Affine-transform every coordinate pair in a path command blob (returns a+ * copy): (x, y) → (m00·x + m01·y + tx, m10·x + m11·y + ty).+ * Command layout: 1=move/2=line (1 pair), 3=quad (2 pairs), 4=cubic (3 pairs)+ * — font-glyph blobs are quad-heavy, so skipping command 3 desyncs the walk.+ */+export function transformGeometryBlob(+ blob: Uint8Array,+ m00: number,+ m01: number,+ m10: number,+ m11: number,+ tx = 0,+ ty = 0+): Uint8Array {+ const out = blob.slice()+ const dv = new DataView(out.buffer, out.byteOffset, out.byteLength)+ let offset = 0+ while (offset < out.length) {+ const command = out[offset++]+ const coords = geometryCommandCoordCount(command)+ if (coords == null) break+ for (let i = 0; i < coords; i++) {+ if (offset + 8 > out.length) break+ const x = dv.getFloat32(offset, true)+ const y = dv.getFloat32(offset + 4, true)+ dv.setFloat32(offset, m00 * x + m01 * y + tx, true)+ dv.setFloat32(offset + 4, m10 * x + m11 * y + ty, true)+ offset += 8}}- return copies+ return out+}++export function transformGeometryPaths(+ paths: GeometryPath[],+ m00: number,+ m01: number,+ m10: number,+ m11: number,+ tx = 0,+ ty = 0+): GeometryPath[] {+ return paths.map((g) =>+ withPathPaintMeta(g, transformGeometryBlob(g.commandsBlob, m00, m01, m10, m11, tx, ty))+ )+}++/**+ * Scale path command blob coordinates by (sx, sy).+ * Identity scale returns a deep copy (same as copyGeometryPaths).+ */+export function scaleGeometryPaths(paths: GeometryPath[], sx: number, sy: number): GeometryPath[] {+ if (sx === 1 && sy === 1) return copyGeometryPaths(paths)+ return transformGeometryPaths(paths, sx, 0, 0, sy)}// --- Internal helpers ---@@ -173,7 +204,8 @@ function copyPropertyDefs()}-function copyGlyphs(glyphs: FigmaDerivedTextGlyph[] | null): FigmaDerivedTextGlyph[] | null {+/** Deep-copy path-text glyphs (fresh commandsBlob buffers). */+export function copyDerivedGlyphs(glyphs: DerivedTextGlyph[] | null): DerivedTextGlyph[] | null {return glyphs ? glyphs.map((g) => ({ ...g, commandsBlob: new Uint8Array(g.commandsBlob) })) : null}@@ -244,13 +276,15 @@ export function cloneNodeProps(pluginRelaunchData: copySpread(src.pluginRelaunchData),exportSettings: copySpread(src.exportSettings),componentPropertyValues: { ...src.componentPropertyValues },- figmaDerivedLayout: src.figmaDerivedLayout ? { ...src.figmaDerivedLayout } : null,+ derivedLayout: src.derivedLayout ? { ...src.derivedLayout } : null,arcData: src.arcData ? copyArcData(src.arcData) : null,vectorNetwork: src.vectorNetwork ? cloneVectorNetwork(src.vectorNetwork) : null,textPicture: src.textPicture ? new Uint8Array(src.textPicture) : null,- figmaDerivedTextGlyphs: src.figmaDerivedTextGlyphs- ? markCopySource(src.figmaDerivedTextGlyphs, copyGlyphs(src.figmaDerivedTextGlyphs) ?? [])+ derivedTextGlyphs: src.derivedTextGlyphs+ ? markCopySource(src.derivedTextGlyphs, copyDerivedGlyphs(src.derivedTextGlyphs) ?? []): null,+ textPathData: src.textPathData ? structuredClone(src.textPathData) : null,+ textPathBox: src.textPathBox ? { ...src.textPathBox } : null,gridPosition: src.gridPosition ? { ...src.gridPosition } : null}}diff --git a/packages/scene-graph/src/geometry.ts b/packages/scene-graph/src/geometry.tsindex e34cbb5c1..093cf5733 100644--- a/packages/scene-graph/src/geometry.ts+++ b/packages/scene-graph/src/geometry.ts@@ -254,9 +254,15 @@ export function intersectVisualBounds(a: VisualBounds, b: VisualBounds): VisualBreturn minX < maxX && minY < maxY ? { minX, minY, maxX, maxY } : null}-function geometryCommandCoordCount(command: number): number | null {+/**+ * Coordinate pairs per path blob command: 0=close, 1=move, 2=line,+ * 3=quad (glyph-derived blobs are quad-heavy), 4=cubic. Unknown → null so+ * walkers stop instead of desyncing into coordinate bytes.+ */+export function geometryCommandCoordCount(command: number): number | null {if (command === 0) return 0if (command === 1 || command === 2) return 1+ if (command === 3) return 2if (command === 4) return 3return null}diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.tsindex 9d073d07c..d9e6f97e0 100644--- a/packages/scene-graph/src/index.ts+++ b/packages/scene-graph/src/index.ts@@ -24,11 +24,11 @@ import { CONTAINER_TYPES, createDefaultNode } from './node-defaults'import { updateNodePreview } from './preview'import { styleDetachmentChanges } from './shared-styles'import { markSourceFieldsEdited } from './source-metadata'-import { GLYPH_AFFECTING_KEYS, TEXT_PICTURE_KEYS } from './text-picture'+import { GLYPH_AFFECTING_KEYS, invalidateTextCaches, TEXT_PICTURE_KEYS } from './text-picture'import * as Variables from './variables'import { normalizeVectorNetwork } from './vector-network'-export type { GUID, Color, Vector, Size } from './primitives'+export type { GUID, Color, Size, Vector } from './primitives'export * from './types'import type { Emitter } from 'nanoevents'@@ -424,12 +424,7 @@ export class SceneGraph {set.add(id)}}- if (node.type === 'TEXT') {- const textChanged = Object.keys(changes).some((k) => TEXT_PICTURE_KEYS.has(k))- if (node.textPicture && textChanged) node.textPicture = null- const glyphChanged = Object.keys(changes).some((k) => GLYPH_AFFECTING_KEYS.has(k))- if (node.figmaDerivedTextGlyphs && glyphChanged) node.figmaDerivedTextGlyphs = null- }+ if (node.type === 'TEXT') invalidateTextCaches(node, changes)if (this.sourceMetadataPreservationDepth === 0) {markSourceFieldsEdited(node, Object.keys(changes))}diff --git a/packages/scene-graph/src/node-defaults.ts b/packages/scene-graph/src/node-defaults.tsindex e95049c61..5964c62d6 100644--- a/packages/scene-graph/src/node-defaults.ts+++ b/packages/scene-graph/src/node-defaults.ts@@ -38,7 +38,7 @@ export function createDefaultNode(height: 100,rotation: 0,source: createDefaultSourceMetadata(),- figmaDerivedLayout: null,+ derivedLayout: null,fills:type === 'TEXT' ? [{ type: 'SOLID' as const, color: BLACK, opacity: 1, visible: true }] : [],strokes: [],@@ -165,7 +165,9 @@ export function createDefaultNode(flipX: false,flipY: false,textPicture: null,- figmaDerivedTextGlyphs: null,+ derivedTextGlyphs: null,+ textPathData: null,+ textPathBox: null,...overrides}}diff --git a/packages/scene-graph/src/preview.ts b/packages/scene-graph/src/preview.tsindex ca5531fdd..528c90ac8 100644--- a/packages/scene-graph/src/preview.ts+++ b/packages/scene-graph/src/preview.ts@@ -1,4 +1,4 @@-import { GLYPH_AFFECTING_KEYS, TEXT_PICTURE_KEYS } from './text-picture'+import { invalidateTextCaches } from './text-picture'import type { SceneNode } from './types'import { normalizeVectorNetwork } from './vector-network'@@ -60,12 +60,7 @@ export function updateNodePreview(}const affectsLayout = Object.keys(changes).some((key) => LAYOUT_AFFECTING_KEYS.has(key))if (affectsLayout) graph.clearAbsPosCache()- if (node.type === 'TEXT') {- const textChanged = Object.keys(changes).some((key) => TEXT_PICTURE_KEYS.has(key))- if (node.textPicture && textChanged) node.textPicture = null- const glyphChanged = Object.keys(changes).some((key) => GLYPH_AFFECTING_KEYS.has(key))- if (node.figmaDerivedTextGlyphs && glyphChanged) node.figmaDerivedTextGlyphs = null- }+ if (node.type === 'TEXT') invalidateTextCaches(node, changes)const normalizedChanges = changes.vectorNetwork? { ...changes, vectorNetwork: normalizeVectorNetwork(changes.vectorNetwork) }: changesdiff --git a/packages/scene-graph/src/resize.ts b/packages/scene-graph/src/resize.tsindex c404bbec8..267c82f19 100644--- a/packages/scene-graph/src/resize.ts+++ b/packages/scene-graph/src/resize.ts@@ -1,11 +1,33 @@-import { copyGeometryPaths, scaleGeometryPaths } from './copy'+import {+ copyDerivedGlyphs,+ copyGeometryPaths,+ copyStroke,+ copyStrokes,+ scaleGeometryPaths+} from './copy'import type { Rect } from './primitives'-import type { ConstraintType, SceneNode, VectorNetwork } from './types'+import type { ConstraintType, DerivedTextGlyph, SceneNode, Stroke, VectorNetwork } from './types'import { cloneVectorNetwork } from './vector-network'+/**+ * Drag-start state a live resize re-scales from. Path text needs more than the+ * layout rect: its OUTSIDE stroke silhouettes and glyph outlines are baked+ * geometry that must scale with the node, and textPathBox is the layout box the+ * glyphs were reflowed against.+ */export type ResizeSnapshot = Pick<SceneNode,- 'x' | 'y' | 'width' | 'height' | 'vectorNetwork' | 'fillGeometry' | 'strokeGeometry'+ | 'x'+ | 'y'+ | 'width'+ | 'height'+ | 'vectorNetwork'+ | 'fillGeometry'+ | 'strokeGeometry'+ | 'derivedTextGlyphs'+ | 'strokes'+ | 'textPathData'+ | 'textPathBox'>interface ResizeGraph {@@ -104,6 +126,109 @@ export function scaleVectorNetworkForResize(}}+/** Snapshot one node's resize-relevant state (rect + geometry that must scale with it). */+export function createResizeSnapshot(node: SceneNode): ResizeSnapshot {+ return {+ x: node.x,+ y: node.y,+ width: node.width,+ height: node.height,+ vectorNetwork: node.vectorNetwork ? cloneVectorNetwork(node.vectorNetwork) : null,+ fillGeometry: copyGeometryPaths(node.fillGeometry),+ strokeGeometry: copyGeometryPaths(node.strokeGeometry),+ derivedTextGlyphs: copyDerivedGlyphs(node.derivedTextGlyphs),+ strokes: copyStrokes(node.strokes),+ textPathData: node.textPathData ? structuredClone(node.textPathData) : null,+ textPathBox: node.textPathBox ? { ...node.textPathBox } : null+ }+}++function scaleDerivedGlyphs(+ glyphs: DerivedTextGlyph[] | null,+ sx: number,+ sy: number+): DerivedTextGlyph[] | null {+ if (!glyphs?.length) return glyphs+ return glyphs.map((g) => ({+ ...g,+ x: g.x * sx,+ y: g.y * sy,+ scaleX: (g.scaleX ?? 1) * sx,+ scaleY: (g.scaleY ?? 1) * sy,+ commandsBlob: new Uint8Array(g.commandsBlob)+ }))+}++function scaleStrokes(strokes: Stroke[], sx: number, sy: number): Stroke[] {+ if (strokes.length === 0) return strokes+ // Weight is a scalar; average scale is the usual 2D → 1D compromise.+ const weightScale = (Math.abs(sx) + Math.abs(sy)) / 2+ return strokes.map((s) => ({ ...copyStroke(s), weight: s.weight * weightScale }))+}++/**+ * All geometry that must track a width/height change. Historically only+ * vectorNetwork + fillGeometry were updated — path-text strokeGeometry and+ * glyphs stayed at the pre-resize size, so shrinking a sticker made the white+ * OUTSIDE outlines look massively thick (DomeSticker resize bug).+ */+export function scaledGeometryChanges(+ orig: Pick<+ ResizeSnapshot,+ | 'vectorNetwork'+ | 'fillGeometry'+ | 'strokeGeometry'+ | 'derivedTextGlyphs'+ | 'strokes'+ | 'textPathData'+ | 'textPathBox'+ >,+ origWidth: number,+ origHeight: number,+ width: number,+ height: number+): Partial<SceneNode> {+ if (origWidth <= 0 || origHeight <= 0) return {}+ const sx = width / origWidth+ const sy = height / origHeight+ if (sx === 1 && sy === 1) return {}++ const changes: Partial<SceneNode> = {}+ const resizedVN = scaleVectorNetworkForResize(+ orig.vectorNetwork,+ origWidth,+ origHeight,+ width,+ height+ )+ if (resizedVN) changes.vectorNetwork = resizedVN++ if (orig.fillGeometry.length > 0) {+ changes.fillGeometry = scaleGeometryPaths(orig.fillGeometry, sx, sy)+ }+ if (orig.strokeGeometry.length > 0) {+ changes.strokeGeometry = scaleGeometryPaths(orig.strokeGeometry, sx, sy)+ }+ if (orig.derivedTextGlyphs?.length) {+ changes.derivedTextGlyphs = scaleDerivedGlyphs(orig.derivedTextGlyphs, sx, sy)+ // Keep the layout/selection box in sync with the scaled glyphs. reflow+ // overrides this when it applies; this covers the fallback where reflow+ // returns null (no path data) so the box doesn't carry a stale size.+ if (orig.textPathBox) {+ changes.textPathBox = {+ x: orig.textPathBox.x * sx,+ y: orig.textPathBox.y * sy,+ width: orig.textPathBox.width * sx,+ height: orig.textPathBox.height * sy+ }+ }+ }+ if (orig.strokes.length > 0) {+ changes.strokes = scaleStrokes(orig.strokes, sx, sy)+ }+ return changes+}+export function collectResizeDescendants(graph: ResizeGraph,rootId: string@@ -118,15 +243,7 @@ export function collectResizeDescendants(for (const childId of parent.childIds) {const child = graph.getNode(childId)if (!child) continue- snapshots.set(childId, {- x: child.x,- y: child.y,- width: child.width,- height: child.height,- vectorNetwork: child.vectorNetwork ? cloneVectorNetwork(child.vectorNetwork) : null,- fillGeometry: copyGeometryPaths(child.fillGeometry),- strokeGeometry: copyGeometryPaths(child.strokeGeometry)- })+ snapshots.set(childId, createResizeSnapshot(child))collect(childId)}}@@ -170,30 +287,9 @@ export function computeConstrainedResizeChanges(child.horizontalConstraint,child.verticalConstraint)- const childChanges: Partial<SceneNode> = { ...rect }- const vectorNetwork = scaleVectorNetworkForResize(- original.vectorNetwork,- original.width,- original.height,- rect.width,- rect.height- )- if (vectorNetwork) childChanges.vectorNetwork = vectorNetwork- if (original.width > 0 && original.height > 0) {- const scaleX = rect.width / original.width- const scaleY = rect.height / original.height- if (scaleX !== 1 || scaleY !== 1) {- if (original.fillGeometry.length > 0) {- childChanges.fillGeometry = scaleGeometryPaths(original.fillGeometry, scaleX, scaleY)- }- if (original.strokeGeometry.length > 0) {- childChanges.strokeGeometry = scaleGeometryPaths(- original.strokeGeometry,- scaleX,- scaleY- )- }- }+ const childChanges: Partial<SceneNode> = {+ ...rect,+ ...scaledGeometryChanges(original, original.width, original.height, rect.width, rect.height)}changes.set(childId, childChanges)// The final pass sees layout containers after Yoga has resolved HUG/FILL sizing.diff --git a/packages/scene-graph/src/text-picture.ts b/packages/scene-graph/src/text-picture.tsindex 323ad81ba..cabcbdfaf 100644--- a/packages/scene-graph/src/text-picture.ts+++ b/packages/scene-graph/src/text-picture.ts@@ -1,3 +1,9 @@+import type { SceneNode } from './types'++/**+ * Invalidate cached Skia textPicture (Paragraph snapshot). Includes width/height+ * because wrapping/layout depends on the box.+ */export const TEXT_PICTURE_KEYS: ReadonlySet<string> = new Set(['text','fontSize',@@ -17,7 +23,6 @@ export const TEXT_PICTURE_KEYS: ReadonlySet<string> = new Set(['height'])-/** Properties that change imported glyph outlines or per-glyph positioning. */export const GLYPH_AFFECTING_KEYS: ReadonlySet<string> = new Set(['text','fontSize',@@ -30,3 +35,21 @@ export const GLYPH_AFFECTING_KEYS: ReadonlySet<string> = new Set(['textCase','styleRuns'])++/**+ * Shared by SceneGraph.updateNode and updateNodePreview (drag hot path) so the+ * two invalidation rules cannot drift. Glyphs are kept when the caller+ * replaces them in the same update (resize supplies scaled copies).+ */+export function invalidateTextCaches(node: SceneNode, changes: Partial<SceneNode>): void {+ const keys = Object.keys(changes)+ if (node.textPicture && keys.some((key) => TEXT_PICTURE_KEYS.has(key))) node.textPicture = null+ const glyphsInvalidated = keys.some((key) => GLYPH_AFFECTING_KEYS.has(key))+ // A successful path-text edit supplies reflowed glyphs in `changes`. Every+ // other mutation path must drop stale baked glyphs and path identity rather+ // than pair new text/style with old visible outlines.+ if (node.derivedTextGlyphs && glyphsInvalidated && !changes.derivedTextGlyphs) {+ node.derivedTextGlyphs = null+ node.textPathData = null+ }+}diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.tsindex b5e29669a..47e9dd53c 100644--- a/packages/scene-graph/src/types.ts+++ b/packages/scene-graph/src/types.ts@@ -305,11 +305,33 @@ export interface PluginRelaunchDataEntry {isDeleted: boolean}-export interface FigmaDerivedTextGlyph {+/**+ * One derived glyph outline for display (path text / missing-font fidelity).+ * Figma import is one producer; OpenPencil editing and reflow can regenerate it.+ * commandsBlob is in font units; paint multiplies by fontSize (and scaleX/Y).+ */+export interface TextPathData {+ network: VectorNetwork+ normalizedSize: Vector+ tValue: number+ forward: boolean+}++export interface DerivedTextGlyph {commandsBlob: Uint8Arrayx: numbery: numberfontSize: number+ /** Figma Glyph.rotation — radians, not degrees. Zero for axis-aligned text. */+ rotation?: number+ /**+ * Accumulated non-uniform resize scale (default 1). Paint order is+ * translate → scale(scaleX,Y) → rotate → scale(fontSize,-fontSize) so+ * anisotropic stretch matches scaleGeometryPaths(strokeGeometry).+ * Do not fold this into fontSize or rotated letters desync from outlines.+ */+ scaleX?: number+ scaleY?: number}export interface SymbolLink {@@ -382,7 +404,8 @@ export interface SceneNode {height: numberrotation: numbersource: SourceMetadata- figmaDerivedLayout: Partial<Rect> | null+ /** Materialized layout hint imported or generated outside the live Yoga layout pass. */+ derivedLayout: Partial<Rect> | nullfills: Fill[]strokes: Stroke[]@@ -535,7 +558,11 @@ export interface SceneNode {flipY: booleantextPicture: Uint8Array | null- figmaDerivedTextGlyphs: FigmaDerivedTextGlyph[] | null+ derivedTextGlyphs: DerivedTextGlyph[] | null+ /** Format-neutral layout path for text-on-path nodes. */+ textPathData: TextPathData | null+ /** Node-local box that maps textPathData into the node coordinate space. */+ textPathBox: Rect | null}export type ComponentPropertyType = 'VARIANT' | 'TEXT' | 'BOOLEAN' | 'INSTANCE_SWAP'diff --git a/packages/vue/src/canvas/text-edit/editing.ts b/packages/vue/src/canvas/text-edit/editing.tsindex dd15fecd4..ceb6b5c05 100644--- a/packages/vue/src/canvas/text-edit/editing.ts+++ b/packages/vue/src/canvas/text-edit/editing.ts@@ -143,7 +143,7 @@ export function createTextEditActions(store: Editor) {function syncText(nodeId: string, text: string, runs?: SceneNode['styleRuns']) {const changes: Partial<SceneNode> = { text }if (runs !== undefined) changes.styleRuns = runs- store.graph.updateNode(nodeId, changes)+ store.updateTextEditNode(nodeId, changes)const updated = store.graph.getNode(nodeId)if (updated) store.textEditor?.rebuildParagraph(updated)store.requestRender()diff --git a/packages/vue/src/shared/input/geometry.ts b/packages/vue/src/shared/input/geometry.tsindex 6a8924670..1f840bf48 100644--- a/packages/vue/src/shared/input/geometry.ts+++ b/packages/vue/src/shared/input/geometry.ts@@ -1,9 +1,10 @@import { CORNER_ROTATE_ZONE, HANDLE_HIT_RADIUS } from '@open-pencil/core/constants'import type { Editor } from '@open-pencil/core/editor'+import { fitTextPathBoxToGlyphs, getTextPathData, sampleTextPath } from '@open-pencil/core/text'import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'import { getAbsoluteRotation, getWorldHandles } from '@open-pencil/scene-graph/coordinate'import { degToRad } from '@open-pencil/scene-graph/geometry'-import type { Vector } from '@open-pencil/scene-graph/primitives'+import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'import resizeCursorSVG from '#vue/shared/assets/resize-cursor.svg?raw'import rotateCursorSVG from '#vue/shared/assets/rotate-cursor.svg?raw'@@ -163,6 +164,24 @@ function getCursorAngleFromHandle(handle: HandlePosition, rotation: number): numreturn (angle + 360) % 360}+/**+ * Node-local box the selection handles are drawn on. For imported text-on-path+ * the overlay draws its bounds/handles on the glyph-fitted path box (see+ * drawTextPathSelection), not node bounds — mirror that exact decision so the+ * hit-test lands on the visible handles instead of ~25px inside them. Returns+ * undefined (→ full node bounds) for every other node and for the same+ * fallbacks the overlay takes (no path data / unsamplable path).+ */+function selectionHandleRect(node: SceneNode): Rect | undefined {+ if (node.textPathData === null || !node.textPathBox) return undefined+ const data = getTextPathData(node)+ const box =+ (data && fitTextPathBoxToGlyphs(data, node.textPathBox, node.derivedTextGlyphs)) ??+ node.textPathBox+ if (!data || !sampleTextPath(data, box)) return undefined+ return box+}+export function getHitHandleByMatrix(cx: number,cy: number,@@ -173,7 +192,7 @@ export function getHitHandleByMatrix(handle: HandlePositionrotation: number} | null {- const handles = getWorldHandles(node, graph)+ const handles = getWorldHandles(node, graph, selectionHandleRect(node))const CORNER_R = HANDLE_HIT_RADIUS / zoom@@ -203,7 +222,7 @@ export function hitTestTopRotationHandleByMatrix(graph: SceneGraph,zoom: number = 1): boolean {- const handles = getWorldHandles(node, graph)+ const handles = getWorldHandles(node, graph, selectionHandleRect(node))const rotation = getAbsoluteRotation(node, graph)const topMidX = (handles.nw.x + handles.ne.x) / 2const topMidY = (handles.nw.y + handles.ne.y) / 2@@ -226,7 +245,7 @@ export function hitTestCornerRotationByMatrix(graph: SceneGraph,zoom: number = 1): CornerPosition | null {- const handles = getWorldHandles(node, graph)+ const handles = getWorldHandles(node, graph, selectionHandleRect(node))const HANDLE_R = HANDLE_HIT_RADIUS / zoomconst ROTATE_R = CORNER_ROTATE_ZONE / zoomdiff --git a/packages/vue/src/shared/input/resize.ts b/packages/vue/src/shared/input/resize.tsindex 0046ead6c..e62da010b 100644--- a/packages/vue/src/shared/input/resize.ts+++ b/packages/vue/src/shared/input/resize.ts@@ -1,47 +1,92 @@export { constrainToAspectRatio } from '#vue/shared/input/resize/rect'export { tryStartResize } from '#vue/shared/input/resize/start'+import { toRaw } from 'vue'+import type { Editor } from '@open-pencil/core/editor'import { computeAllLayouts } from '@open-pencil/core/layout'+import { calibratePathTextLayout, reflowPathTextGlyphs } from '@open-pencil/core/text'import { cloneVectorNetwork } from '@open-pencil/scene-graph'import type { SceneNode } from '@open-pencil/scene-graph'-import { copyGeometryPaths, scaleGeometryPaths } from '@open-pencil/scene-graph/copy'+import { copyDerivedGlyphs, copyGeometryPaths, copyStrokes } from '@open-pencil/scene-graph/copy'import {computeConstrainedResizeChanges,- scaleVectorNetworkForResize+ scaledGeometryChanges,+ type ResizeSnapshot} from '@open-pencil/scene-graph/resize'import { calculateResizeRect } from '#vue/shared/input/resize/rect'import type { DragResize } from '#vue/shared/input/types'+/**+ * Resize path-text glyphs without baking anisotropic scale into fontSize.+ * commandsBlob stays in font units; paint multiplies by fontSize then scaleX/Y.+ * Accumulating scaleX/Y (not fontSize *= avg) keeps non-uniform stretch correct+ * under rotation — see drawDerivedText transform order.+ */+/**+ * Figma resize semantics for imported text-on-path: constant font size,+ * glyphs re-placed along the scaled path (see core/text/path). 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(+ 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)+ if (!glyphs) return null+ return {+ derivedTextGlyphs: glyphs,+ textPathBox: box,+ strokeGeometry: [],+ strokes: copyStrokes(orig.strokes)+ }+}+function resizeChanges(d: DragResize, cx: number, cy: number, constrain: boolean) {const { origRect } = dconst newRect = calculateResizeRect(d.handle, origRect, cx - d.startX, cy - d.startY, constrain)- const changes: Partial<SceneNode> = { ...newRect }-- const resizedVectorNetwork = scaleVectorNetworkForResize(- d.origVectorNetwork,- origRect.width,- origRect.height,- newRect.width,- newRect.height- )- if (resizedVectorNetwork) changes.vectorNetwork = resizedVectorNetwork- if (origRect.width > 0 && origRect.height > 0) {- const scaleX = newRect.width / origRect.width- const scaleY = newRect.height / origRect.height- if (scaleX !== 1 || scaleY !== 1) {- if (d.origFillGeometry.length > 0) {- changes.fillGeometry = scaleGeometryPaths(d.origFillGeometry, scaleX, scaleY)- }- if (d.origStrokeGeometry.length > 0) {- changes.strokeGeometry = scaleGeometryPaths(d.origStrokeGeometry, scaleX, scaleY)- }- }+ const changes: Partial<SceneNode> = {+ ...newRect,+ ...scaledGeometryChanges(+ {+ vectorNetwork: d.origVectorNetwork,+ fillGeometry: d.origFillGeometry,+ strokeGeometry: d.origStrokeGeometry,+ derivedTextGlyphs: d.origDerivedTextGlyphs,+ strokes: d.origStrokes,+ textPathData: d.origTextPathData,+ textPathBox: d.origTextPathBox+ },+ origRect.width,+ origRect.height,+ newRect.width,+ newRect.height+ )}return { changes, newRect }}+/**+ * Re-apply the root resize to descendants through the constraint engine, then+ * layer path-text reflow on top: constrained children get their own before/after+ * box, and path text must re-place glyphs along its path rather than scale as a+ * blob (see reflowedPathTextChanges).+ */function applyConstrainedChildren(d: DragResize,newRect: Pick<SceneNode, 'width' | 'height'>,@@ -56,20 +101,51 @@ function applyConstrainedChildren(d.origChildren)for (const [childId, childChanges] of changes) {+ const orig = d.origChildren.get(childId)+ 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)+ if (reflow) Object.assign(childChanges, reflow)+ }editor.graph.updateNodePreview(childId, childChanges)editor.renderer?.invalidateVectorPath(childId)}}export function applyResize(- d: DragResize,+ dragState: DragResize,cx: number,cy: number,constrain: boolean,editor: Editor) {+ // Drag state lives in Vue-reactive input state; nested arrays read through+ // it are reactive proxies. Writing those into the graph poisons it for+ // structuredClone consumers (export subgraph clone, undo snapshots) with+ // DataCloneError. Unwrap once — also keeps the drag hot path off proxies.+ const d = toRaw(dragState)const { changes, newRect } = resizeChanges(d, cx, cy, constrain)+ if (d.origRect.width > 0 && d.origRect.height > 0) {+ const reflow = reflowedPathTextChanges(+ {+ textPathData: d.origTextPathData,+ textPathBox: d.origTextPathBox,+ derivedTextGlyphs: d.origDerivedTextGlyphs,+ strokes: d.origStrokes+ },+ newRect.width / d.origRect.width,+ newRect.height / d.origRect.height+ )+ if (reflow) Object.assign(changes, reflow)+ }editor.graph.updateNodePreview(d.nodeId, changes)+ if (changes.fillGeometry || changes.strokeGeometry || changes.vectorNetwork) {+ editor.renderer?.invalidateVectorPath(d.nodeId)+ }++ // Two passes around the layout run: the first sizes children so Yoga can+ // resolve HUG/FILL, the second re-applies against the settled boxes.applyConstrainedChildren(d, newRect, editor)editor.graph.runPreviewUpdates(() => computeAllLayouts(editor.graph, d.nodeId))applyConstrainedChildren(d, newRect, editor)@@ -77,53 +153,118 @@ export function applyResize(editor.requestRepaint()}-export function commitResizePreview(d: DragResize, editor: Editor) {- const node = editor.graph.getNode(d.nodeId)- if (!node) return- const finalChanges: Partial<SceneNode> = {+/**+ * Deep-copy geometry read back from a previewed node — preview values can+ * be reactivity-wrapped, and storing proxies breaks structuredClone snapshots+ * (delete/undo would throw DataCloneError).+ */+function snapshotResizeFinal(node: SceneNode): Partial<SceneNode> {+ const final: Partial<SceneNode> = {x: node.x,y: node.y,width: node.width,height: node.height}- if (node.vectorNetwork) finalChanges.vectorNetwork = cloneVectorNetwork(node.vectorNetwork)- finalChanges.fillGeometry = copyGeometryPaths(node.fillGeometry)- finalChanges.strokeGeometry = copyGeometryPaths(node.strokeGeometry)+ if (node.vectorNetwork) final.vectorNetwork = cloneVectorNetwork(node.vectorNetwork)+ if (node.fillGeometry.length > 0) final.fillGeometry = copyGeometryPaths(node.fillGeometry)+ // Path-text reflow legitimately EMPTIES strokeGeometry (textPathBox marks+ // those nodes) — commit it so the pre-resize silhouettes don't resurrect.+ // Everything else keeps the length guard: a spurious strokeGeometry key on+ // plain nodes would clear their raw Figma payload on commit.+ if (node.strokeGeometry.length > 0 || node.textPathBox) {+ final.strokeGeometry = copyGeometryPaths(node.strokeGeometry)+ }+ if (node.derivedTextGlyphs?.length) {+ final.derivedTextGlyphs = copyDerivedGlyphs(node.derivedTextGlyphs)+ }+ if (node.textPathBox) final.textPathBox = { ...node.textPathBox }+ if (node.textPathData) final.textPathData = structuredClone(node.textPathData)+ if (node.strokes.length > 0) final.strokes = copyStrokes(node.strokes)+ return final+}++/**+ * Resize commits run inside preserveSourceMetadataDuring so the raw Figma+ * payload (vectorData, textPathStart, effects, ...) survives — but the+ * geometry-derived raw fields are now stale and export PREFERS them over+ * node values (rawSize would resurrect the pre-resize dimensions in the+ * exported file). Invalidate exactly those.+ */+function clearResizedRawGeometry(editor: Editor, nodeId: string): void {+ const node = editor.graph.getNode(nodeId)+ if (!node) return+ node.source.fig.rawSize = null+ node.source.fig.rawTransform = null+ const raw = node.source.fig.rawNodeFields+ delete raw.fillGeometry+ delete raw.strokeGeometry+ delete raw.strokeWeight+ // vectorData is dual-use: for VECTOR nodes it gates nodeForGeometryExport —+ // leaving it makes export pair stale raw vectorData with styleID-less+ // explicit paths (multi-color icons turn gray). For TEXT it is the+ // TEXT_PATH layout path and must survive or reflow dies.+ if (node.type !== 'TEXT') delete raw.vectorData+}++export function commitResizePreview(dragState: DragResize, editor: Editor) {+ // See applyResize — reactive drag state must not leak into graph writes.+ const d = toRaw(dragState)+ const node = editor.graph.getNode(d.nodeId)+ if (!node) return+ const finalChanges = snapshotResizeFinal(node)if (d.origChildren) {const finalChildren = new Map<string, Partial<SceneNode>>()for (const [childId] of d.origChildren) {const child = editor.graph.getNode(childId)if (!child) continue- const final: Partial<SceneNode> = {- x: child.x,- y: child.y,- width: child.width,- height: child.height- }- if (child.vectorNetwork) final.vectorNetwork = cloneVectorNetwork(child.vectorNetwork)- final.fillGeometry = copyGeometryPaths(child.fillGeometry)- final.strokeGeometry = copyGeometryPaths(child.strokeGeometry)- finalChildren.set(childId, final)+ finalChildren.set(childId, snapshotResizeFinal(child))}editor.graph.updateNodePreview(d.nodeId, d.origRect)for (const [childId, orig] of d.origChildren) {- editor.graph.updateNodePreview(childId, orig)- }- editor.updateNode(d.nodeId, finalChanges)- for (const [childId, final] of finalChildren) {- editor.updateNode(childId, final)+ editor.graph.updateNodePreview(childId, {+ x: orig.x,+ y: orig.y,+ width: orig.width,+ height: orig.height,+ vectorNetwork: orig.vectorNetwork,+ fillGeometry: orig.fillGeometry,+ strokeGeometry: orig.strokeGeometry,+ derivedTextGlyphs: orig.derivedTextGlyphs,+ strokes: orig.strokes,+ textPathData: orig.textPathData,+ textPathBox: orig.textPathBox+ })}+ // Resize is geometric — the raw Figma import payload (vectorData,+ // textPathStart, effects, ...) must survive or path-text reflow works+ // exactly once and export fidelity degrades.+ editor.graph.preserveSourceMetadataDuring(() => {+ editor.updateNode(d.nodeId, finalChanges)+ for (const [childId, final] of finalChildren) {+ editor.updateNode(childId, final)+ }+ })+ clearResizedRawGeometry(editor, d.nodeId)+ for (const [childId] of finalChildren) clearResizedRawGeometry(editor, childId)editor.commitGroupResize(d.nodeId, d.origRect, d.origChildren)editor.requestRepaint()} else {editor.graph.updateNodePreview(d.nodeId, d.origRect)- editor.updateNode(d.nodeId, finalChanges)+ // See the group branch — raw import payload survives geometric commits.+ editor.graph.preserveSourceMetadataDuring(() => {+ editor.updateNode(d.nodeId, finalChanges)+ })+ clearResizedRawGeometry(editor, d.nodeId)editor.commitResize(d.nodeId, {...d.origRect,- vectorNetwork: d.origVectorNetwork,- fillGeometry: d.origFillGeometry,- strokeGeometry: d.origStrokeGeometry+ ...(d.origVectorNetwork || node.vectorNetwork ? { vectorNetwork: d.origVectorNetwork } : {}),+ ...(d.origFillGeometry.length > 0 ? { fillGeometry: d.origFillGeometry } : {}),+ ...(d.origStrokeGeometry.length > 0 ? { strokeGeometry: d.origStrokeGeometry } : {}),+ ...(d.origDerivedTextGlyphs?.length ? { derivedTextGlyphs: d.origDerivedTextGlyphs } : {}),+ ...(d.origStrokes.length > 0 ? { strokes: d.origStrokes } : {}),+ ...(d.origTextPathData ? { textPathData: d.origTextPathData } : {}),+ ...(d.origTextPathBox ? { textPathBox: d.origTextPathBox } : {})})}}diff --git a/packages/vue/src/shared/input/resize/start.ts b/packages/vue/src/shared/input/resize/start.tsindex d61553d4e..1e426aeef 100644--- a/packages/vue/src/shared/input/resize/start.ts+++ b/packages/vue/src/shared/input/resize/start.ts@@ -1,7 +1,5 @@import type { Editor } from '@open-pencil/core/editor'-import { cloneVectorNetwork } from '@open-pencil/scene-graph'-import { copyGeometryPaths } from '@open-pencil/scene-graph/copy'-import { collectResizeDescendants } from '@open-pencil/scene-graph/resize'+import { collectResizeDescendants, createResizeSnapshot } from '@open-pencil/scene-graph/resize'import { getHitHandleByMatrix } from '#vue/shared/input/geometry'import type { DragResize } from '#vue/shared/input/types'@@ -12,6 +10,7 @@ export function tryStartResize(cx: number, cy: number, editor: Editor): DragResiif (!node || node.locked) continueconst handleResult = getHitHandleByMatrix(cx, cy, node, editor.graph, editor.renderer?.zoom)if (handleResult) {+ const snap = createResizeSnapshot(node)return {type: 'resize',handle: handleResult.handle,@@ -19,9 +18,13 @@ export function tryStartResize(cx: number, cy: number, editor: Editor): DragResistartY: cy,origRect: { x: node.x, y: node.y, width: node.width, height: node.height },nodeId: id,- origVectorNetwork: node.vectorNetwork ? cloneVectorNetwork(node.vectorNetwork) : null,- origFillGeometry: copyGeometryPaths(node.fillGeometry),- origStrokeGeometry: copyGeometryPaths(node.strokeGeometry),+ origVectorNetwork: snap.vectorNetwork,+ origFillGeometry: snap.fillGeometry,+ origStrokeGeometry: snap.strokeGeometry,+ origDerivedTextGlyphs: snap.derivedTextGlyphs,+ origStrokes: snap.strokes,+ origTextPathData: snap.textPathData,+ origTextPathBox: snap.textPathBox,origChildren: collectResizeDescendants(editor.graph, id)}}diff --git a/packages/vue/src/shared/input/types.ts b/packages/vue/src/shared/input/types.tsindex 1a9e790e5..5744e4040 100644--- a/packages/vue/src/shared/input/types.ts+++ b/packages/vue/src/shared/input/types.ts@@ -1,5 +1,12 @@import type { Tool } from '@open-pencil/core/editor'-import type { GeometryPath, NodeType, VectorNetwork } from '@open-pencil/scene-graph'+import type {+ DerivedTextGlyph,+ GeometryPath,+ NodeType,+ Stroke,+ TextPathData,+ VectorNetwork+} from '@open-pencil/scene-graph'import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'import type { ResizeSnapshot } from '@open-pencil/scene-graph/resize'@@ -47,7 +54,12 @@ export interface DragResize {nodeId: stringorigVectorNetwork: VectorNetwork | nullorigFillGeometry: GeometryPath[]+ /** Path-text OUTSIDE outlines / vector stroke blobs — must scale with the node. */origStrokeGeometry: GeometryPath[]+ origDerivedTextGlyphs: DerivedTextGlyph[] | null+ origStrokes: Stroke[]+ origTextPathData: TextPathData | null+ origTextPathBox: Rect | nullorigChildren: Map<string, ResizeSnapshot> | null}diff --git a/tests/e2e/canvas/text-path-visual.spec.ts b/tests/e2e/canvas/text-path-visual.spec.tsnew file mode 100644index 000000000..2a10a60e4--- /dev/null+++ b/tests/e2e/canvas/text-path-visual.spec.ts@@ -0,0 +1,28 @@+import { expect, test, useEditorSetup } from '#tests/e2e/fixtures'++const editor = useEditorSetup('/?test&no-chrome&no-rulers')++test('renders imported text on a path with its selection overlay', async () => {+ test.setTimeout(90_000)+ await editor.page.evaluate(() => window.openPencil?.openFile?.('/tests/fixtures/circle-text.fig'))+ await editor.canvas.waitForRender()++ const selected = 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 false+ store.select([node.id])+ store.zoomToSelection()+ store.requestRender()+ return true+ })+ expect(selected).toBe(true)+ await editor.canvas.waitForRender()+ editor.canvas.assertNoErrors()++ const buffer = await editor.canvas.canvas.screenshot()+ expect(buffer).toMatchSnapshot('text-path-rendering-and-selection.png')+})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.pngnew file mode 100644index 000000000..3a98683d7Binary files /dev/null and b/tests/e2e/canvas/text-path-visual.spec.ts-snapshots/text-path-rendering-and-selection-openpencil-darwin.png differdiff --git a/tests/engine/core/editor/text/path-edit.test.ts b/tests/engine/core/editor/text/path-edit.test.tsnew file mode 100644index 000000000..dd2653eb1--- /dev/null+++ b/tests/engine/core/editor/text/path-edit.test.ts@@ -0,0 +1,196 @@+import { describe, expect, test } from 'bun:test'++import { SceneGraph } from '@open-pencil/scene-graph'++import { pathTextEditChanges } from '#core/editor/text/path-edit'+import { fontManager } from '#core/text/fonts'+import { getGlyphOutlineMetricsSync } from '#core/text/opentype'++import { expectDefined } from '#tests/helpers/assert'++/** Straight horizontal line, in 400x100 normalized space (zero tangents = no curve). */+function straightLineNetwork() {+ return {+ vertices: [+ { x: 0, y: 50 },+ { x: 400, y: 50 }+ ],+ segments: [{ start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }],+ regions: []+ }+}++describe('pathTextEditChanges — reflow on character edit', () => {+ test('re-lays out glyphs along the path instead of clearing them', async () => {+ const font = await fontManager.fetchBundledFont('/Inter-Regular.ttf')+ expect(font).toBeTruthy()+ if (!font) return+ fontManager.markLoaded('Inter', 'Regular', font)++ 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, {+ x: 0,+ y: 0,+ width: 400,+ height: 100,+ text: 'AB',+ fontFamily: 'Inter',+ fontWeight: 400,+ italic: false,+ fontSize: 40,+ textPathBox: { ...box },+ derivedTextGlyphs: [+ { commandsBlob: new Uint8Array(4), x: 50, y: 50, fontSize: 40, rotation: 0 },+ { commandsBlob: new Uint8Array(4), x: 90, y: 50, fontSize: 40, rotation: 0 }+ ]+ })+ node.textPathData = {+ network: straightLineNetwork(),+ normalizedSize: { x: 400, y: 100 },+ tValue: 0,+ forward: true+ }++ const changes = pathTextEditChanges(node, { text: 'Edited' })++ const glyphs = expectDefined(changes.derivedTextGlyphs, 'reflowed glyphs')+ expect(glyphs.length).toBe('Edited'.length)+ expect(changes.strokeGeometry).toEqual([])+ // Glyphs walk forward along the path — not stacked at one point.+ expect(glyphs[glyphs.length - 1].x).toBeGreaterThan(glyphs[0].x)+ for (const g of glyphs) {+ expect(g.commandsBlob.length).toBeGreaterThan(0)+ expect(Number.isFinite(g.x)).toBe(true)+ expect(Number.isFinite(g.y)).toBe(true)+ }+ })++ test('uses opentype.js glyph positioning when the font supports its shaping pipeline', async () => {+ const font = await fontManager.fetchBundledFont('/Inter-Regular.ttf')+ expect(font).toBeTruthy()+ if (!font) return+ fontManager.markLoaded('Inter', 'Regular', font)++ const metrics = getGlyphOutlineMetricsSync('Inter', 'Regular', 'AV ffi', 40)+ expect(metrics).toBeTruthy()+ expect(metrics?.length).toBeGreaterThan(0)+ for (let index = 1; index < (metrics?.length ?? 0); index++) {+ expect(metrics?.[index]?.x).toBeGreaterThan(metrics?.[index - 1]?.x ?? -Infinity)+ }+ })++ test('folds letterSpacing into the pen-walk advance', async () => {+ const font = await fontManager.fetchBundledFont('/Inter-Regular.ttf')+ expect(font).toBeTruthy()+ if (!font) return+ fontManager.markLoaded('Inter', 'Regular', font)++ function lastGlyphX(letterSpacing: number): number {+ 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, {+ x: 0,+ y: 0,+ width: 400,+ height: 100,+ text: 'AB',+ fontFamily: 'Inter',+ fontWeight: 400,+ italic: false,+ fontSize: 40,+ letterSpacing,+ textPathBox: { ...box },+ derivedTextGlyphs: [+ { commandsBlob: new Uint8Array(4), x: 50, y: 50, fontSize: 40, rotation: 0 },+ { commandsBlob: new Uint8Array(4), x: 90, y: 50, fontSize: 40, rotation: 0 }+ ]+ })+ node.textPathData = {+ network: straightLineNetwork(),+ normalizedSize: { x: 400, y: 100 },+ tValue: 0,+ forward: true+ }+ const changes = pathTextEditChanges(node, { text: 'ABCD' })+ const glyphs = expectDefined(changes.derivedTextGlyphs, 'reflowed glyphs')+ return glyphs[glyphs.length - 1].x+ }++ // Wider tracking pushes the last glyph further along the (straight) path.+ expect(lastGlyphX(20)).toBeGreaterThan(lastGlyphX(0))+ })++ test('clears stale path glyphs when text becomes empty', () => {+ const graph = new SceneGraph()+ const page = expectDefined(graph.getPages()[0])+ const node = graph.createNode('TEXT', page.id, {+ text: 'AB',+ textPathBox: { x: 0, y: 0, width: 100, height: 50 },+ strokeGeometry: [{ windingRule: 'NONZERO', commandsBlob: new Uint8Array(4) }],+ derivedTextGlyphs: [+ { commandsBlob: new Uint8Array(4), x: 10, y: 20, fontSize: 20, rotation: 0 }+ ]+ })++ expect(pathTextEditChanges(node, { text: ' ' })).toEqual({+ derivedTextGlyphs: null,+ strokeGeometry: []+ })+ })++ test('falls back to {} when the node has no path data', () => {+ const graph = new SceneGraph()+ const page = expectDefined(graph.getPages()[0])+ const node = graph.createNode('TEXT', page.id, {+ text: 'AB',+ derivedTextGlyphs: [+ { commandsBlob: new Uint8Array(4), x: 0, y: 0, fontSize: 40, rotation: 0 }+ ]+ })+ // No textPathData / textPathBox — not reflowable.+ expect(pathTextEditChanges(node, { text: 'Edited' })).toEqual({})+ })++ test('uses pending fontSize from the same update batch', async () => {+ const font = await fontManager.fetchBundledFont('/Inter-Regular.ttf')+ expect(font).toBeTruthy()+ if (!font) return+ fontManager.markLoaded('Inter', 'Regular', font)++ 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, {+ x: 0,+ y: 0,+ width: 400,+ height: 100,+ text: 'AB',+ fontFamily: 'Inter',+ fontWeight: 400,+ italic: false,+ fontSize: 20,+ textPathBox: { ...box },+ derivedTextGlyphs: [+ { commandsBlob: new Uint8Array(4), x: 50, y: 50, fontSize: 20, rotation: 0 },+ { commandsBlob: new Uint8Array(4), x: 90, y: 50, fontSize: 20, rotation: 0 }+ ]+ })+ node.textPathData = {+ network: straightLineNetwork(),+ normalizedSize: { x: 400, y: 100 },+ tValue: 0,+ forward: true+ }++ const changes = pathTextEditChanges(node, { text: 'Hi', fontSize: 48 })+ const glyphs = expectDefined(changes.derivedTextGlyphs, 'reflowed glyphs')+ expect(glyphs.length).toBe(2)+ for (const g of glyphs) {+ expect(g.fontSize).toBe(48)+ }+ })+})diff --git a/tests/engine/core/editor/text/start-editing-gate.test.ts b/tests/engine/core/editor/text/start-editing-gate.test.tsnew file mode 100644index 000000000..898265e7f--- /dev/null+++ b/tests/engine/core/editor/text/start-editing-gate.test.ts@@ -0,0 +1,54 @@+import { describe, expect, test } from 'bun:test'++import { createEditor } from '@open-pencil/core/editor'++import { fontManager } from '#core/text/fonts'++/**+ * Path text can only be edited when the font's glyph OUTLINES are available to+ * reflow. Unavailable-font path text is a baked graphic: startTextEditing must+ * refuse to enter edit mode (so a keystroke can't corrupt the lettering). Non-+ * path text and available-font path text edit normally.+ */+describe('startTextEditing — path-text font gate', () => {+ test('blocks unavailable-font path text, allows available-font + normal text', async () => {+ const font = await fontManager.fetchBundledFont('/Inter-Regular.ttf')+ expect(font).toBeTruthy()+ if (!font) return+ fontManager.markLoaded('Inter', 'Regular', font)++ const editor = createEditor()+ const page = editor.state.currentPageId+ const box = { x: 0, y: 0, width: 200, height: 200 }++ // Path text, font AVAILABLE → editable.+ const editable = editor.graph.createNode('TEXT', page, {+ text: 'ab',+ fontFamily: 'Inter',+ fontWeight: 400,+ textPathBox: { ...box }+ })+ editor.startTextEditing(editable.id)+ expect(editor.state.editingTextId).toBe(editable.id)++ // Path text, font UNAVAILABLE → blocked (stays a baked graphic). Starting on+ // it also commits the previous edit, so editingTextId must end up null.+ const baked = editor.graph.createNode('TEXT', page, {+ text: 'ab',+ fontFamily: 'NoSuchFont',+ fontWeight: 400,+ textPathBox: { ...box }+ })+ editor.startTextEditing(baked.id)+ expect(editor.state.editingTextId).toBeNull()++ // Plain text (no path) with an unavailable font → still editable.+ const plain = editor.graph.createNode('TEXT', page, {+ text: 'ab',+ fontFamily: 'NoSuchFont',+ fontWeight: 400+ })+ editor.startTextEditing(plain.id)+ expect(editor.state.editingTextId).toBe(plain.id)+ })+})diff --git a/tests/engine/core/text/path-layout.test.ts b/tests/engine/core/text/path-layout.test.tsnew file mode 100644index 000000000..ad4f830ab--- /dev/null+++ b/tests/engine/core/text/path-layout.test.ts@@ -0,0 +1,372 @@+import { describe, expect, test } from 'bun:test'++import { SceneGraph } from '@open-pencil/scene-graph'+import type { SceneNode, VectorNetwork } from '@open-pencil/scene-graph'++import {+ calibratePathTextLayout,+ fitTextPathBoxToGlyphs,+ getTextPathData,+ layoutPathTextFromAdvances,+ pathTextSelectionBand,+ pointAtArc,+ reflowPathTextGlyphs,+ sampleTextPath+} from '#core/text/path'++import { expectDefined } from '#tests/helpers/assert'+import { loadFigFixture } from '#tests/helpers/fig-fixtures'++/** Signed shortest angular difference a - b. */+function angleDiff(a: number, b: number): number {+ return Math.atan2(Math.sin(a - b), Math.cos(a - b))+}++const LOCAL_CIRCLE_TEXT = 'tests/fixtures/circle-text.fig'++describe('path-text reflow — real fixture (optional local)', () => {+ test('identity reflow reproduces baked glyphs; anisotropic reflow re-places without touching outlines', async () => {+ const graph = await loadFigFixture(LOCAL_CIRCLE_TEXT)+ if (!graph) return+ const node = expectDefined(+ [...graph.getAllNodes()].find((n) => n.name === 'ArnoCoenen.art'),+ 'path text node'+ )+ const data = expectDefined(getTextPathData(node), 'text path data')+ const box = expectDefined(node.textPathBox, 'textPathBox')+ const glyphs = expectDefined(node.derivedTextGlyphs, 'imported glyphs')+ expect(glyphs.length).toBeGreaterThan(0)++ const layout = expectDefined(calibratePathTextLayout(glyphs, data, box), 'layout')++ // Identity reflow (same box) must reproduce every baked glyph.+ const identity = expectDefined(+ reflowPathTextGlyphs(glyphs, data, layout, box),+ 'identity reflow'+ )+ expect(identity).toHaveLength(glyphs.length)+ for (let i = 0; i < glyphs.length; i++) {+ const dist = Math.hypot(identity[i].x - glyphs[i].x, identity[i].y - glyphs[i].y)+ expect(dist).toBeLessThan(1)+ const rot = Math.abs(angleDiff(identity[i].rotation ?? 0, glyphs[i].rotation ?? 0))+ expect(rot).toBeLessThan(0.01)+ }++ // Anisotropic reflow: 0.5x width, 1.0x height.+ const half = { x: box.x * 0.5, y: box.y, width: box.width * 0.5, height: box.height }+ const reflowed = expectDefined(+ reflowPathTextGlyphs(glyphs, data, layout, half),+ 'anisotropic reflow'+ )+ let changedPairs = 0+ let pairs = 0+ for (let i = 0; i < glyphs.length; i++) {+ // Re-layout, not geometric squash: no residual glyph scale...+ expect(reflowed[i].scaleX).toBeUndefined()+ expect(reflowed[i].scaleY).toBeUndefined()+ // ...and the outline blob itself is byte-identical to the source glyph's.+ expect(+ Buffer.from(reflowed[i].commandsBlob).equals(Buffer.from(glyphs[i].commandsBlob))+ ).toBe(true)+ for (let j = i + 1; j < glyphs.length; j++) {+ pairs+++ const before = Math.hypot(glyphs[i].x - glyphs[j].x, glyphs[i].y - glyphs[j].y)+ const after = Math.hypot(reflowed[i].x - reflowed[j].x, reflowed[i].y - reflowed[j].y)+ if (Math.abs(after - before) > 1) changedPairs+++ }+ }+ // Glyphs moved relative to each other — the layout changed, the shapes did not.+ expect(pairs).toBeGreaterThan(0)+ expect(changedPairs).toBeGreaterThan(0)+ })++ // Task 3.3 / 4.1: the selection overlay strokes sampleTextPath(data, fitted),+ // where `fitted` = fitTextPathBoxToGlyphs. Guard that the fitted curve tracks+ // the imported glyph baselines TIGHTLY — the raw textPathBox is ~4% too small+ // and sits ~30px off (the visible offset bug this fit corrects).+ function maxGlyphToPath(+ path: { xs: Float64Array; ys: Float64Array },+ glyphs: SceneNode['derivedTextGlyphs'] & object+ ) {+ let max = 0+ for (const g of glyphs) {+ let best = Infinity+ for (let s = 0; s < path.xs.length; s++) {+ best = Math.min(best, Math.hypot(path.xs[s] - g.x, path.ys[s] - g.y))+ }+ max = Math.max(max, best)+ }+ return max+ }++ test('fitted overlay curve + start marker track the imported glyph baselines', async () => {+ const graph = await loadFigFixture(LOCAL_CIRCLE_TEXT)+ if (!graph) return+ const node = expectDefined(+ [...graph.getAllNodes()].find((n) => n.name === 'ArnoCoenen.art'),+ 'path text node'+ )+ const data = expectDefined(getTextPathData(node), 'text path data')+ const box = expectDefined(node.textPathBox, 'textPathBox')+ const glyphs = expectDefined(node.derivedTextGlyphs, 'imported glyphs')++ // Raw textPathBox path is materially off the glyphs (the bug).+ const rawPath = expectDefined(sampleTextPath(data, box), 'raw path')+ expect(maxGlyphToPath(rawPath, glyphs)).toBeGreaterThan(15)++ // The fitted box lands the path ON the glyph baselines.+ const fitted = expectDefined(fitTextPathBoxToGlyphs(data, box, glyphs), 'fitted box')+ // Aspect preserved from textPathBox, so the overlay ovals under a non-uniform+ // resize instead of forcing a circle.+ expect(fitted.width / fitted.height).toBeCloseTo(box.width / box.height, 3)+ 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+ )+ })++ test('fitTextPathBoxToGlyphs returns null with no glyphs to fit', async () => {+ const graph = await loadFigFixture(LOCAL_CIRCLE_TEXT)+ if (!graph) return+ const node = expectDefined(+ [...graph.getAllNodes()].find((n) => n.name === 'ArnoCoenen.art'),+ 'path text node'+ )+ const data = expectDefined(getTextPathData(node), 'text path data')+ const box = expectDefined(node.textPathBox, 'textPathBox')+ expect(fitTextPathBoxToGlyphs(data, box, [])).toBeNull()+ expect(fitTextPathBoxToGlyphs(data, box, null)).toBeNull()+ })+})++// --- Synthetic circle path (always runs) ---++const KAPPA = 0.5523++/** 4-cubic circle, radius 100 centered (128,128), in 256x256 normalized space. */+function circleNetwork(): VectorNetwork {+ const c = 128+ const r = 100+ const k = r * KAPPA+ return {+ vertices: [+ { x: c + r, y: c },+ { x: c, y: c + r },+ { x: c - r, y: c },+ { x: c, y: c - r }+ ],+ segments: [+ { start: 0, end: 1, tangentStart: { x: 0, y: k }, tangentEnd: { x: k, y: 0 } },+ { start: 1, end: 2, tangentStart: { x: -k, y: 0 }, tangentEnd: { x: 0, y: k } },+ { start: 2, end: 3, tangentStart: { x: 0, y: -k }, tangentEnd: { x: -k, y: 0 } },+ { start: 3, end: 0, tangentStart: { x: k, y: 0 }, tangentEnd: { x: 0, y: -k } }+ ],+ regions: []+ }+}++/** Minimal move+line outline blob — layout never reads its contents. */+function glyphBlob(): Uint8Array {+ const blob = new Uint8Array(2 * 9)+ const view = new DataView(blob.buffer)+ blob[0] = 1+ view.setFloat32(1, 0, true)+ view.setFloat32(5, 0, true)+ blob[9] = 2+ view.setFloat32(10, 1, true)+ view.setFloat32(14, 0, true)+ return blob+}++describe('path-text reflow — synthetic circle', () => {+ test('reflowed glyphs stay on the scaled path with tangent-derived rotations', () => {+ const graph = new SceneGraph()+ const page = expectDefined(graph.getPages()[0])+ const box = { x: 0, y: 0, width: 256, height: 256 }+ const node = graph.createNode('TEXT', page.id, {+ x: 0,+ y: 0,+ width: 256,+ height: 256,+ text: 'abc',+ textPathBox: { ...box }+ })+ node.textPathData = {+ network: circleNetwork(),+ normalizedSize: { x: 256, y: 256 },+ tValue: 0.25,+ forward: false+ }++ const data = expectDefined(getTextPathData(node), 'synthetic path data')+ expect(data.forward).toBe(false)++ // Seed glyphs with the engine's own pen walk so the test is self-consistent.+ const seeds = expectDefined(+ layoutPathTextFromAdvances(data, box, 0.25, 0, [+ { commandsBlob: glyphBlob(), fontSize: 40, advance: 0.6 },+ { commandsBlob: glyphBlob(), fontSize: 40, advance: 0.6 },+ { commandsBlob: glyphBlob(), fontSize: 40, advance: 0.6 }+ ]),+ 'seed glyphs'+ )+ expect(seeds).toHaveLength(3)++ const layout = expectDefined(calibratePathTextLayout(seeds, data, box), 'layout')++ // Identity round-trip: calibrate → reflow on the same box reproduces the seeds.+ const identity = expectDefined(reflowPathTextGlyphs(seeds, data, layout, box), 'identity')+ for (let i = 0; i < seeds.length; i++) {+ expect(Math.hypot(identity[i].x - seeds[i].x, identity[i].y - seeds[i].y)).toBeLessThan(1)+ expect(Math.abs(angleDiff(identity[i].rotation ?? 0, seeds[i].rotation ?? 0))).toBeLessThan(+ 0.01+ )+ }++ // Reflow into a 2x-wide box.+ const wide = { x: 0, y: 0, width: 512, height: 256 }+ const reflowed = expectDefined(reflowPathTextGlyphs(seeds, data, layout, wide), 'reflow')+ const path = expectDefined(sampleTextPath(data, wide), 'sampled wide path')++ for (let i = 0; i < reflowed.length; i++) {+ const g = reflowed[i]+ expect(g.scaleX).toBeUndefined()+ expect(g.scaleY).toBeUndefined()++ // Nearest sampled path point — glyph baselines must sit on the scaled path.+ let best = 0+ let bestD = Infinity+ for (let s = 0; s < path.xs.length; s++) {+ const d = Math.hypot(path.xs[s] - g.x, path.ys[s] - g.y)+ if (d < bestD) {+ bestD = d+ best = s+ }+ }+ expect(bestD).toBeLessThan(2)++ // Rotation follows the LOCAL tangent (negated: forward=false) plus the+ // calibrated phase for this glyph.+ const a = Math.max(0, best - 1)+ const b = Math.min(path.xs.length - 1, best + 1)+ const tx = -(path.xs[b] - path.xs[a])+ const ty = -(path.ys[b] - path.ys[a])+ const expected = -Math.atan2(ty, tx) + layout.phases[i]+ expect(Math.abs(angleDiff(g.rotation ?? 0, expected))).toBeLessThan(0.05)+ }++ // The wider path actually moved the glyphs.+ expect(reflowed.some((g, i) => Math.hypot(g.x - seeds[i].x, g.y - seeds[i].y) > 1)).toBe(true)+ })+})++// --- Selection overlay: shared path helpers + eligibility (task 3.1/3.2) ---++/** Build the synthetic circle TEXT_PATH node used across overlay tests. */+function makeCircleTextPathNode(tValue = 0, forward = true): SceneNode {+ const graph = new SceneGraph()+ const page = expectDefined(graph.getPages()[0])+ const node = graph.createNode('TEXT', page.id, {+ x: 0,+ y: 0,+ width: 256,+ height: 256,+ text: 'abc',+ textPathBox: { x: 0, y: 0, width: 256, height: 256 }+ })+ node.textPathData = {+ network: circleNetwork(),+ normalizedSize: { x: 256, y: 256 },+ tValue,+ forward+ }+ return node+}++describe('selection overlay — path helpers', () => {+ test('pointAtArc lands on the curve at an arc fraction (start-marker geometry)', () => {+ const node = makeCircleTextPathNode()+ const data = expectDefined(getTextPathData(node), 'data')+ const box = expectDefined(node.textPathBox, 'box')+ const path = expectDefined(sampleTextPath(data, box), 'path')++ // Radius-100 circle centered at (128,128): every arc point is 100 from center.+ const start = pointAtArc(path, 0)+ expect(Math.hypot(start.x - 128, start.y - 128)).toBeCloseTo(100, 0)++ const mid = pointAtArc(path, 0.25 * path.length)+ expect(Math.hypot(mid.x - 128, mid.y - 128)).toBeCloseTo(100, 0)+ // Moved along the arc from the start.+ expect(Math.hypot(mid.x - start.x, mid.y - start.y)).toBeGreaterThan(1)+ })++ 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.+ const data = expectDefined(getTextPathData(node), 'data')+ const box = expectDefined(node.textPathBox, 'box')+ const path = expectDefined(sampleTextPath(data, box), 'path')++ // Curve, not rectangle: every sample sits at ~radius 100 from box center;+ // a bounding rectangle would give corner distances ~181 and edges 100.+ let rMin = Infinity+ let rMax = 0+ for (let i = 0; i < path.xs.length; i++) {+ const rr = Math.hypot(path.xs[i] - 128, path.ys[i] - 128)+ rMin = Math.min(rMin, rr)+ rMax = Math.max(rMax, rr)+ }+ expect(rMax - rMin).toBeLessThan(1)+ expect(Math.abs(rMax - 100)).toBeLessThan(1)++ // Ineligible: no materialized path data → null → the overlay branch is+ // skipped and drawNodeSelection (rectangle) runs.+ const graph = new SceneGraph()+ const page = expectDefined(graph.getPages()[0])+ const bare = graph.createNode('TEXT', page.id, {+ x: 0,+ y: 0,+ width: 100,+ height: 40,+ text: 'x'+ })+ 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)+ }+ })+})diff --git a/tests/engine/editor/text-auto-resize.test.ts b/tests/engine/editor/text-auto-resize.test.tsindex 39dad4194..4d4cca2f2 100644--- a/tests/engine/editor/text-auto-resize.test.ts+++ b/tests/engine/editor/text-auto-resize.test.ts@@ -51,6 +51,51 @@ describe('editor text auto-resize updates', () => {expect(getNodeOrThrow(editor.graph, text.id).height).toBe(48)})+ test('direct edits drop stale path glyphs without paragraph auto-resize', () => {+ // A mutation outside the font-gated canvas edit session cannot reflow the+ // glyphs. It must clear stale outlines/path identity without applying+ // paragraph auto-resize to the imported path-text box.+ setTextMeasurer((node) => ({ width: node.width, height: node.lineHeight ?? 20 }))++ const editor = createEditor()+ const glyphs = [+ { commandsBlob: new Uint8Array([1, 0, 0, 0, 0]), x: 0, y: 0, fontSize: 80 },+ { commandsBlob: new Uint8Array([1, 0, 0, 0, 0]), x: 40, y: 5, fontSize: 80 }+ ]+ const text = editor.graph.createNode('TEXT', editor.state.currentPageId, {+ text: 'ab',+ textAutoResize: 'HEIGHT',+ width: 200,+ height: 200,+ fontFamily: 'NoSuchFont',+ fontSize: 80,+ textPathData: {+ network: {+ vertices: [+ { x: 0, y: 100 },+ { x: 200, y: 100 }+ ],+ segments: [+ { start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }+ ],+ regions: []+ },+ normalizedSize: { x: 200, y: 200 },+ tValue: 0,+ forward: true+ },+ textPathBox: { x: 0, y: 0, width: 200, height: 200 },+ derivedTextGlyphs: glyphs+ })++ editor.updateNode(text.id, { text: 'abc' })++ const updated = getNodeOrThrow(editor.graph, text.id)+ expect(updated.derivedTextGlyphs).toBeNull()+ expect(updated.textPathData).toBeNull()+ expect(updated.height).toBe(200)+ })+test('font size changes resize width-and-height text', () => {setTextMeasurer((node) => ({ width: node.fontSize * 4, height: node.fontSize * 2 }))diff --git a/tests/engine/io/fig/export/path-text-reflow-export.test.ts b/tests/engine/io/fig/export/path-text-reflow-export.test.tsnew file mode 100644index 000000000..41ed77164--- /dev/null+++ b/tests/engine/io/fig/export/path-text-reflow-export.test.ts@@ -0,0 +1,99 @@+import { describe, expect, test } from 'bun:test'++import { parseFigBuffer } from '@open-pencil/fig'++import { exportFigFile } from '#core/io/formats/fig/export'+import { calibratePathTextLayout, getTextPathData, reflowPathTextGlyphs } from '#core/text/path'++import { expectDefined } from '#tests/helpers/assert'+import { loadFigFixture } from '#tests/helpers/fig-fixtures'++const LOCAL_CIRCLE_TEXT = 'tests/fixtures/circle-text.fig'++/** exportFigFile returns a Uint8Array; parseFigBuffer takes an ArrayBuffer. */+function reparse(out: Uint8Array) {+ return parseFigBuffer(out.buffer.slice(out.byteOffset, out.byteOffset + out.byteLength))+}++describe('TEXT_PATH reflow export hygiene (optional local)', () => {+ test('reflowed node exports no strokeGeometry and reflowed glyph positions', async () => {+ const graph = await loadFigFixture(LOCAL_CIRCLE_TEXT)+ if (!graph) return++ const node = expectDefined(+ [...graph.getAllNodes()].find((n) => n.name === 'ArnoCoenen.art'),+ 'path text node'+ )+ const data = expectDefined(getTextPathData(node), 'text path data')+ const box = expectDefined(node.textPathBox, 'textPathBox')+ const origGlyphs = expectDefined(node.derivedTextGlyphs, 'imported glyphs')+ const layout = expectDefined(calibratePathTextLayout(origGlyphs, data, box), 'layout')+ const halfBox = {+ x: box.x * 0.5,+ y: box.y * 0.5,+ width: box.width * 0.5,+ height: box.height * 0.5+ }+ const reflowed = expectDefined(+ reflowPathTextGlyphs(origGlyphs, data, layout, halfBox),+ 'reflowed glyphs'+ )+ // Sanity: reflow at half size must actually move the glyphs.+ expect(reflowed.some((g, i) => Math.abs(g.x - origGlyphs[i].x) > 1)).toBe(true)++ // Simulate the state resize.ts's reflow leaves behind: scene strokeGeometry+ // emptied while rawNodeFields still holds the ORIGINAL baked silhouettes+ // plus vectorData/textPathStart. preserveSourceMetadataDuring keeps the raw+ // fields — a bare updateNode would wipe them (clearEditedSourceMetadata)+ // and hide exactly the stale-silhouette fallback this test guards against.+ graph.preserveSourceMetadataDuring(() => {+ graph.updateNode(node.id, {+ strokeGeometry: [],+ textPathBox: halfBox,+ derivedTextGlyphs: reflowed+ })+ })+ const updated = expectDefined(graph.getNode(node.id), 'updated node')+ expect(updated.strokeGeometry.length).toBe(0)+ expect('strokeGeometry' in updated.source.fig.rawNodeFields).toBe(true)++ const out = await exportFigFile(graph)+ const reparsed = reparse(out)+ const exported = expectDefined(+ reparsed.nodeChanges.find((nc) => nc.name === 'ArnoCoenen.art'),+ 'exported node change'+ )+ expect(exported.type).toBe('TEXT_PATH')++ // No strokeGeometry at all: neither from the (empty) scene field nor from+ // stale rawNodeFields — silhouettes are re-derived from the glyphs.+ expect(exported.strokeGeometry).toBeUndefined()++ // derivedTextData carries the reflowed positions, not raw pre-resize ones.+ const glyphs = expectDefined(exported.derivedTextData?.glyphs, 'exported glyphs')+ expect(glyphs.length).toBe(reflowed.length)+ for (let i = 0; i < reflowed.length; i++) {+ expect(expectDefined(glyphs[i]?.position?.x)).toBeCloseTo(reflowed[i].x, 2)+ expect(expectDefined(glyphs[i]?.position?.y)).toBeCloseTo(reflowed[i].y, 2)+ }++ // The layout path payload survives so reimport can reflow again.+ const rawExported = exported as typeof exported & Record<string, unknown>+ expect(rawExported.vectorData).toBeDefined()+ expect(rawExported.textPathStart).toBeDefined()+ })++ test('unmodified fixture still round-trips WITH strokeGeometry', async () => {+ const graph = await loadFigFixture(LOCAL_CIRCLE_TEXT)+ if (!graph) return++ const out = await exportFigFile(graph)+ const reparsed = reparse(out)+ const exported = expectDefined(+ reparsed.nodeChanges.find((nc) => nc.name === 'ArnoCoenen.art'),+ 'exported node change'+ )+ expect(exported.type).toBe('TEXT_PATH')+ expect(exported.strokeGeometry?.length ?? 0).toBeGreaterThan(0)+ })+})diff --git a/tests/engine/io/fig/export/rotation-transform.test.ts b/tests/engine/io/fig/export/rotation-transform.test.tsnew file mode 100644index 000000000..98dcaf2f0--- /dev/null+++ b/tests/engine/io/fig/export/rotation-transform.test.ts@@ -0,0 +1,113 @@+/**+ * Rotated nodes must survive an export → reimport with their world position+ * intact. computeExportTransform (serialize.ts) encodes the .fig transform and+ * must be the exact inverse of the import decode (convert.ts), which treats an+ * unflipped rotation as about the node CENTER. A prior AABB-min-corner encode+ * only matched the rotation==0 / flipped branch, so every rotated node drifted+ * on reimport (and a rotated text-on-path sticker slid out of its frame clip).+ */+import { describe, expect, test } from 'bun:test'++import { SceneGraph } from '@open-pencil/scene-graph'+import type { SceneNode } from '@open-pencil/scene-graph'+import { getWorldMatrix } from '@open-pencil/scene-graph/coordinate'+import Matrix from '@open-pencil/scene-graph/matrix'++import { exportFigFile } from '#core/io/formats/fig/export'+import { parseFigFile } from '#core/io/formats/fig/read'++import { loadFigFixture, readFigFixture } from '#tests/helpers/fig-fixtures'++function worldCorners(graph: SceneGraph, name: string) {+ const node = [...graph.getAllNodes()].find((n) => n.name === name)+ if (!node) throw new Error(`node ${name} not found`)+ const m = getWorldMatrix(node, graph)+ return Matrix.mapPoints(m, [0, 0, node.width, 0, node.width, node.height, 0, node.height])+}++async function roundTrip(graph: SceneGraph) {+ const out = await exportFigFile(graph)+ const ab = out.buffer.slice(out.byteOffset, out.byteOffset + out.byteLength) as ArrayBuffer+ return parseFigFile(ab)+}++describe('rotated node transform round-trip', () => {+ test.each([0, 30, -45, 90, 137])('rotation %i° keeps world corners', async (rotation) => {+ const graph = new SceneGraph()+ graph.createNode('RECTANGLE', graph.getPages()[0].id, {+ name: 'R',+ x: 100,+ y: 200,+ width: 300,+ height: 150,+ rotation+ })+ const before = worldCorners(graph, 'R')+ const after = worldCorners(await roundTrip(graph), 'R')+ for (let i = 0; i < before.length; i++) {+ expect(after[i]).toBeCloseTo(before[i], 2)+ }+ })++ test('rotated + off-origin node round-trips', async () => {+ const graph = new SceneGraph()+ graph.createNode('RECTANGLE', graph.getPages()[0].id, {+ name: 'R',+ x: -37.5,+ y: 412.9,+ width: 88,+ height: 220,+ rotation: 62+ })+ const before = worldCorners(graph, 'R')+ const after = worldCorners(await roundTrip(graph), 'R')+ for (let i = 0; i < before.length; i++) {+ expect(after[i]).toBeCloseTo(before[i], 2)+ }+ })+})++// Real imported text-on-path (with stroke silhouettes + an expanded layout box)+// exercises all three coupled fixes: the transform pivot, size/transform pairing+// (exportNodeSize), and the edited-path-text strip (raw glyphs/silhouettes are+// rebuilt from the shifted graph glyphs). Editing one — rotate OR move — used to+// slide it out of its frame clip on reimport.+const CIRCLE_TEXT = 'tests/fixtures/circle-text.fig'+// Skip *visibly* when the LFS fixture isn't fetched (contributor checkout). A+// helper early-return would let Bun report these as passed with 0 assertions.+const describeWithFixture = readFigFixture(CIRCLE_TEXT) ? describe : describe.skip++function glyphWorld(graph: SceneGraph) {+ const node = [...graph.getAllNodes()].find((n) => n.name === 'ArnoCoenen.art')+ if (!node?.derivedTextGlyphs) throw new Error('path-text node not found')+ const m = getWorldMatrix(node, graph)+ return node.derivedTextGlyphs.map((g) => Matrix.mapPoints(m, [g.x, g.y]))+}++async function assertEditKeepsGlyphs(edit: (node: SceneNode) => Partial<SceneNode>) {+ const graph = await loadFigFixture(CIRCLE_TEXT)+ if (!graph) throw new Error('circle-text.fig fixture unavailable')+ const node = [...graph.getAllNodes()].find((n) => n.name === 'ArnoCoenen.art')+ if (!node) throw new Error('node missing')+ graph.updateNode(node.id, edit(node))+ const before = glyphWorld(graph)+ const after = glyphWorld(await roundTrip(graph))+ let maxDrift = 0+ for (let i = 0; i < before.length; i++) {+ maxDrift = Math.max(+ maxDrift,+ Math.hypot(after[i][0] - before[i][0], after[i][1] - before[i][1])+ )+ }+ expect(maxDrift).toBeLessThan(0.05)+}++describeWithFixture('edited imported text-on-path round-trip', () => {+ test.each([0, 30, -55, 90])('rotation %i° keeps glyph world positions', async (rotation) => {+ await assertEditKeepsGlyphs(() => ({ rotation }))+ })++ test('move (rotation 0) keeps glyph world positions', async () => {+ await assertEditKeepsGlyphs((node) => ({ x: node.x + 120, y: node.y - 45 }))+ })+})diff --git a/tests/engine/io/fig/import/derived-symbol-data.test.ts b/tests/engine/io/fig/import/derived-symbol-data.test.tsindex 4519866c5..385f26656 100644--- a/tests/engine/io/fig/import/derived-symbol-data.test.ts+++ b/tests/engine/io/fig/import/derived-symbol-data.test.ts@@ -17,8 +17,8 @@ describe('fig import derived symbol data', () => {const graph = new SceneGraph()const source = graph.createNode('TEXT', pageId(graph), {text: 'Account',- figmaDerivedTextGlyphs: [{ commandsBlob: new Uint8Array([0]), x: 0, y: 10, fontSize: 14 }],- figmaDerivedLayout: { width: 56, height: 20 }+ derivedTextGlyphs: [{ commandsBlob: new Uint8Array([0]), x: 0, y: 10, fontSize: 14 }],+ derivedLayout: { width: 56, height: 20 }})const clone = graph.createNode('TEXT', pageId(graph), {text: 'Account',@@ -32,8 +32,8 @@ describe('fig import derived symbol data', () => {propagateDsdChanges(ctx, new Set([source.id]), new Set())- expect(clone.figmaDerivedTextGlyphs).toEqual(source.figmaDerivedTextGlyphs)- expect(clone.figmaDerivedLayout).toEqual(source.figmaDerivedLayout)+ expect(clone.derivedTextGlyphs).toEqual(source.derivedTextGlyphs)+ expect(clone.derivedLayout).toEqual(source.derivedLayout)})test('inherits derived positions when a clone has an explicit derived size', () => {@@ -43,7 +43,7 @@ describe('fig import derived symbol data', () => {y: 0,width: 136,height: 40,- figmaDerivedLayout: { x: 152, y: 0, width: 136, height: 40 }+ derivedLayout: { x: 152, y: 0, width: 136, height: 40 }})const clone = graph.createNode('INSTANCE', pageId(graph), {x: 136,@@ -51,7 +51,7 @@ describe('fig import derived symbol data', () => {width: 144,height: 48,componentId: source.id,- figmaDerivedLayout: { x: 136, y: 4, width: 144, height: 48 }+ derivedLayout: { x: 136, y: 4, width: 144, height: 48 }})const ctx = {graph,@@ -64,7 +64,7 @@ describe('fig import derived symbol data', () => {expect(graph.getNode(clone.id)).toMatchObject({x: 152,y: 0,- figmaDerivedLayout: {+ derivedLayout: {x: 152,y: 0,width: 144,@@ -79,13 +79,13 @@ describe('fig import derived symbol data', () => {width: 232,height: 24,layoutMode: 'NONE',- figmaDerivedLayout: { width: 232, height: 24 }+ derivedLayout: { width: 232, height: 24 }})const text = graph.createNode('TEXT', parent.id, {width: 256,height: 20,horizontalConstraint: 'STRETCH',- figmaDerivedLayout: { width: 232, height: 20 }+ derivedLayout: { width: 232, height: 20 }})const ctx = {graph,@@ -103,14 +103,14 @@ describe('fig import derived symbol data', () => {width: 232,height: 24,layoutMode: 'NONE',- figmaDerivedLayout: { width: 232 }+ derivedLayout: { width: 232 }})const child = graph.createNode('FRAME', parent.id, {width: 100,height: 20,horizontalConstraint: 'STRETCH',verticalConstraint: 'STRETCH',- figmaDerivedLayout: { height: 20 }+ derivedLayout: { height: 20 }})const ctx = { graph, activeNodeIds: new Set([parent.id, child.id]) } as OverrideContext@@ -210,12 +210,15 @@ describe('fig import derived symbol data', () => {target)- expect(updates.figmaDerivedTextGlyphs).toEqual([+ expect(updates.derivedTextGlyphs).toEqual([{commandsBlob: glyphBlob,x: 4,y: 15,- fontSize: 14+ fontSize: 14,+ // Path text needs per-glyph rotation preserved through import (#396);+ // plain text imports it as 0 rather than dropping the field.+ rotation: 0}])})diff --git a/tests/engine/io/fig/import/instance-regressions.test.ts b/tests/engine/io/fig/import/instance-regressions.test.tsindex 71f3043d2..6fcd986a9 100644--- a/tests/engine/io/fig/import/instance-regressions.test.ts+++ b/tests/engine/io/fig/import/instance-regressions.test.ts@@ -27,7 +27,7 @@ describe('derived instance layout regressions', () => {test('retains imported glyph outlines through non-glyph layout updates', () => {const glyphCount = () =>layoutNodes.filter(- (node) => node.type === 'TEXT' && (node.figmaDerivedTextGlyphs?.length ?? 0) > 0+ (node) => node.type === 'TEXT' && (node.derivedTextGlyphs?.length ?? 0) > 0).lengthexpect(glyphCount()).toBe(43)@@ -101,7 +101,7 @@ describe('derived instance layout regressions', () => {)expect(dividers).toHaveLength(3)const generatedDividers = dividers.filter(- (node) => layoutGraph.getNode(node.componentId)?.figmaDerivedLayout?.y === 13.5+ (node) => layoutGraph.getNode(node.componentId)?.derivedLayout?.y === 13.5)expect(generatedDividers).toHaveLength(3)for (const divider of generatedDividers) expect(divider.y).toBeCloseTo(13.5, 3)@@ -196,7 +196,7 @@ describe('derived instance layout regressions', () => {b: 0.9215686321258545,a: 1})- expect(linkText?.figmaDerivedTextGlyphs).toBeNull()+ expect(linkText?.derivedTextGlyphs).toBeNull()const input = previewChild(graph, nodes, 'Input')const inputRoot = childNamed(graph, input, '_input')diff --git a/tests/engine/io/fig/import/legacy/text.test.ts b/tests/engine/io/fig/import/legacy/text.test.tsindex e3ba0155a..582f44ff5 100644--- a/tests/engine/io/fig/import/legacy/text.test.ts+++ b/tests/engine/io/fig/import/legacy/text.test.ts@@ -48,20 +48,23 @@ describe('fig-import: text properties', () => {[glyphBlob])const n = graph.getChildren(graph.getPages()[0].id)[0]- expect(n.figmaDerivedTextGlyphs).toEqual([+ expect(n.derivedTextGlyphs).toEqual([{commandsBlob: glyphBlob,x: 2,y: 8,- fontSize: 14+ fontSize: 14,+ // Path text needs per-glyph rotation preserved through import (#396);+ // plain text imports it as 0 rather than dropping the field.+ rotation: 0}])graph.updateNode(n.id, { opacity: 0.5 })- expect(graph.getNode(n.id)?.figmaDerivedTextGlyphs).toHaveLength(1)+ expect(graph.getNode(n.id)?.derivedTextGlyphs).toHaveLength(1)graph.updateNode(n.id, { text: 'B' })- expect(graph.getNode(n.id)?.figmaDerivedTextGlyphs).toBeNull()+ expect(graph.getNode(n.id)?.derivedTextGlyphs).toBeNull()})test('uses derived line metrics for imported Figma text rendering', () => {diff --git a/tests/engine/io/fig/import/text-path.test.ts b/tests/engine/io/fig/import/text-path.test.tsnew file mode 100644index 000000000..0967a7706--- /dev/null+++ b/tests/engine/io/fig/import/text-path.test.ts@@ -0,0 +1,290 @@+import { describe, expect, test } from 'bun:test'++import { parseFigBuffer } from '@open-pencil/fig'+import { convertFigmaDerivedTextGlyphs, nodeChangeToProps } from '@open-pencil/fig/node-change'+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 { exportFigFile } from '#core/io/formats/fig/export'+import { encodeVectorNetworkBlob } from '#core/vector'++import { expectDefined } from '#tests/helpers/assert'+import { loadFigFixture } from '#tests/helpers/fig-fixtures'++/** exportFigFile returns a Uint8Array; parseFigBuffer takes an ArrayBuffer. */+function reparse(out: Uint8Array) {+ return parseFigBuffer(out.buffer.slice(out.byteOffset, out.byteOffset + out.byteLength))+}++function emptyBlob(size = 8): Uint8Array {+ return new Uint8Array(size)+}++describe('TEXT_PATH import mapping', () => {+ test('maps TEXT_PATH to TEXT and materializes format-neutral path data', () => {+ const networkBlob = encodeVectorNetworkBlob({+ vertices: [+ { x: 0, y: 0 },+ { x: 100, y: 0 }+ ],+ segments: [{ start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }],+ regions: []+ })+ const props = nodeChangeToProps(+ {+ type: 'TEXT_PATH',+ name: 'Along path',+ fontSize: 24,+ textData: { characters: 'Hello' },+ size: { x: 100, y: 100 },+ vectorData: {+ vectorNetworkBlob: 0,+ normalizedSize: { x: 100, y: 100 },+ styleOverrideTable: []+ },+ textPathStart: { tValue: 0.25, forward: false },+ fillPaints: [+ {+ type: 'SOLID',+ color: { r: 0, g: 0, b: 0, a: 1 },+ opacity: 1,+ visible: true,+ blendMode: 'NORMAL'+ }+ ]+ } as NodeChange,+ [networkBlob]+ )++ expect(props.nodeType).toBe('TEXT')+ expect(props.name).toBe('Along path')+ expect(props.text).toBe('Hello')+ expect(props.textPathData?.tValue).toBe(0.25)+ expect(props.textPathData?.forward).toBe(false)+ expect(props.textPathData?.network.vertices).toHaveLength(2)+ })++ test('preserves glyph rotation from derivedTextData', () => {+ const blob = emptyBlob(16)+ const glyphs = convertFigmaDerivedTextGlyphs(+ {+ glyphs: [+ {+ commandsBlob: 0,+ position: { x: 10, y: 20 },+ fontSize: 80,+ rotation: -1.75+ },+ {+ commandsBlob: 0,+ position: { x: 12, y: 22 },+ fontSize: 80,+ rotation: 0+ }+ ]+ },+ [blob]+ )++ expect(glyphs).toHaveLength(2)+ expect(glyphs[0]?.rotation).toBeCloseTo(-1.75, 5)+ expect(glyphs[0]?.x).toBe(10)+ expect(glyphs[0]?.y).toBe(20)+ expect(glyphs[0]?.fontSize).toBe(80)+ expect(glyphs[1]?.rotation).toBe(0)+ })+})++const LOCAL_CIRCLE_TEXT = 'tests/fixtures/circle-text.fig'++describe('TEXT_PATH real fixture (optional local)', () => {+ test('imports circular path text without RECTANGLE occlusion type', async () => {+ const graph = await loadFigFixture(LOCAL_CIRCLE_TEXT)+ if (!graph) return++ const pathText = expectDefined(+ [...graph.getAllNodes()].find((n) => n.name === 'ArnoCoenen.art'),+ 'path text node'+ )+ expect(pathText.type).toBe('TEXT')+ expect(pathText.type).not.toBe('RECTANGLE')+ expect(pathText.text).toContain('ArnoCoenen')+ expect(pathText.textPathData).not.toBeNull()+ expect(pathText.derivedTextGlyphs?.length).toBeGreaterThan(0)+ expect(pathText.derivedTextGlyphs?.some((g) => (g.rotation ?? 0) !== 0)).toBe(true)+ expect(pathText.strokeGeometry.length).toBeGreaterThan(0)++ // Multi-color logo sibling must remain a VECTOR (not covered by type fallback)+ const icon = expectDefined(+ [...graph.getAllNodes()].find((n) => n.name === 'ArnoIcon' && n.type === 'VECTOR'),+ 'ArnoIcon vector'+ )+ expect(icon.fillGeometry.length).toBeGreaterThan(0)++ // Unedited export preserves TEXT_PATH type+ const out = await exportFigFile(graph)+ const reparsed = reparse(out)+ const exported = reparsed.nodeChanges.find((nc) => nc.name === 'ArnoCoenen.art')+ expect(exported?.type).toBe('TEXT_PATH')+ const rotations = exported?.derivedTextData?.glyphs?.map((g) => g.rotation ?? 0) ?? []+ expect(rotations.some((r) => r !== 0)).toBe(true)+ })+})++function unitSquareBlob(): Uint8Array {+ const blob = new Uint8Array(1 + 4 * 9 + 1)+ const view = new DataView(blob.buffer)+ const pts = [+ [1, 0, 0],+ [2, 1, 0],+ [2, 1, 1],+ [2, 0, 1]+ ] as const+ let offset = 0+ for (const [cmd, x, y] of pts) {+ blob[offset] = cmd+ view.setFloat32(offset + 1, x, true)+ view.setFloat32(offset + 5, y, true)+ offset += 9+ }+ return blob+}++describe('TEXT_PATH resize export', () => {+ test('bakes glyph scaleX/scaleY into blobs — Kiwi Glyph has no scale field', async () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ graph.createNode('TEXT', page.id, {+ text: 'A',+ width: 100,+ height: 100,+ textPathData: {+ network: { vertices: [], segments: [], regions: [] },+ normalizedSize: { x: 100, y: 100 },+ tValue: 0,+ forward: true+ },+ derivedTextGlyphs: [+ {+ commandsBlob: unitSquareBlob(),+ x: 10,+ y: 20,+ fontSize: 40,+ rotation: Math.PI / 2,+ scaleX: 0.5,+ scaleY: 1+ }+ ]+ })++ const out = await exportFigFile(graph)+ const reparsed = reparse(out)+ const exported = expectDefined(reparsed.nodeChanges.find((nc) => nc.type === 'TEXT_PATH'))+ const glyph = expectDefined(exported.derivedTextData?.glyphs?.[0])+ const blob = expectDefined(reparsed.blobs[expectDefined(glyph.commandsBlob)])++ // At θ=π/2 the horizontal squash lands on the glyph's local Y axis:+ // (1,1) → (1,0.5). Without baking, reload would draw unscaled shapes at+ // scaled positions (the DomeSticker save/reopen garble).+ const view = new DataView(blob.buffer, blob.byteOffset)+ expect(view.getFloat32(2 * 9 + 1, true)).toBeCloseTo(1, 4)+ expect(view.getFloat32(2 * 9 + 5, true)).toBeCloseTo(0.5, 4)+ })+})++describe('TEXT_PATH raw payload round-trip (synthetic)', () => {+ test('vectorData + textPathStart survive .fig export unchanged', async () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const networkBlob = encodeVectorNetworkBlob({+ vertices: [+ { x: 0, y: 0 },+ { x: 100, y: 0 }+ ],+ segments: [{ start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }],+ regions: []+ })+ const node = graph.createNode('TEXT', page.id, {+ text: 'A',+ width: 100,+ height: 100,+ textPathData: {+ network: {+ vertices: [+ { x: 0, y: 0 },+ { x: 100, y: 0 }+ ],+ segments: [+ { start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }+ ],+ regions: []+ },+ normalizedSize: { x: 100, y: 100 },+ tValue: 0.3,+ forward: false+ },+ derivedTextGlyphs: [+ { commandsBlob: unitSquareBlob(), x: 10, y: 20, fontSize: 40, rotation: 0 }+ ]+ })+ node.source.fig.rawNodeFields = {+ vectorData: {+ vectorNetworkBlob: { __openPencilFigmaBlob: networkBlob },+ normalizedSize: { x: 100, y: 100 }+ },+ textPathStart: { tValue: 0.3, forward: false }+ }++ const out = await exportFigFile(graph)+ const reparsed = reparse(out)+ const exported = expectDefined(reparsed.nodeChanges.find((nc) => nc.type === 'TEXT_PATH'))++ const rawExported = exported as typeof exported & Record<string, unknown>+ const vectorData = rawExported.vectorData as {+ vectorNetworkBlob?: number+ normalizedSize?: Vector+ }+ expect(vectorData.normalizedSize).toEqual({ x: 100, y: 100 })+ const blobIndex = expectDefined(vectorData.vectorNetworkBlob, 'vectorNetworkBlob index')+ const exportedBlob = expectDefined(reparsed.blobs[blobIndex], 'exported network blob')+ expect(Buffer.from(exportedBlob).equals(Buffer.from(networkBlob))).toBe(true)++ const textPathStart = rawExported.textPathStart as { tValue?: number; forward?: boolean }+ expect(textPathStart.tValue).toBeCloseTo(0.3, 6)+ expect(textPathStart.forward).toBe(false)+ })+})++describe('TEXT_PATH edit invalidation', () => {+ test('clears format-neutral path data when text content is edited', () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const node = graph.createNode('TEXT', page.id, {+ text: 'ArnoCoenen.art',+ textPathBox: { x: 0, y: 0, width: 100, height: 100 },+ textPathData: {+ network: { vertices: [], segments: [], regions: [] },+ normalizedSize: { x: 1, y: 1 },+ tValue: 0,+ forward: true+ },+ derivedTextGlyphs: [+ {+ commandsBlob: emptyBlob(),+ x: 0,+ y: 0,+ fontSize: 80,+ rotation: -1.5+ }+ ]+ })++ graph.updateNode(node.id, { text: 'Edited' })++ const updated = expectDefined(graph.getNode(node.id))+ expect(updated.derivedTextGlyphs).toBeNull()+ expect(updated.textPathData).toBeNull()+ expect(updated.textPathBox).not.toBeNull()+ })+})diff --git a/tests/engine/layout/auto-layout/imported-derived-layout.test.ts b/tests/engine/layout/auto-layout/imported-derived-layout.test.tsindex ecb2d93fc..28aadbe14 100644--- a/tests/engine/layout/auto-layout/imported-derived-layout.test.ts+++ b/tests/engine/layout/auto-layout/imported-derived-layout.test.ts@@ -34,7 +34,7 @@ describe('imported auto-layout bounds', () => {align: 'OUTSIDE'}],- figmaDerivedLayout: { x: 0, y: 0, width: 280, height: 44 }+ derivedLayout: { x: 0, y: 0, width: 280, height: 44 }})const wrapper = graph.createNode('FRAME', frame.id, {x: 2,@@ -73,7 +73,7 @@ describe('imported auto-layout bounds', () => {align: 'OUTSIDE'}],- figmaDerivedLayout: { x: 0, y: 0, width: 276, height: 40 }+ derivedLayout: { x: 0, y: 0, width: 276, height: 40 }})graph.createNode('TEXT', field.id, {x: 12,@@ -132,7 +132,7 @@ describe('imported auto-layout bounds', () => {align: 'CENTER'}],- figmaDerivedLayout: { x: 0, y: 0, width: 200, height: 1 }+ derivedLayout: { x: 0, y: 0, width: 200, height: 1 }})const following = graph.createNode('RECTANGLE', column.id, { width: 200, height: 20 })@@ -157,14 +157,14 @@ describe('imported auto-layout bounds', () => {height: 14,layoutMode: 'HORIZONTAL',layoutGrow: 1,- figmaDerivedLayout: { width: 136, height: 14 }+ derivedLayout: { width: 136, height: 14 }})const second = graph.createNode('INSTANCE', row.id, {width: 136,height: 40,layoutMode: 'HORIZONTAL',layoutGrow: 1,- figmaDerivedLayout: { width: 136, height: 40 }+ derivedLayout: { width: 136, height: 40 }})graph.createNode('RECTANGLE', first.id, { width: 200, height: 14 })@@ -191,14 +191,14 @@ describe('imported auto-layout bounds', () => {height: 40,layoutMode: 'HORIZONTAL',layoutGrow: 1,- figmaDerivedLayout: { width: 136, height: 40 }+ derivedLayout: { width: 136, height: 40 }})const second = graph.createNode('INSTANCE', row.id, {width: 152,height: 40,layoutMode: 'HORIZONTAL',layoutGrow: 1,- figmaDerivedLayout: { width: 152, height: 40 }+ derivedLayout: { width: 152, height: 40 }})computeAllLayouts(graph)@@ -223,14 +223,14 @@ describe('imported auto-layout bounds', () => {height: 14,layoutMode: 'HORIZONTAL',layoutGrow: 1,- figmaDerivedLayout: { width: 136, height: 14 }+ derivedLayout: { width: 136, height: 14 }})const second = graph.createNode('INSTANCE', row.id, {width: 136,height: 40,layoutMode: 'HORIZONTAL',layoutGrow: 1,- figmaDerivedLayout: { width: 136, height: 40 }+ derivedLayout: { width: 136, height: 40 }})computeAllLayouts(graph)@@ -248,7 +248,7 @@ describe('imported auto-layout bounds', () => {layoutMode: 'VERTICAL',primaryAxisSizing: 'FIXED',counterAxisSizing: 'FIXED',- figmaDerivedLayout: { width: 302, height: 60 }+ derivedLayout: { width: 302, height: 60 }})const label = graph.createNode('INSTANCE', column.id, {width: 280,@@ -311,7 +311,7 @@ describe('imported auto-layout bounds', () => {height: 14,text: 'Label',textAutoResize: 'WIDTH_AND_HEIGHT',- figmaDerivedLayout: { x: 0, y: 0, width: 37, height: 14 }+ derivedLayout: { x: 0, y: 0, width: 37, height: 14 }})computeAllLayouts(graph)@@ -341,7 +341,7 @@ describe('imported auto-layout bounds', () => {text: 'Models',textAutoResize: 'HEIGHT',layoutGrow: 1,- figmaDerivedLayout: { width: 160, height: 20 }+ derivedLayout: { width: 160, height: 20 }})const chevron = graph.createNode('INSTANCE', row.id, { width: 16, height: 16 })@@ -367,7 +367,7 @@ describe('imported auto-layout bounds', () => {width: 424,height: 40,layoutAlignSelf: 'STRETCH',- figmaDerivedLayout: { width: 424, height: 40 }+ derivedLayout: { width: 424, height: 40 }})graph.updateNode(text.id, {source: { ...text.source, format: 'fig', id: '1:3' }@@ -399,7 +399,7 @@ describe('imported auto-layout bounds', () => {text: 'Bar Chart',textAutoResize: 'HEIGHT',layoutAlignSelf: 'STRETCH',- figmaDerivedLayout: { width: 333, height: 30 }+ derivedLayout: { width: 333, height: 30 }})computeAllLayouts(graph)@@ -489,7 +489,7 @@ describe('imported auto-layout bounds', () => {y: 0,width: 40,height: 20,- figmaDerivedLayout: { x: 0, y: 0, width: 40, height: 20 }+ derivedLayout: { x: 0, y: 0, width: 40, height: 20 }})computeAllLayouts(graph)diff --git a/tests/engine/layout/auto-layout/imported-derived-layout/effective-generated-text.test.ts b/tests/engine/layout/auto-layout/imported-derived-layout/effective-generated-text.test.tsindex 873c03705..576f904c0 100644--- a/tests/engine/layout/auto-layout/imported-derived-layout/effective-generated-text.test.ts+++ b/tests/engine/layout/auto-layout/imported-derived-layout/effective-generated-text.test.ts@@ -41,7 +41,7 @@ describe('effective generated FIG text layout', () => {counterAxisSizing: 'HUG',paddingLeft: 8,componentId: 'text-wrapper',- figmaDerivedLayout: { width: 350, height: 40 }+ derivedLayout: { width: 350, height: 40 }})const generatedText = graph.createNode('TEXT', textWrapper.id, {width: 342,@@ -49,7 +49,7 @@ describe('effective generated FIG text layout', () => {text: source.text,textAutoResize: 'WIDTH_AND_HEIGHT',componentId: source.id,- figmaDerivedLayout: { width: 342, height: 20 }+ derivedLayout: { width: 342, height: 20 }})setTextMeasurer(() => ({ width: 336, height: 20 }))@@ -58,11 +58,11 @@ describe('effective generated FIG text layout', () => {expect(graph.getNode(generatedText.id)).toMatchObject({width: 336,height: 20,- figmaDerivedLayout: { width: 336, height: 20 }+ derivedLayout: { width: 336, height: 20 }})expect(graph.getNode(textWrapper.id)).toMatchObject({width: 344,- figmaDerivedLayout: { width: 344, height: 40 }+ derivedLayout: { width: 344, height: 40 }})expect(graph.getNode(checkbox.id)).toMatchObject({ width: 360, height: 40 })expect(graph.getNode(source.id)).toMatchObject({ width: 342, height: 20 })@@ -86,7 +86,7 @@ describe('effective generated FIG text layout', () => {text: source.text,textAutoResize: 'WIDTH_AND_HEIGHT',componentId: source.id,- figmaDerivedLayout: { width: 100, height: 20 }+ derivedLayout: { width: 100, height: 20 }})setTextMeasurer(() => ({ width: 80, height: 20 }))@@ -109,7 +109,7 @@ describe('effective generated FIG text layout', () => {paddingRight: 10,counterAxisAlign: 'STRETCH',componentId: 'parent',- figmaDerivedLayout: { width: 120, height: 80 }+ derivedLayout: { width: 120, height: 80 }})graph.createNode('TEXT', parent.id, {width: 100,@@ -117,27 +117,27 @@ describe('effective generated FIG text layout', () => {text: source.text,textAutoResize: 'WIDTH_AND_HEIGHT',componentId: source.id,- figmaDerivedLayout: { width: 100, height: 20 }+ derivedLayout: { width: 100, height: 20 }})const inheritedStretch = graph.createNode('RECTANGLE', parent.id, {width: 100,height: 10,layoutAlignSelf: 'AUTO',- figmaDerivedLayout: { width: 100, height: 10 }+ derivedLayout: { width: 100, height: 10 }})const hiddenStretch = graph.createNode('RECTANGLE', parent.id, {width: 100,height: 10,visible: false,layoutAlignSelf: 'AUTO',- figmaDerivedLayout: { width: 100, height: 10 }+ derivedLayout: { width: 100, height: 10 }})const absoluteStretch = graph.createNode('RECTANGLE', parent.id, {width: 100,height: 10,layoutPositioning: 'ABSOLUTE',layoutAlignSelf: 'AUTO',- figmaDerivedLayout: { width: 100, height: 10 }+ derivedLayout: { width: 100, height: 10 }})setTextMeasurer(() => ({ width: 80, height: 20 }))@@ -162,7 +162,7 @@ describe('effective generated FIG text layout', () => {paddingLeft: 16,paddingRight: 16,componentId: 'input',- figmaDerivedLayout: { width: 108, height: 40 }+ derivedLayout: { width: 108, height: 40 }})const generatedText = graph.createNode('TEXT', input.id, {width: 76,@@ -170,7 +170,7 @@ describe('effective generated FIG text layout', () => {text: source.text,textAutoResize: 'WIDTH_AND_HEIGHT',componentId: source.id,- figmaDerivedLayout: { width: 76, height: 20 }+ derivedLayout: { width: 76, height: 20 }})setTextMeasurer(() => ({ width: 74, height: 20 }))@@ -180,7 +180,7 @@ describe('effective generated FIG text layout', () => {expect(graph.getNode(input.id)).toMatchObject({width: 108,height: 40,- figmaDerivedLayout: { width: 108, height: 40 }+ derivedLayout: { width: 108, height: 40 }})})@@ -198,7 +198,7 @@ describe('effective generated FIG text layout', () => {paddingLeft: 24,paddingRight: 24,componentId: 'card-header',- figmaDerivedLayout: { width: 381, height: 102 }+ derivedLayout: { width: 381, height: 102 }})const generatedText = graph.createNode('TEXT', cardHeader.id, {width: 333,@@ -207,7 +207,7 @@ describe('effective generated FIG text layout', () => {textAutoResize: 'HEIGHT',layoutAlignSelf: 'STRETCH',componentId: source.id,- figmaDerivedLayout: { width: 333, height: 30 }+ derivedLayout: { width: 333, height: 30 }})setTextMeasurer(() => ({ width: 329, height: 37 }))@@ -217,7 +217,7 @@ describe('effective generated FIG text layout', () => {expect(graph.getNode(cardHeader.id)).toMatchObject({width: 377,height: 102,- figmaDerivedLayout: { width: 377, height: 102 }+ derivedLayout: { width: 377, height: 102 }})})@@ -232,7 +232,7 @@ describe('effective generated FIG text layout', () => {text: 'Email',textAutoResize: 'HEIGHT',componentId: source.id,- figmaDerivedLayout: { width: 280, height: 14 }+ derivedLayout: { width: 280, height: 14 }})const generatedText = graph.createNode('TEXT', page.id, {width: 302,@@ -240,7 +240,7 @@ describe('effective generated FIG text layout', () => {text: 'Name',textAutoResize: 'WIDTH_AND_HEIGHT',componentId: fixedIntermediate.id,- figmaDerivedLayout: { width: 302, height: 14 }+ derivedLayout: { width: 302, height: 14 }})setTextMeasurer(() => ({ width: 36, height: 17 }))@@ -263,7 +263,7 @@ describe('effective generated FIG text layout', () => {paddingLeft: 24,paddingRight: 24,componentId: 'parent',- figmaDerivedLayout: { width: 381, height: 68 }+ derivedLayout: { width: 381, height: 68 }})const overrideText = graph.createNode('TEXT', parent.id, {width: 333,@@ -272,7 +272,7 @@ describe('effective generated FIG text layout', () => {textAutoResize: 'HEIGHT',layoutAlignSelf: 'STRETCH',componentId: source.id,- figmaDerivedLayout: { width: 333, height: 20 }+ derivedLayout: { width: 333, height: 20 }})setTextMeasurer(() => ({ width: 329, height: 20 }))diff --git a/tests/engine/layout/auto-layout/text/measurement.test.ts b/tests/engine/layout/auto-layout/text/measurement.test.tsindex d4f48be42..3307b0d47 100644--- a/tests/engine/layout/auto-layout/text/measurement.test.ts+++ b/tests/engine/layout/auto-layout/text/measurement.test.ts@@ -37,7 +37,7 @@ describe('text measurement', () => {width: 56,height: 20,textAutoResize: 'WIDTH_AND_HEIGHT',- figmaDerivedLayout: { width: 56, height: 20 }+ derivedLayout: { width: 56, height: 20 }})setTextMeasurer(() => ({ width: 56, height: 40 }))@@ -62,7 +62,7 @@ describe('text measurement', () => {width: 424,height: 40,textAutoResize: 'HEIGHT',- figmaDerivedLayout: { width: 424, height: 120 },+ derivedLayout: { width: 424, height: 120 },source: {format: 'fig',id: '1:2',diff --git a/tests/engine/render/canvas/derived-text.test.ts b/tests/engine/render/canvas/derived-text.test.tsindex f463a0439..193ed902d 100644--- a/tests/engine/render/canvas/derived-text.test.ts+++ b/tests/engine/render/canvas/derived-text.test.ts@@ -1,13 +1,16 @@import { beforeAll, describe, expect, test } from 'bun:test'-import { renderNodesToImage, SceneGraph, SkiaRenderer } from '@open-pencil/core'+import { SceneGraph } from '@open-pencil/scene-graph'import { initCanvasKit } from '#cli/headless'+import { SkiaRenderer } from '#core/canvas/renderer'import {derivedUnderlineRect,- shouldUseHardFigmaDerivedGlyphCoverage,- snapFigmaDerivedGlyphBaseline+ hasRotatedDerivedGlyphs,+ shouldUseHardDerivedGlyphCoverage,+ snapDerivedGlyphBaseline} from '#core/canvas/text/derived'+import { renderNodesToImage } from '#core/io/formats/raster/render'import { expectDefined } from '#tests/helpers/assert'@@ -43,15 +46,15 @@ function squareCommandsBlob(): Uint8Array {describe('derived text rendering', () => {test('snaps Figma glyph baselines to device pixels', () => {- expect(snapFigmaDerivedGlyphBaseline(47.45454406738281)).toBe(47)- expect(snapFigmaDerivedGlyphBaseline(15.090909004211426)).toBe(15)- expect(snapFigmaDerivedGlyphBaseline(17.81818199157715)).toBe(18)+ expect(snapDerivedGlyphBaseline(47.45454406738281)).toBe(47)+ expect(snapDerivedGlyphBaseline(15.090909004211426)).toBe(15)+ expect(snapDerivedGlyphBaseline(17.81818199157715)).toBe(18)})test('uses hard source coverage only for regular 20px derived glyphs', () => {- expect(shouldUseHardFigmaDerivedGlyphCoverage({ fontSize: 20, fontWeight: 400 })).toBeTrue()- expect(shouldUseHardFigmaDerivedGlyphCoverage({ fontSize: 20, fontWeight: 600 })).toBeFalse()- expect(shouldUseHardFigmaDerivedGlyphCoverage({ fontSize: 14, fontWeight: 500 })).toBeFalse()+ expect(shouldUseHardDerivedGlyphCoverage({ fontSize: 20, fontWeight: 400 })).toBeTrue()+ expect(shouldUseHardDerivedGlyphCoverage({ fontSize: 20, fontWeight: 600 })).toBeFalse()+ expect(shouldUseHardDerivedGlyphCoverage({ fontSize: 14, fontWeight: 500 })).toBeFalse()})test('places derived underlines at Figma-like subpixel coverage bounds', () => {@@ -79,7 +82,7 @@ describe('derived text rendering', () => {visible: true}],- figmaDerivedTextGlyphs: [+ derivedTextGlyphs: [{commandsBlob: squareCommandsBlob(),x: 2,@@ -137,7 +140,7 @@ describe('derived text rendering', () => {visible: true}],- figmaDerivedTextGlyphs: [+ derivedTextGlyphs: [{commandsBlob: squareCommandsBlob(),x: 2,@@ -203,7 +206,7 @@ describe('derived text rendering', () => {visible: true}],- figmaDerivedTextGlyphs: [+ derivedTextGlyphs: [{commandsBlob: squareCommandsBlob(),x: 2,@@ -298,7 +301,7 @@ describe('derived text rendering', () => {visible: true}],- figmaDerivedTextGlyphs: [+ derivedTextGlyphs: [{commandsBlob: squareCommandsBlob(),x: 2,@@ -351,3 +354,86 @@ describe('derived text rendering', () => {}})})++describe('rotated derived glyphs (text-on-path)', () => {+ test('hasRotatedDerivedGlyphs detects non-zero rotation', () => {+ expect(+ hasRotatedDerivedGlyphs({+ derivedTextGlyphs: [+ { commandsBlob: squareCommandsBlob(), x: 0, y: 0, fontSize: 12, rotation: 0 }+ ]+ })+ ).toBe(false)+ expect(+ hasRotatedDerivedGlyphs({+ derivedTextGlyphs: [+ { commandsBlob: squareCommandsBlob(), x: 0, y: 0, fontSize: 12, rotation: -1.5 }+ ]+ })+ ).toBe(true)+ })++ test('draws rotated derived glyphs without throwing', async () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const text = graph.createNode('TEXT', page.id, {+ width: 200,+ height: 200,+ text: 'x',+ fontFamily: '__MissingFont__',+ fills: [+ {+ type: 'SOLID',+ color: { r: 0, g: 0, b: 0, a: 1 },+ opacity: 1,+ visible: true+ }+ ],+ derivedTextGlyphs: [+ {+ commandsBlob: squareCommandsBlob(),+ x: 50,+ y: 50,+ fontSize: 20,+ rotation: -Math.PI / 2+ }+ ]+ })++ const surface = expectDefined(ck.MakeSurface(1, 1), 'surface')+ const renderer = new SkiaRenderer(ck, surface)+ // The font is intentionally missing; baked glyphs only paint once font+ // resolution is exhausted (see renderText's readiness gate).+ useDerivedGlyphFallback(renderer)+ try {+ const png = expectDefined(+ renderNodesToImage(ck, renderer, graph, page.id, [text.id], {+ scale: 1,+ format: 'PNG'+ }),+ 'png'+ )+ // A blank canvas also yields a non-empty PNG, so decode and require the+ // rotated glyph to actually paint pixels — not merely render without throwing.+ const image = expectDefined(ck.MakeImageFromEncoded(png), 'image')+ const pixels = expectDefined(+ image.readPixels(0, 0, {+ alphaType: ck.AlphaType.Unpremul,+ colorType: ck.ColorType.RGBA_8888,+ colorSpace: ck.ColorSpace.SRGB,+ width: image.width(),+ height: image.height()+ }),+ 'pixels'+ )+ let paintedPixels = 0+ for (let index = 3; index < pixels.length; index += 4) {+ if ((pixels[index] ?? 0) > 0) paintedPixels+++ }+ image.delete()+ expect(paintedPixels).toBeGreaterThan(0)+ } finally {+ surface.delete()+ }+ })+})diff --git a/tests/engine/render/canvas/effects/types.test.ts b/tests/engine/render/canvas/effects/types.test.tsindex ac5ac9473..ca1afcb17 100644--- a/tests/engine/render/canvas/effects/types.test.ts+++ b/tests/engine/render/canvas/effects/types.test.ts@@ -3,6 +3,7 @@ import { describe, expect, mock, test } from 'bun:test'import type { Canvas } from 'canvaskit-wasm'import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { createDefaultSourceMetadata } from '@open-pencil/scene-graph/node-defaults'import { applyClippedBlur } from '#core/canvas/effects'import { renderNode } from '#core/canvas/scene'@@ -289,7 +290,8 @@ describe('Renderer handles all effect types (Behavioral)', () => {rotation: 0,opacity: 1,effects: [{ type: 'LAYER_BLUR', visible: true, radius: 10 }],- childIds: []+ childIds: [],+ source: createDefaultSourceMetadata()}const graph: Partial<SceneGraph> = {getNode: mock(() => node as SceneNode)@@ -313,7 +315,8 @@ describe('Renderer handles all effect types (Behavioral)', () => {rotation: 0,opacity: 1,effects: [{ type: 'FOREGROUND_BLUR', visible: true, radius: 20 }],- childIds: []+ childIds: [],+ source: createDefaultSourceMetadata()}const graph: Partial<SceneGraph> = {getNode: mock(() => node as SceneNode)diff --git a/tests/engine/render/canvas/renderer-lifecycle.test.ts b/tests/engine/render/canvas/renderer-lifecycle.test.tsindex e7dbc92a5..24e003269 100644--- a/tests/engine/render/canvas/renderer-lifecycle.test.ts+++ b/tests/engine/render/canvas/renderer-lifecycle.test.ts@@ -18,6 +18,7 @@ function createRenderer() {vectorStrokeOutlineCache: new Map(),fillGeometryCache: new Map(),strokeGeometryCache: new Map(),+ glyphSilhouetteCache: new Map(),fillPaint: deletable<Paint>(),strokePaint: deletable<Paint>(),selectionPaint: deletable<Paint>(),diff --git a/tests/engine/render/canvas/silhouette-autopsy.test.ts b/tests/engine/render/canvas/silhouette-autopsy.test.tsindex f0ec4c188..e3eadae24 100644--- a/tests/engine/render/canvas/silhouette-autopsy.test.ts+++ b/tests/engine/render/canvas/silhouette-autopsy.test.ts@@ -108,7 +108,7 @@ describe('Doc 01 — The Current Engine: Static Code Claims', () => {expect(src).not.toContain("'FOREGROUND_BLUR' ? 'LAYER_BLUR'")})- test('C01-06: renderShapeUncached order = behind effects → fills → strokes → front effects (scene.ts:430-466)', () => {+ test('C01-06: renderShapeUncached order = behind effects → fills → strokes → front effects', () => {const src = readSource(scenePath)const renderShapeUncachedMatch = src.match(/export function renderShapeUncached[\s\S]*?(?=\nexport function|\n$)/@@ -119,7 +119,9 @@ describe('Doc 01 — The Current Engine: Static Code Claims', () => {// Find indices of key callsconst behindIdx = body.indexOf("'behind'")const fillIdx = body.indexOf('drawNodeFill')- const strokeIdx = body.indexOf('drawNodeStroke')+ // Strokes paint through paintNodeStrokes, which path text calls earlier+ // (stroke-first); the default order is asserted from its second call site.+ const strokeIdx = body.lastIndexOf('paintNodeStrokes')const frontIdx = body.indexOf("'front'")expect(behindIdx).toBeGreaterThan(-1)diff --git a/tests/engine/render/canvas/text.test.ts b/tests/engine/render/canvas/text.test.tsindex d4dd6d111..75862d907 100644--- a/tests/engine/render/canvas/text.test.ts+++ b/tests/engine/render/canvas/text.test.ts@@ -7,6 +7,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 { initCanvasKit } from '#cli/headless'import type { SkiaRenderer } from '#core/canvas/renderer'@@ -95,6 +96,7 @@ function textNode(overrides: Partial<SceneNode> = {}): SceneNode {textDecoration: 'NONE',textDirection: 'AUTO',styleRuns: [],+ source: createDefaultSourceMetadata(),...overrides} as SceneNode}diff --git a/tests/engine/scene-graph/basic/update-node.test.ts b/tests/engine/scene-graph/basic/update-node.test.tsindex 624088cc4..1579b3d56 100644--- a/tests/engine/scene-graph/basic/update-node.test.ts+++ b/tests/engine/scene-graph/basic/update-node.test.ts@@ -186,7 +186,7 @@ describe('updateNode', () => {expect(expectDefined(afterUpdate, 'updated node').textPicture).toBeNull()})- test('figmaDerivedTextGlyphs are nulled when text rendering properties change on TEXT node', () => {+ test('derivedTextGlyphs are nulled when text rendering properties change on TEXT node', () => {const graph = new SceneGraph()const page = pageId(graph)const textId = graph.createNode('TEXT', page, {@@ -198,14 +198,14 @@ describe('updateNode', () => {}).idconst glyphs = [{ commandsBlob: new Uint8Array([1, 2, 3]), x: 0, y: 10, fontSize: 14 }]const textNode = expectDefined(graph.getNode(textId), 'text node')- textNode.figmaDerivedTextGlyphs = glyphs+ textNode.derivedTextGlyphs = glyphsgraph.updateNode(textId, { textDirection: 'RTL' })- expect(expectDefined(graph.getNode(textId), 'updated node').figmaDerivedTextGlyphs).toBeNull()+ expect(expectDefined(graph.getNode(textId), 'updated node').derivedTextGlyphs).toBeNull()})- test('figmaDerivedTextGlyphs survive picture-only text property changes', () => {+ test('derivedTextGlyphs survive picture-only text property changes', () => {const pictureOnlyChanges = [{ width: 120 },{ height: 24 },@@ -226,17 +226,15 @@ describe('updateNode', () => {}).idconst glyphs = [{ commandsBlob: new Uint8Array([4, 5, 6]), x: 0, y: 10, fontSize: 14 }]const textNode = expectDefined(graph.getNode(textId), 'text node')- textNode.figmaDerivedTextGlyphs = glyphs+ textNode.derivedTextGlyphs = glyphsgraph.updateNode(textId, changes)- expect(expectDefined(graph.getNode(textId), 'updated node').figmaDerivedTextGlyphs).toBe(- glyphs- )+ expect(expectDefined(graph.getNode(textId), 'updated node').derivedTextGlyphs).toBe(glyphs)}})- test('figmaDerivedTextGlyphs survive non-text property change on TEXT node', () => {+ test('derivedTextGlyphs survive non-text property change on TEXT node', () => {const graph = new SceneGraph()const page = pageId(graph)const textId = graph.createNode('TEXT', page, {@@ -248,11 +246,11 @@ describe('updateNode', () => {}).idconst glyphs = [{ commandsBlob: new Uint8Array([4, 5, 6]), x: 0, y: 10, fontSize: 14 }]const textNode = expectDefined(graph.getNode(textId), 'text node')- textNode.figmaDerivedTextGlyphs = glyphs+ textNode.derivedTextGlyphs = glyphsgraph.updateNode(textId, { opacity: 0.5 })- expect(expectDefined(graph.getNode(textId), 'updated node').figmaDerivedTextGlyphs).toBe(glyphs)+ expect(expectDefined(graph.getNode(textId), 'updated node').derivedTextGlyphs).toBe(glyphs)})test('textPicture survives non-text property change on TEXT node', () => {diff --git a/tests/engine/scene-graph/clone/node-props.test.ts b/tests/engine/scene-graph/clone/node-props.test.tsindex ef190d7f2..02a120585 100644--- a/tests/engine/scene-graph/clone/node-props.test.ts+++ b/tests/engine/scene-graph/clone/node-props.test.ts@@ -55,7 +55,7 @@ describe('cloneNodeProps deep-copies vectorNetwork', () => {})})-describe('cloneNodeProps deep-copies textPicture and figmaDerivedTextGlyphs', () => {+describe('cloneNodeProps deep-copies textPicture and derivedTextGlyphs', () => {test('cloned textPicture is not the same reference as original', () => {const graph = new SceneGraph()const node = graph.createNode('TEXT', pageId(graph), {@@ -76,14 +76,14 @@ describe('cloneNodeProps deep-copies textPicture and figmaDerivedTextGlyphs', ()}})- test('cloned figmaDerivedTextGlyphs is not the same reference as original', () => {+ test('cloned derivedTextGlyphs is not the same reference as original', () => {const graph = new SceneGraph()const node = graph.createNode('TEXT', pageId(graph), {name: 'Text',text: 'Hi',fontSize: 14,fontFamily: 'Inter',- figmaDerivedTextGlyphs: [+ derivedTextGlyphs: [{ commandsBlob: new Uint8Array([10, 20]), x: 0, y: 0, fontSize: 14 },{ commandsBlob: new Uint8Array([30, 40]), x: 10, y: 0, fontSize: 14 }]@@ -92,14 +92,14 @@ describe('cloneNodeProps deep-copies textPicture and figmaDerivedTextGlyphs', ()const clone = graph.cloneTree(node.id, pageId(graph))const clonedNode = graph.getNode(clone.id)- expect(clonedNode.figmaDerivedTextGlyphs).not.toBe(original.figmaDerivedTextGlyphs)- if (original.figmaDerivedTextGlyphs && clonedNode.figmaDerivedTextGlyphs) {- expect(clonedNode.figmaDerivedTextGlyphs[0]).not.toBe(original.figmaDerivedTextGlyphs[0])- expect(clonedNode.figmaDerivedTextGlyphs[0].commandsBlob).not.toBe(- original.figmaDerivedTextGlyphs[0].commandsBlob+ expect(clonedNode.derivedTextGlyphs).not.toBe(original.derivedTextGlyphs)+ if (original.derivedTextGlyphs && clonedNode.derivedTextGlyphs) {+ expect(clonedNode.derivedTextGlyphs[0]).not.toBe(original.derivedTextGlyphs[0])+ expect(clonedNode.derivedTextGlyphs[0].commandsBlob).not.toBe(+ original.derivedTextGlyphs[0].commandsBlob)- clonedNode.figmaDerivedTextGlyphs[0].commandsBlob[0] = 99- expect(original.figmaDerivedTextGlyphs[0].commandsBlob[0]).toBe(10)+ clonedNode.derivedTextGlyphs[0].commandsBlob[0] = 99+ expect(original.derivedTextGlyphs[0].commandsBlob[0]).toBe(10)}})})@@ -226,7 +226,7 @@ describe('cloneNodeProps coverage guard', () => {}},textPicture: new Uint8Array([1, 2, 3]),- figmaDerivedTextGlyphs: [{ commandsBlob: new Uint8Array([4, 5]), x: 0, y: 0, fontSize: 12 }],+ derivedTextGlyphs: [{ commandsBlob: new Uint8Array([4, 5]), x: 0, y: 0, fontSize: 12 }],gridPosition: { column: 1, row: 1, columnSpan: 1, rowSpan: 1 }})diff --git a/tests/engine/scene-graph/copy.test.ts b/tests/engine/scene-graph/copy.test.tsindex 2078026de..3d3a018ed 100644--- a/tests/engine/scene-graph/copy.test.ts+++ b/tests/engine/scene-graph/copy.test.ts@@ -7,7 +7,8 @@ import {copyStroke,copyEffect,copyStyleRun,- copyGeometryPaths+ copyGeometryPaths,+ scaleGeometryPaths} from '@open-pencil/scene-graph/copy'import { expectDefined } from '#tests/helpers/assert'@@ -104,6 +105,35 @@ describe('copy helpers — mutation isolation', () => {expect(original[0].fills?.[0]?.color.r).toBe(1)})+ test('copyGeometryPaths and scaleGeometryPaths keep path-level fills', () => {+ // Resize snapshots use these helpers; dropping fills collapses multi-color+ // vectors to a single node fill (gray blob).+ const orange: Fill = {+ type: 'SOLID',+ color: { r: 1, g: 0.32, b: 0, a: 1 },+ opacity: 1,+ visible: true+ }+ const original: GeometryPath[] = [+ {+ windingRule: 'NONZERO',+ commandsBlob: new Uint8Array([1, 0, 0, 0, 0, 0, 0, 0, 0]),+ fills: [orange]+ },+ { windingRule: 'EVENODD', commandsBlob: new Uint8Array([2, 3, 4]) }+ ]++ const copied = copyGeometryPaths(original)+ expect(copied[0]?.fills?.[0]?.color.r).toBeCloseTo(1, 2)+ expect(copied[1]?.fills).toBeUndefined()+ expectDefined(copied[0]?.fills?.[0], 'copied path fill').color.r = 0+ expect(original[0]?.fills?.[0]?.color.r).toBe(1)++ const scaled = scaleGeometryPaths(original, 0.5, 0.5)+ expect(scaled[0]?.fills?.[0]?.color.g).toBeCloseTo(0.32, 2)+ expect(scaled[0]?.commandsBlob).not.toBe(original[0]?.commandsBlob)+ })+test('copyFills: array independence', () => {const originals: Fill[] = [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, opacity: 1, visible: true },diff --git a/tests/engine/scene-graph/world-transform.test.ts b/tests/engine/scene-graph/world-transform.test.tsindex 5e21368ef..b95dbee69 100644--- a/tests/engine/scene-graph/world-transform.test.ts+++ b/tests/engine/scene-graph/world-transform.test.ts@@ -7,7 +7,12 @@*/import { describe, expect, test } from 'bun:test'-import { getWorldMatrix, SceneGraph, TransformMatrix } from '@open-pencil/scene-graph'+import {+ getWorldHandles,+ getWorldMatrix,+ SceneGraph,+ TransformMatrix+} from '@open-pencil/scene-graph'function pageId(graph: SceneGraph) {return graph.getPages()[0].id@@ -307,3 +312,44 @@ describe('world transform — corner mapping', () => {expect(opposite[1]).toBeCloseTo(170, 8)})})++describe('getWorldHandles — localRect override', () => {+ test('defaults to full node bounds', () => {+ const graph = new SceneGraph()+ const node = graph.createNode('RECTANGLE', pageId(graph), {+ name: 'R',+ x: 100,+ y: 200,+ width: 500,+ height: 400+ })+ const h = getWorldHandles(node, graph)+ expect(h.nw).toEqual({ x: 100, y: 200 })+ expect(h.se).toEqual({ x: 600, y: 600 })+ expect(h.n).toEqual({ x: 350, y: 200 })+ })++ // Text-on-path handles sit on the glyph-fitted path box (inset from node+ // bounds), not the node rectangle — passing that box must move every handle+ // to the box corners or the visible handles are unclickable.+ test('localRect insets handles to the given box', () => {+ const graph = new SceneGraph()+ const node = graph.createNode('TEXT', pageId(graph), {+ name: 'T',+ x: 100,+ y: 200,+ width: 500,+ height: 400+ })+ const box = { x: 20, y: 30, width: 400, height: 300 }+ const h = getWorldHandles(node, graph, box)+ // nw = node origin + box origin+ expect(h.nw).toEqual({ x: 120, y: 230 })+ // se = node origin + box far corner+ expect(h.se).toEqual({ x: 520, y: 530 })+ // e = right edge, vertical midpoint of the box+ expect(h.e).toEqual({ x: 520, y: 380 })+ // n = horizontal midpoint of the box, top edge+ expect(h.n).toEqual({ x: 320, y: 230 })+ })+})diff --git a/tests/engine/text/edit-undo.test.ts b/tests/engine/text/edit-undo.test.tsindex 417e260bb..66b25e77b 100644--- a/tests/engine/text/edit-undo.test.ts+++ b/tests/engine/text/edit-undo.test.ts@@ -3,10 +3,12 @@ import { describe, test, expect } from 'bun:test'import type { CanvasKit } from 'canvaskit-wasm'import { SceneGraph, TextEditor, UndoManager } from '@open-pencil/core'-import type { StyleRun } from '@open-pencil/core'+import type { DerivedTextGlyph, StyleRun } from '@open-pencil/core'import { createTextActions } from '@open-pencil/core/editor'import type { EditorContext, EditorState } from '@open-pencil/core/editor'+import { fontManager } from '#core/text/fonts'+import { expectDefined, getNodeOrThrow } from '#tests/helpers/assert'function setup() {@@ -53,6 +55,46 @@ function setup() {return { graph, undo, textEditor, state, textNode, actions }}+function straightTextPathNetwork() {+ return {+ vertices: [+ { x: 0, y: 20 },+ { x: 200, y: 20 }+ ],+ segments: [{ start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }],+ regions: []+ }+}++async function setupPathText() {+ const font = await fontManager.fetchBundledFont('/Inter-Regular.ttf')+ expect(font).toBeTruthy()+ if (!font) return null+ fontManager.markLoaded('Inter', 'Regular', font)++ const setupResult = setup()+ const glyphs: DerivedTextGlyph[] = [+ { commandsBlob: new Uint8Array([0]), x: 20, y: 20, fontSize: 20, rotation: 0 },+ { commandsBlob: new Uint8Array([0]), x: 40, y: 20, fontSize: 20, rotation: 0 }+ ]+ setupResult.graph.updateNode(setupResult.textNode.id, {+ text: 'AB',+ fontFamily: 'Inter',+ fontSize: 20,+ width: 200,+ height: 40,+ textPathData: {+ network: straightTextPathNetwork(),+ normalizedSize: { x: 200, y: 40 },+ tValue: 0,+ forward: true+ },+ textPathBox: { x: 0, y: 0, width: 200, height: 40 },+ derivedTextGlyphs: glyphs+ })+ return setupResult+}+function paragraphWithHeight(height: number) {return {getHeight: () => height,@@ -103,6 +145,60 @@ describe('text edit undo', () => {expect(getNodeOrThrow(graph, textNode.id).text).toBe('Hello World')})+ test('reflows live path-text edits and restores glyphs through undo and redo', async () => {+ const setupResult = await setupPathText()+ if (!setupResult) return+ const { graph, undo, textEditor, textNode, actions } = setupResult+ const originalGlyphs = structuredClone(+ expectDefined(getNodeOrThrow(graph, textNode.id).derivedTextGlyphs)+ )++ actions.startTextEditing(textNode.id)+ textEditor.insert('C', getNodeOrThrow(graph, textNode.id))+ actions.updateTextEditNode(textNode.id, {+ text: expectDefined(textEditor.state, 'text editor state').text+ })++ const liveGlyphs = expectDefined(getNodeOrThrow(graph, textNode.id).derivedTextGlyphs)+ expect(liveGlyphs).toHaveLength(3)+ expect(liveGlyphs).not.toEqual(originalGlyphs)++ actions.commitTextEdit()+ const committedGlyphs = structuredClone(+ expectDefined(getNodeOrThrow(graph, textNode.id).derivedTextGlyphs)+ )+ undo.undo()+ expect(getNodeOrThrow(graph, textNode.id).text).toBe('AB')+ expect(getNodeOrThrow(graph, textNode.id).derivedTextGlyphs).toEqual(originalGlyphs)++ undo.redo()+ expect(getNodeOrThrow(graph, textNode.id).text).toBe('ABC')+ expect(getNodeOrThrow(graph, textNode.id).derivedTextGlyphs).toEqual(committedGlyphs)+ })++ test('restores path identity when undoing an edit to empty text', async () => {+ const setupResult = await setupPathText()+ if (!setupResult) return+ const { graph, undo, textEditor, textNode, actions } = setupResult+ const originalPathData = structuredClone(+ expectDefined(getNodeOrThrow(graph, textNode.id).textPathData)+ )++ actions.startTextEditing(textNode.id)+ textEditor.selectAll()+ textEditor.backspace(getNodeOrThrow(graph, textNode.id))+ actions.updateTextEditNode(textNode.id, { text: '' })+ actions.commitTextEdit()++ expect(getNodeOrThrow(graph, textNode.id).textPathData).toBeNull()+ undo.undo()+ expect(getNodeOrThrow(graph, textNode.id).text).toBe('AB')+ expect(getNodeOrThrow(graph, textNode.id).textPathData).toEqual(originalPathData)+ undo.redo()+ expect(getNodeOrThrow(graph, textNode.id).text).toBe('')+ expect(getNodeOrThrow(graph, textNode.id).textPathData).toBeNull()+ })+test('keeps an empty text override inside an instance through sync and undo', () => {const { graph, undo, textEditor, actions } = setup()const page = graph.getPages()[0]@@ -195,15 +291,15 @@ describe('text edit undo', () => {expect(undo.canUndo).toBe(false)})- test('commitTextEdit preserves Figma derived glyphs when text unchanged', () => {+ test('commitTextEdit preserves derived glyphs when text unchanged', () => {const { graph, actions, textNode } = setup()const glyphs = [{ commandsBlob: new Uint8Array([0]), x: 0, y: 10, fontSize: 14 }]- graph.updateNode(textNode.id, { figmaDerivedTextGlyphs: glyphs })+ graph.updateNode(textNode.id, { derivedTextGlyphs: glyphs })actions.startTextEditing(textNode.id)actions.commitTextEdit()- expect(getNodeOrThrow(graph, textNode.id).figmaDerivedTextGlyphs).toBe(glyphs)+ expect(getNodeOrThrow(graph, textNode.id).derivedTextGlyphs).toBe(glyphs)})test('undo restores original text even when graph was synced mid-edit', () => {diff --git a/tests/engine/vue/controls/constraints.test.ts b/tests/engine/vue/controls/constraints.test.tsindex 31f504a42..4d9e27f2d 100644--- a/tests/engine/vue/controls/constraints.test.ts+++ b/tests/engine/vue/controls/constraints.test.ts@@ -28,7 +28,10 @@ function original(node: {height: node.height,vectorNetwork: node.vectorNetwork,fillGeometry: [],- strokeGeometry: []+ strokeGeometry: [],+ derivedTextGlyphs: null,+ strokes: [],+ textPathBox: null}}@@ -67,7 +70,10 @@ describe('constraint resize geometry', () => {height: 20,vectorNetwork: null,fillGeometry: [],- strokeGeometry: []+ strokeGeometry: [],+ derivedTextGlyphs: null,+ strokes: [],+ textPathBox: null}const expectedX: Record<ConstraintType, [number, number]> = {MIN: [20, 40],@@ -120,6 +126,9 @@ describe('constraint resize geometry', () => {origVectorNetwork: null,origFillGeometry: [],origStrokeGeometry: [],+ origDerivedTextGlyphs: null,+ origStrokes: [],+ origTextPathBox: null,origChildren: new Map([[nested.id, original(nested)],[grandchild.id, original(grandchild)]@@ -165,6 +174,9 @@ describe('constraint resize geometry', () => {origVectorNetwork: null,origFillGeometry: [],origStrokeGeometry: [],+ origDerivedTextGlyphs: null,+ origStrokes: [],+ origTextPathBox: null,origChildren: collectResizeDescendants(graph, root.id)}diff --git a/tests/engine/vue/input/resize-geometry.test.ts b/tests/engine/vue/input/resize/geometry.test.tssimilarity index 98%rename from tests/engine/vue/input/resize-geometry.test.tsrename to tests/engine/vue/input/resize/geometry.test.tsindex e5ee7954b..5aabefc79 100644--- a/tests/engine/vue/input/resize-geometry.test.ts+++ b/tests/engine/vue/input/resize/geometry.test.ts@@ -74,6 +74,9 @@ function dragFor(node: SceneNode, origChildren: DragResize['origChildren'] = nulorigVectorNetwork: geometry.network,origFillGeometry: geometry.fills,origStrokeGeometry: geometry.strokes,+ origDerivedTextGlyphs: null,+ origStrokes: [],+ origTextPathBox: null,origChildren}}diff --git a/tests/engine/vue/input/resize/path-text/basic.test.ts b/tests/engine/vue/input/resize/path-text/basic.test.tsnew file mode 100644index 000000000..666281392--- /dev/null+++ b/tests/engine/vue/input/resize/path-text/basic.test.ts@@ -0,0 +1,254 @@+import { describe, expect, test } from 'bun:test'++import { reactive } from 'vue'++import type { Editor } from '@open-pencil/core/editor'+import { SceneGraph } from '@open-pencil/scene-graph'+import type { DerivedTextGlyph, Fill, SceneNode, Stroke } from '@open-pencil/scene-graph'+import { copyGeometryPaths, copyStrokes } from '@open-pencil/scene-graph/copy'++import { applyResize, commitResizePreview } from '#vue/shared/input/resize'+import type { DragResize, OrigChildState } from '#vue/shared/input/types'++import { expectDefined } from '#tests/helpers/assert'++const BLACK: Fill = {+ type: 'SOLID',+ color: { r: 0, g: 0, b: 0, a: 1 },+ opacity: 1,+ visible: true,+ blendMode: 'NORMAL'+}++const WHITE_STROKE: Stroke = {+ color: { r: 1, g: 1, b: 1, a: 1 },+ weight: 4,+ opacity: 1,+ visible: true,+ align: 'OUTSIDE',+ cap: 'NONE',+ join: 'MITER',+ dashPattern: []+}++function squareBlob(size: number): Uint8Array {+ const blob = new Uint8Array(1 + 4 * 9 + 1)+ const view = new DataView(blob.buffer)+ const pts = [+ [1, 0, 0],+ [2, size, 0],+ [2, size, size],+ [2, 0, size]+ ] as const+ let o = 0+ for (const [cmd, x, y] of pts) {+ blob[o] = cmd+ view.setFloat32(o + 1, x, true)+ view.setFloat32(o + 5, y, true)+ o += 9+ }+ blob[o] = 0+ return blob+}++function readBlobX(blob: Uint8Array, cmdIndex: number): number {+ // Each move/line is 9 bytes; second command starts at offset 9, x at +1+ return new DataView(blob.buffer, blob.byteOffset).getFloat32(cmdIndex * 9 + 1, true)+}++describe('resize scales path-text stroke geometry and glyphs', () => {+ test('group resize scales TEXT strokeGeometry + derived glyphs', () => {+ const graph = new SceneGraph()+ const page = expectDefined(graph.getPages()[0])+ const group = graph.createNode('GROUP', page.id, {+ x: 0,+ y: 0,+ width: 200,+ height: 200+ })+ const glyphs: DerivedTextGlyph[] = [+ {+ commandsBlob: squareBlob(1),+ x: 100,+ y: 50,+ fontSize: 80,+ rotation: -1.5+ }+ ]+ const text = graph.createNode('TEXT', group.id, {+ x: 0,+ y: 0,+ width: 200,+ height: 200,+ text: 'A',+ fills: [BLACK],+ strokes: [WHITE_STROKE],+ strokeGeometry: [{ windingRule: 'NONZERO', commandsBlob: squareBlob(200) }],+ derivedTextGlyphs: glyphs+ })++ const editor = {+ graph,+ renderer: undefined,+ requestRepaint: () => undefined+ } as Editor++ const origChild: OrigChildState = {+ x: text.x,+ y: text.y,+ width: text.width,+ height: text.height,+ vectorNetwork: null,+ fillGeometry: [],+ strokeGeometry: copyGeometryPaths(text.strokeGeometry),+ derivedTextGlyphs: glyphs.map((g) => ({+ ...g,+ commandsBlob: new Uint8Array(g.commandsBlob)+ })),+ strokes: copyStrokes(text.strokes),+ textPathData: null,+ textPathBox: null+ }++ const drag: DragResize = {+ type: 'resize',+ handle: 'se',+ startX: 200,+ startY: 200,+ origRect: { x: 0, y: 0, width: 200, height: 200 },+ nodeId: group.id,+ origVectorNetwork: null,+ origFillGeometry: [],+ origStrokeGeometry: [],+ origDerivedTextGlyphs: null,+ origStrokes: [],+ origTextPathData: null,+ origTextPathBox: null,+ origChildren: new Map([[text.id, origChild]])+ }++ // Scale group to half size+ applyResize(drag, 100, 100, false, editor)++ const resized = expectDefined(graph.getNode(text.id))+ expect(resized.width).toBe(100)+ expect(resized.height).toBe(100)++ // strokeGeometry must scale with the node — otherwise OUTSIDE outlines+ // stay full-size and look massively thick after a shrink.+ const sg = expectDefined(resized.strokeGeometry[0])+ expect(readBlobX(sg.commandsBlob, 1)).toBeCloseTo(100, 3)++ const g0 = expectDefined(resized.derivedTextGlyphs?.[0])+ expect(g0.x).toBeCloseTo(50, 3)+ expect(g0.y).toBeCloseTo(25, 3)+ // fontSize stays; non-uniform/uniform scale is carried on scaleX/Y+ expect(g0.fontSize).toBeCloseTo(80, 3)+ expect(g0.scaleX).toBeCloseTo(0.5, 3)+ expect(g0.scaleY).toBeCloseTo(0.5, 3)+ expect(g0.rotation).toBeCloseTo(-1.5, 4)++ expect(resized.strokes[0]?.weight).toBeCloseTo(2, 3)+ })++ test('reactive drag state does not leak proxies into the graph', () => {+ // The app stores DragResize in a Vue ref, so commit-time reads through it+ // yield reactive proxies. Writing those into the graph made every+ // structuredClone consumer throw DataCloneError (export subgraph clone).+ const graph = new SceneGraph()+ const page = expectDefined(graph.getPages()[0])+ const group = graph.createNode('GROUP', page.id, { x: 0, y: 0, width: 200, height: 200 })+ const text = graph.createNode('TEXT', group.id, {+ x: 0,+ y: 0,+ width: 200,+ height: 200,+ text: 'A',+ fills: [BLACK],+ strokes: [WHITE_STROKE],+ strokeGeometry: [{ windingRule: 'NONZERO', commandsBlob: squareBlob(200) }],+ derivedTextGlyphs: [+ { commandsBlob: squareBlob(1), x: 100, y: 50, fontSize: 80, rotation: -1.5 }+ ]+ })++ const editor = {+ graph,+ renderer: undefined,+ requestRepaint: () => undefined,+ updateNode: (id: string, changes: Partial<SceneNode>) => graph.updateNode(id, changes),+ commitGroupResize: () => undefined,+ commitResize: () => undefined+ } as Editor++ const origChild: OrigChildState = {+ x: text.x,+ y: text.y,+ width: text.width,+ height: text.height,+ vectorNetwork: null,+ fillGeometry: [],+ strokeGeometry: copyGeometryPaths(text.strokeGeometry),+ derivedTextGlyphs: expectDefined(text.derivedTextGlyphs).map((g) => ({+ ...g,+ commandsBlob: new Uint8Array(g.commandsBlob)+ })),+ strokes: copyStrokes(text.strokes),+ textPathData: null,+ textPathBox: null+ }+ const drag: DragResize = reactive({+ type: 'resize',+ handle: 'se',+ startX: 200,+ startY: 200,+ origRect: { x: 0, y: 0, width: 200, height: 200 },+ nodeId: group.id,+ origVectorNetwork: null,+ origFillGeometry: [],+ origStrokeGeometry: [],+ origDerivedTextGlyphs: null,+ origStrokes: [],+ origTextPathData: null,+ origTextPathBox: null,+ origChildren: new Map([[text.id, origChild]])+ }) as DragResize++ applyResize(drag, 100, 100, false, editor)+ commitResizePreview(drag, editor)++ for (const id of [group.id, text.id]) {+ const node = expectDefined(graph.getNode(id))+ for (const key of Object.keys(node) as (keyof SceneNode)[]) {+ expect(() => structuredClone(node[key])).not.toThrow()+ }+ }+ })++ test('width/height resize does not drop derived glyphs', () => {+ const graph = new SceneGraph()+ const page = expectDefined(graph.getPages()[0])+ const glyphs: DerivedTextGlyph[] = [+ { commandsBlob: squareBlob(1), x: 10, y: 20, fontSize: 40, rotation: -1 }+ ]+ const text = graph.createNode('TEXT', page.id, {+ width: 100,+ height: 100,+ text: 'A',+ textPathData: {+ network: { vertices: [], segments: [], regions: [] },+ normalizedSize: { x: 100, y: 100 },+ tValue: 0,+ forward: true+ },+ derivedTextGlyphs: glyphs+ })++ graph.updateNodePreview(text.id, { width: 50, height: 80 })++ const updated = expectDefined(graph.getNode(text.id))+ expect(updated.derivedTextGlyphs).not.toBeNull()+ expect(updated.derivedTextGlyphs).toHaveLength(1)+ expect(updated.textPathData).not.toBeNull()+ })+})diff --git a/tests/engine/vue/input/resize/path-text/reflow.test.ts b/tests/engine/vue/input/resize/path-text/reflow.test.tsnew file mode 100644index 000000000..871bf893d--- /dev/null+++ b/tests/engine/vue/input/resize/path-text/reflow.test.ts@@ -0,0 +1,435 @@+import { describe, expect, test } from 'bun:test'++import type { Editor } from '@open-pencil/core/editor'+import { parseFigBuffer } from '@open-pencil/fig'+import { SceneGraph } from '@open-pencil/scene-graph'+import type { Fill, SceneNode, Stroke, VectorNetwork } from '@open-pencil/scene-graph'+import { copyGeometryPaths, copyStrokes } from '@open-pencil/scene-graph/copy'++import { exportFigFile } from '#core/io/formats/fig/export'+import { getTextPathData, layoutPathTextFromAdvances } from '#core/text/path'+import { applyResize, commitResizePreview } from '#vue/shared/input/resize'+import type { DragResize, OrigChildState } from '#vue/shared/input/types'++import { expectDefined } from '#tests/helpers/assert'++const BLACK: Fill = {+ type: 'SOLID',+ color: { r: 0, g: 0, b: 0, a: 1 },+ opacity: 1,+ visible: true,+ blendMode: 'NORMAL'+}++const WHITE_STROKE: Stroke = {+ color: { r: 1, g: 1, b: 1, a: 1 },+ weight: 4,+ opacity: 1,+ visible: true,+ align: 'OUTSIDE',+ cap: 'NONE',+ join: 'MITER',+ dashPattern: []+}++const KAPPA = 0.5523++/** 4-cubic circle, radius 100 centered (128,128), in 256x256 normalized space. */+function circleNetwork(): VectorNetwork {+ const c = 128+ const r = 100+ const k = r * KAPPA+ return {+ vertices: [+ { x: c + r, y: c },+ { x: c, y: c + r },+ { x: c - r, y: c },+ { x: c, y: c - r }+ ],+ segments: [+ { start: 0, end: 1, tangentStart: { x: 0, y: k }, tangentEnd: { x: k, y: 0 } },+ { start: 1, end: 2, tangentStart: { x: -k, y: 0 }, tangentEnd: { x: 0, y: k } },+ { start: 2, end: 3, tangentStart: { x: 0, y: -k }, tangentEnd: { x: -k, y: 0 } },+ { start: 3, end: 0, tangentStart: { x: k, y: 0 }, tangentEnd: { x: 0, y: -k } }+ ],+ regions: []+ }+}++/** Minimal move+line outline blob — layout never reads its contents. */+function glyphBlob(): Uint8Array {+ const blob = new Uint8Array(2 * 9)+ const view = new DataView(blob.buffer)+ blob[0] = 1+ view.setFloat32(1, 0, true)+ view.setFloat32(5, 0, true)+ blob[9] = 2+ view.setFloat32(10, 1, true)+ view.setFloat32(14, 0, true)+ return blob+}++function squareGeometryBlob(size: number): Uint8Array {+ const blob = new Uint8Array(1 + 4 * 9 + 1)+ const view = new DataView(blob.buffer)+ const pts = [+ [1, 0, 0],+ [2, size, 0],+ [2, size, size],+ [2, 0, size]+ ] as const+ let o = 0+ for (const [cmd, x, y] of pts) {+ blob[o] = cmd+ view.setFloat32(o + 1, x, true)+ view.setFloat32(o + 5, y, true)+ o += 9+ }+ blob[o] = 0+ return blob+}++describe('group resize reflows path text instead of squashing it', () => {+ test('non-uniform group resize: box scales, strokeGeometry clears, glyphs carry no scale', () => {+ const graph = new SceneGraph()+ const page = expectDefined(graph.getPages()[0])+ const group = graph.createNode('GROUP', page.id, { x: 0, y: 0, width: 256, height: 256 })+ const box = { x: 0, y: 0, width: 256, height: 256 }+ const text = graph.createNode('TEXT', group.id, {+ x: 0,+ y: 0,+ width: 256,+ height: 256,+ text: 'abc',+ fills: [BLACK],+ strokes: [WHITE_STROKE],+ strokeGeometry: [{ windingRule: 'NONZERO', commandsBlob: squareGeometryBlob(256) }],+ textPathBox: { ...box }+ })+ text.textPathData = {+ network: circleNetwork(),+ normalizedSize: { x: 256, y: 256 },+ tValue: 0.25,+ forward: false+ }++ const data = expectDefined(getTextPathData(text), 'synthetic path data')+ const seeds = expectDefined(+ layoutPathTextFromAdvances(data, box, 0.25, 0, [+ { commandsBlob: glyphBlob(), fontSize: 40, advance: 0.6 },+ { commandsBlob: glyphBlob(), fontSize: 40, advance: 0.6 },+ { commandsBlob: glyphBlob(), fontSize: 40, advance: 0.6 }+ ]),+ 'seed glyphs'+ )+ text.derivedTextGlyphs = seeds.map((g) => ({+ ...g,+ commandsBlob: new Uint8Array(g.commandsBlob)+ }))++ const editor = {+ graph,+ renderer: undefined,+ requestRepaint: () => undefined,+ updateNode: (id: string, changes: Partial<SceneNode>) => graph.updateNode(id, changes),+ commitResize: () => undefined,+ commitGroupResize: () => undefined+ } as Editor++ const origChild: OrigChildState = {+ x: 0,+ y: 0,+ width: 256,+ height: 256,+ vectorNetwork: null,+ fillGeometry: [],+ strokeGeometry: copyGeometryPaths(text.strokeGeometry),+ derivedTextGlyphs: seeds.map((g) => ({+ ...g,+ commandsBlob: new Uint8Array(g.commandsBlob)+ })),+ strokes: copyStrokes(text.strokes),+ textPathData: structuredClone(expectDefined(text.textPathData)),+ textPathBox: { ...box }+ }++ const drag: DragResize = {+ type: 'resize',+ handle: 'se',+ startX: 256,+ startY: 256,+ origRect: { x: 0, y: 0, width: 256, height: 256 },+ nodeId: group.id,+ origVectorNetwork: null,+ origFillGeometry: [],+ origStrokeGeometry: [],+ origDerivedTextGlyphs: null,+ origStrokes: [],+ origTextPathData: null,+ origTextPathBox: null,+ origChildren: new Map([[text.id, origChild]])+ }++ // Drag the SE handle right by 256px: 256x256 -> 512x256 (non-uniform).+ applyResize(drag, 512, 256, false, editor)+ commitResizePreview(drag, editor)++ const committed = expectDefined(graph.getNode(text.id), 'committed text node')+ expect(committed.width).toBe(512)+ expect(committed.height).toBe(256)++ // textPathBox scaled x2 in width only.+ const tpb = expectDefined(committed.textPathBox, 'committed textPathBox')+ expect(tpb.x).toBeCloseTo(0, 3)+ expect(tpb.y).toBeCloseTo(0, 3)+ expect(tpb.width).toBeCloseTo(512, 3)+ expect(tpb.height).toBeCloseTo(256, 3)++ // Reflow cleared the baked silhouettes — the renderer rebuilds per glyph.+ expect(committed.strokeGeometry).toEqual([])++ const glyphs = expectDefined(committed.derivedTextGlyphs, 'committed glyphs')+ expect(glyphs).toHaveLength(3)+ for (const g of glyphs) {+ expect(g.scaleX).toBeUndefined()+ expect(g.scaleY).toBeUndefined()+ expect(g.fontSize).toBeCloseTo(40, 3)+ }+ // The wider path actually re-placed the glyphs.+ expect(glyphs.some((g, i) => Math.hypot(g.x - seeds[i].x, g.y - seeds[i].y) > 1)).toBe(true)++ // Reflow keeps stroke weight constant (like font size).+ expect(committed.strokes[0]?.weight).toBeCloseTo(4, 3)++ // Undo payloads snapshot graph state via structuredClone — the committed+ // nodes must not carry proxies or non-clonable values.+ expect(() => structuredClone(committed)).not.toThrow()+ expect(() => structuredClone(expectDefined(graph.getNode(group.id)))).not.toThrow()+ })+})++describe('direct (non-group) resize reflows path text instead of squashing it', () => {+ test('dragging a TEXT_PATH node itself scales the box, clears strokeGeometry, glyphs carry no scale', () => {+ const graph = new SceneGraph()+ const page = expectDefined(graph.getPages()[0])+ const box = { x: 0, y: 0, width: 256, height: 256 }+ const text = graph.createNode('TEXT', page.id, {+ x: 0,+ y: 0,+ width: 256,+ height: 256,+ text: 'abc',+ fills: [BLACK],+ strokes: [WHITE_STROKE],+ strokeGeometry: [{ windingRule: 'NONZERO', commandsBlob: squareGeometryBlob(256) }],+ textPathBox: { ...box }+ })+ text.textPathData = {+ network: circleNetwork(),+ normalizedSize: { x: 256, y: 256 },+ tValue: 0.25,+ forward: false+ }++ const data = expectDefined(getTextPathData(text), 'synthetic path data')+ const seeds = expectDefined(+ layoutPathTextFromAdvances(data, box, 0.25, 0, [+ { commandsBlob: glyphBlob(), fontSize: 40, advance: 0.6 },+ { commandsBlob: glyphBlob(), fontSize: 40, advance: 0.6 },+ { commandsBlob: glyphBlob(), fontSize: 40, advance: 0.6 }+ ]),+ 'seed glyphs'+ )+ text.derivedTextGlyphs = seeds.map((g) => ({+ ...g,+ commandsBlob: new Uint8Array(g.commandsBlob)+ }))++ const editor = {+ graph,+ renderer: undefined,+ requestRepaint: () => undefined,+ updateNode: (id: string, changes: Partial<SceneNode>) => graph.updateNode(id, changes),+ commitResize: () => undefined,+ commitGroupResize: () => undefined+ } as Editor++ const drag: DragResize = {+ type: 'resize',+ handle: 'se',+ startX: 256,+ startY: 256,+ origRect: { x: 0, y: 0, width: 256, height: 256 },+ nodeId: text.id,+ origVectorNetwork: null,+ origFillGeometry: [],+ origStrokeGeometry: copyGeometryPaths(text.strokeGeometry),+ origDerivedTextGlyphs: seeds.map((g) => ({+ ...g,+ commandsBlob: new Uint8Array(g.commandsBlob)+ })),+ origStrokes: copyStrokes(text.strokes),+ origTextPathData: structuredClone(expectDefined(text.textPathData)),+ origTextPathBox: { ...box },+ origChildren: null+ }++ // Drag the SE handle right by 256px: 256x256 -> 512x256 (non-uniform).+ applyResize(drag, 512, 256, false, editor)+ commitResizePreview(drag, editor)++ const committed = expectDefined(graph.getNode(text.id), 'committed text node')+ expect(committed.width).toBe(512)+ expect(committed.height).toBe(256)++ const tpb = expectDefined(committed.textPathBox, 'committed textPathBox')+ expect(tpb.width).toBeCloseTo(512, 3)+ expect(tpb.height).toBeCloseTo(256, 3)++ // Reflow cleared the baked silhouettes — the renderer rebuilds per glyph.+ expect(committed.strokeGeometry).toEqual([])++ const glyphs = expectDefined(committed.derivedTextGlyphs, 'committed glyphs')+ expect(glyphs).toHaveLength(3)+ for (const g of glyphs) {+ expect(g.scaleX).toBeUndefined()+ expect(g.scaleY).toBeUndefined()+ expect(g.fontSize).toBeCloseTo(40, 3)+ }+ // The wider path actually re-placed the glyphs.+ expect(glyphs.some((g, i) => Math.hypot(g.x - seeds[i].x, g.y - seeds[i].y) > 1)).toBe(true)++ // Reflow keeps stroke weight constant (like font size).+ expect(committed.strokes[0]?.weight).toBeCloseTo(4, 3)++ expect(() => structuredClone(committed)).not.toThrow()+ })+})++describe('resize + export integration: real commit path clears stale raw payload', () => {+ test('reflowed derivedTextData exports fresh positions, not the stale pre-resize raw blob', async () => {+ // Regression test for the bug where clearResizedRawGeometry (which deletes+ // rawNodeFields.strokeGeometry on every commit) broke export's reflow+ // detection, letting stale raw derivedTextData resurrect pre-resize glyph+ // positions in the exported file. Unlike the gated fixture test, this+ // drives the REAL resize.ts commit path (not a bare graph.updateNode), so+ // clearResizedRawGeometry actually runs before export sees the node.+ const graph = new SceneGraph()+ const page = expectDefined(graph.getPages()[0])+ const box = { x: 0, y: 0, width: 256, height: 256 }+ const text = graph.createNode('TEXT', page.id, {+ x: 0,+ y: 0,+ width: 256,+ height: 256,+ text: 'abc',+ fills: [BLACK],+ strokes: [WHITE_STROKE],+ strokeGeometry: [{ windingRule: 'NONZERO', commandsBlob: squareGeometryBlob(256) }],+ textPathBox: { ...box }+ })+ // applyRawFigmaNodeFields only force-overwrites nc.derivedTextData from raw+ // when node.source.id is set — that's the imported-node marker a real .fig+ // import stamps. A freshly created (non-imported) node doesn't reach the+ // buggy branch, so this must mimic a genuine import to be a real regression+ // guard.+ text.source.id = '1:2'+ text.textPathData = {+ network: circleNetwork(),+ normalizedSize: { x: 256, y: 256 },+ tValue: 0.25,+ forward: false+ }++ const data = expectDefined(getTextPathData(text), 'synthetic path data')+ const seeds = expectDefined(+ layoutPathTextFromAdvances(data, box, 0.25, 0, [+ { commandsBlob: glyphBlob(), fontSize: 40, advance: 0.6 },+ { commandsBlob: glyphBlob(), fontSize: 40, advance: 0.6 },+ { commandsBlob: glyphBlob(), fontSize: 40, advance: 0.6 }+ ]),+ 'seed glyphs'+ )+ text.derivedTextGlyphs = seeds.map((g) => ({+ ...g,+ commandsBlob: new Uint8Array(g.commandsBlob)+ }))++ // The rest of the raw payload a real .fig import would carry: stale baked+ // derivedTextData + strokeGeometry silhouettes matching the pre-resize seeds.+ text.source.fig.rawNodeFields = {+ ...text.source.fig.rawNodeFields,+ derivedTextData: {+ glyphs: seeds.map((g) => ({+ commandsBlob: { __openPencilFigmaBlob: new Uint8Array(g.commandsBlob) },+ position: { x: g.x, y: g.y },+ fontSize: g.fontSize,+ rotation: g.rotation ?? 0+ }))+ },+ strokeGeometry: [+ { windingRule: 'NONZERO', commandsBlob: { __openPencilFigmaBlob: squareGeometryBlob(256) } }+ ]+ }++ const editor = {+ graph,+ renderer: undefined,+ requestRepaint: () => undefined,+ updateNode: (id: string, changes: Partial<SceneNode>) => graph.updateNode(id, changes),+ commitResize: () => undefined,+ commitGroupResize: () => undefined+ } as Editor++ const drag: DragResize = {+ type: 'resize',+ handle: 'se',+ startX: 256,+ startY: 256,+ origRect: { x: 0, y: 0, width: 256, height: 256 },+ nodeId: text.id,+ origVectorNetwork: null,+ origFillGeometry: [],+ origStrokeGeometry: copyGeometryPaths(text.strokeGeometry),+ origDerivedTextGlyphs: seeds.map((g) => ({+ ...g,+ commandsBlob: new Uint8Array(g.commandsBlob)+ })),+ origStrokes: copyStrokes(text.strokes),+ origTextPathData: structuredClone(expectDefined(text.textPathData)),+ origTextPathBox: { ...box },+ origChildren: null+ }++ // Drag the SE handle right by 256px: 256x256 -> 512x256 (non-uniform).+ applyResize(drag, 512, 256, false, editor)+ commitResizePreview(drag, editor)++ const committed = expectDefined(graph.getNode(text.id), 'committed text node')+ const committedGlyphs = expectDefined(committed.derivedTextGlyphs, 'committed glyphs')+ // Sanity: the real resize path actually reflowed (moved) the glyphs.+ expect(committedGlyphs.some((g, i) => Math.hypot(g.x - seeds[i].x, g.y - seeds[i].y) > 1)).toBe(+ true+ )++ const out = await exportFigFile(graph)+ const reparsed = parseFigBuffer(out)+ const exported = expectDefined(reparsed.nodeChanges.find((nc) => nc.type === 'TEXT_PATH'))++ // No stale silhouette geometry resurrected from the raw payload.+ expect(exported.strokeGeometry).toBeUndefined()++ // Exported derivedTextData must match the REFLOWED positions, not the+ // stale pre-resize raw blob set up above.+ const exportedGlyphs = expectDefined(exported.derivedTextData?.glyphs, 'exported glyphs')+ expect(exportedGlyphs.length).toBe(committedGlyphs.length)+ for (let i = 0; i < committedGlyphs.length; i++) {+ expect(expectDefined(exportedGlyphs[i]?.position?.x)).toBeCloseTo(committedGlyphs[i].x, 2)+ expect(expectDefined(exportedGlyphs[i]?.position?.y)).toBeCloseTo(committedGlyphs[i].y, 2)+ }+ // ...and specifically NOT the stale seed positions (the bug this guards against).+ expect(exportedGlyphs.some((g, i) => Math.abs((g.position?.x ?? 0) - seeds[i].x) > 5)).toBe(+ true+ )+ })+})diff --git a/tests/fixtures/circle-text.fig b/tests/fixtures/circle-text.fignew file mode 100644index 000000000..948af7b62--- /dev/null+++ b/tests/fixtures/circle-text.fig@@ -0,0 +1,3 @@+version https://git-lfs.github.com/spec/v1+oid sha256:23fd94a2593021ca996d96ebe33701aca0831936299f2b2da6819f3709f6136a+size 155324diff --git a/tests/helpers/fig-fixtures.ts b/tests/helpers/fig-fixtures.tsindex 28ae45233..bf0b3e1fe 100644--- a/tests/helpers/fig-fixtures.ts+++ b/tests/helpers/fig-fixtures.ts@@ -1,4 +1,4 @@-import { readFileSync } from 'node:fs'+import { existsSync, readFileSync } from 'node:fs'import { resolve } from 'node:path'import {@@ -66,3 +66,31 @@ export async function parseGoldPreviewFixture(): Promise<{const graph = await parseFixture('gold-preview.fig')return { graph, allNodes: collectAllNodes(graph) }}++const LFS_POINTER_PREFIX = 'version https://git-lfs'++/**+ * Read a `.fig` fixture by absolute path, or `null` when it is absent OR an+ * un-fetched Git LFS pointer. `tests/fixtures/*.fig` are LFS-tracked, so on a+ * shallow/LFS-less checkout `existsSync` passes but the bytes are a tiny ASCII+ * pointer stub — parsing it would throw. Optional-local tests skip on `null`.+ * (Contrast `readFixtureBytes`/`parseFixture`, which take a name and assume the+ * fixture is present.)+ */+export function readFigFixture(path: string): ArrayBuffer | null {+ if (!existsSync(path)) return null+ const bytes = readFileSync(path)+ if (+ bytes.length < 1024 &&+ bytes.toString('utf8', 0, LFS_POINTER_PREFIX.length) === LFS_POINTER_PREFIX+ ) {+ return null+ }+ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength)+}++/** Parse a `.fig` fixture by path into a SceneGraph, or `null` when unavailable (see readFigFixture). */+export async function loadFigFixture(path: string): Promise<SceneGraph | null> {+ const ab = readFigFixture(path)+ return ab ? parseFigFile(ab) : null+}