Skip to content

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

fix: keep stroke weight on canvas resize, close SVG paths on their start, type % or px (#1567)

Danila Poyarkov9b3a34586ae6
diff --git a/changes/1567/breaking.md b/changes/1567/breaking.md
new file mode 100644
index 000000000..31d03be28
--- /dev/null
+++ b/changes/1567/breaking.md
@@ -0,0 +1 @@
+- `clipPolygon` and `clipBoundsToPolygon` move from `@open-pencil/scene-graph/geometry` to `@open-pencil/scene-graph/clipping`.
diff --git a/changes/1567/fixed.md b/changes/1567/fixed.md
new file mode 100644
index 000000000..55a7523bb
--- /dev/null
+++ b/changes/1567/fixed.md
@@ -0,0 +1,4 @@
+- Resizing a layer on the canvas keeps its stroke weight, as in Figma; imported text on a path that kept only its glyphs still scales as a whole.
+- Inside and outside strokes on a vector drawn from its path stay on their side instead of drawing centred.
+- An SVG rounded rectangle imports with its outline closed on its first point, as in Figma, instead of an extra point that left it open.
+- Typing `%` or `px` after a line height or letter spacing switches its unit.
diff --git a/packages/core/src/canvas/scene.ts b/packages/core/src/canvas/scene.ts
index 27c3938e9..f60d08408 100644
--- a/packages/core/src/canvas/scene.ts
+++ b/packages/core/src/canvas/scene.ts
@@ -667,7 +667,7 @@ function vectorStrokePaths(r: SkiaRenderer, node: SceneNode): Path[] | null {
function strokeOutlineKey(
node: SceneNode,
stroke: SceneNode['strokes'][0],
- source: 'runs' | 'regions'
+ source: 'runs' | 'regions' | 'closed' | 'open'
): string {
return `${node.id}|${source}|${stroke.weight}|${stroke.cap ?? node.strokeCap}|${stroke.join ?? node.strokeJoin}|${node.strokeMiterLimit}`
}
@@ -762,6 +762,74 @@ function drawRegularStroke(
}
}
+/**
+ * Strokes a vector's paths on the side its alignment takes, as a shape's stroke is: a centred
+ * stroke twice as wide, kept inside its closed regions for `INSIDE` and outside them for
+ * `OUTSIDE`. Open segments enclose nothing to take a side of, so they stroke centred.
+ */
+function drawAlignedVectorPathStrokes(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ node: SceneNode,
+ vectorPaths: Path[],
+ stroke: SceneNode['strokes'][0],
+ sc: Color
+): void {
+ const miter = node.strokeMiterLimit
+ // `vectorNetworkToPath` lists a path for each region, then one for the open segments.
+ const regions = node.vectorNetwork?.regions.length ?? 0
+ const closed = vectorPaths.slice(0, regions)
+ // The inside of the regions, which an inside stroke keeps to; a union that fails strokes centred.
+ const inside = stroke.align === 'INSIDE' && closed.length > 0 ? unitePaths(r, closed) : null
+ const sided = stroke.align === 'OUTSIDE' ? closed.length > 0 : !!inside
+ if (!sided) {
+ const outlineKey = strokeOutlineKey(node, stroke, 'regions')
+ drawVectorPathStrokes(r, canvas, vectorPaths, stroke, sc, miter, outlineKey)
+ return
+ }
+ const doubled = { ...stroke, weight: stroke.weight * 2 }
+ canvas.save()
+ if (inside) {
+ canvas.clipPath(inside, r.ck.ClipOp.Intersect, true)
+ inside.delete()
+ } else {
+ for (const path of closed) canvas.clipPath(path, r.ck.ClipOp.Difference, true)
+ }
+ drawVectorPathStrokes(
+ r,
+ canvas,
+ closed,
+ doubled,
+ sc,
+ miter,
+ strokeOutlineKey(node, doubled, 'closed')
+ )
+ canvas.restore()
+ const open = vectorPaths.slice(regions)
+ if (open.length > 0)
+ drawVectorPathStrokes(
+ r,
+ canvas,
+ open,
+ stroke,
+ sc,
+ miter,
+ strokeOutlineKey(node, stroke, 'open')
+ )
+}
+
+/** One path covering every path given, which a clip can keep the inside of. */
+function unitePaths(r: SkiaRenderer, paths: Path[]): Path | null {
+ let united: Path | null = paths[0]?.copy() ?? null
+ for (const path of paths.slice(1)) {
+ if (!united) break
+ const next = r.ck.Path.MakeFromOp(united, path, r.ck.PathOp.Union)
+ united.delete()
+ united = next
+ }
+ return united
+}
+
function drawNodeStroke(
r: SkiaRenderer,
canvas: Canvas,
@@ -784,10 +852,8 @@ function drawNodeStroke(
return
}
if (!sg) {
- if (vectorPaths) {
- const outlineKey = strokeOutlineKey(node, stroke, 'regions')
- drawVectorPathStrokes(r, canvas, vectorPaths, stroke, sc, node.strokeMiterLimit, outlineKey)
- } else drawRegularStroke(r, canvas, node, stroke, sc)
+ if (vectorPaths) drawAlignedVectorPathStrokes(r, canvas, node, vectorPaths, stroke, sc)
+ else drawRegularStroke(r, canvas, node, stroke, sc)
return
}
if (stroke.align !== 'INSIDE') {
diff --git a/packages/core/src/figma-api/accessors/basic.ts b/packages/core/src/figma-api/accessors/basic.ts
index c9178a30c..d20752d80 100644
--- a/packages/core/src/figma-api/accessors/basic.ts
+++ b/packages/core/src/figma-api/accessors/basic.ts
@@ -1,5 +1,3 @@
-import { isEmptyObject } from 'es-toolkit'
-
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { getAxisAlignedWorldBounds, getWorldMatrix } from '@open-pencil/scene-graph/coordinate'
import { TRANSFORM_FIELDS as NODE_TRANSFORM_FIELDS } from '@open-pencil/scene-graph/fields'
@@ -265,32 +263,23 @@ function descendants(scene: SceneGraph, node: SceneNode): SceneNode[] {
/**
* A vector's path scaled to its new size, as Figma's resize does. The stroke keeps its weight: with
- * a network to stroke, the saved stroke outline goes and the stroke draws from the scaled path, as
- * when the path is set; without one, the outline is all that draws the stroke, so it scales too.
+ * a path to stroke, the saved stroke outline goes and the stroke draws from the scaled path, as
+ * when the path is set; without one, the outline is all that draws the stroke, so it scales.
*/
function resizedVectorGeometry(node: SceneNode, width: number, height: number): Partial<SceneNode> {
if (node.type !== 'VECTOR') return {}
- const strokesPath = (node.vectorNetwork?.vertices.length ?? 0) > 0
- const snapshot = createResizeSnapshot(node)
- const path = {
- ...snapshot,
- strokes: [],
- strokeGeometry: strokesPath ? [] : snapshot.strokeGeometry
- }
// A side at zero keeps the path along it, as in Figma, so the next resize scales the path from
// its own extent and gets the shape back.
const bounds = node.vectorNetwork ? computeAccurateBounds(node.vectorNetwork) : null
const fromWidth = node.width > 0 ? node.width : (bounds?.width ?? 0)
const fromHeight = node.height > 0 ? node.height : (bounds?.height ?? 0)
- const geometry = scaledGeometryChanges(
- path,
+ return scaledGeometryChanges(
+ createResizeSnapshot(node),
fromWidth,
fromHeight,
width || fromWidth,
height || fromHeight
)
- if (!strokesPath || isEmptyObject(geometry) || node.strokeGeometry.length === 0) return geometry
- return { ...geometry, strokeGeometry: [] }
}
/** The least size Figma's `resize` gives a side; `resizeWithoutConstraints` allows zero. */
diff --git a/packages/core/src/lint/rules/color-contrast.ts b/packages/core/src/lint/rules/color-contrast.ts
index e143cdd01..87194881c 100644
--- a/packages/core/src/lint/rules/color-contrast.ts
+++ b/packages/core/src/lint/rules/color-contrast.ts
@@ -1,11 +1,7 @@
+import { clipPolygon } from '@open-pencil/scene-graph/clipping'
import { colorToHex, compositeOver, contrastRatio } from '@open-pencil/scene-graph/color'
import { BLACK } from '@open-pencil/scene-graph/constants'
-import {
- clipPolygon,
- degToRad,
- rotatedCorners,
- rotatePoint
-} from '@open-pencil/scene-graph/geometry'
+import { degToRad, rotatedCorners, rotatePoint } from '@open-pencil/scene-graph/geometry'
import type { Color, Vector } from '@open-pencil/scene-graph/primitives'
import { defineRule } from '#core/lint/rule'
diff --git a/packages/core/src/tools/analyze/overlaps/helpers.ts b/packages/core/src/tools/analyze/overlaps/helpers.ts
index d7f2622c2..e51408332 100644
--- a/packages/core/src/tools/analyze/overlaps/helpers.ts
+++ b/packages/core/src/tools/analyze/overlaps/helpers.ts
@@ -1,7 +1,7 @@
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import { clipPolygon } from '@open-pencil/scene-graph/clipping'
import { getWorldMatrix } from '@open-pencil/scene-graph/coordinate'
import {
- clipPolygon,
effectOverflow,
geometryBlobBounds,
intersectVisualBounds,
diff --git a/packages/core/tests/canvas/strokes/vector-align.test.ts b/packages/core/tests/canvas/strokes/vector-align.test.ts
new file mode 100644
index 000000000..713976098
--- /dev/null
+++ b/packages/core/tests/canvas/strokes/vector-align.test.ts
@@ -0,0 +1,159 @@
+import { beforeAll, expect, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+
+import { SceneGraph, type Stroke, type VectorNetwork } from '@open-pencil/scene-graph'
+import { strokeOverflow } from '@open-pencil/scene-graph/geometry'
+
+import { SkiaRenderer } from '#core/canvas/renderer'
+import { getCanvasKit } from '#core/canvaskit'
+import { renderNodesToImage } from '#core/io/formats/raster/render'
+
+let ck: Awaited<ReturnType<typeof getCanvasKit>>
+
+beforeAll(async () => {
+ ck = await getCanvasKit()
+})
+
+const SIDE = 40
+const corner = { x: 0, y: 0 }
+const SQUARE: VectorNetwork = {
+ vertices: [
+ { x: 0, y: 0 },
+ { x: SIDE, y: 0 },
+ { x: SIDE, y: SIDE },
+ { x: 0, y: SIDE }
+ ],
+ segments: [0, 1, 2, 3].map((start) => ({
+ start,
+ end: (start + 1) % 4,
+ tangentStart: corner,
+ tangentEnd: corner
+ })),
+ regions: [{ windingRule: 'NONZERO', loops: [[0, 1, 2, 3]] }]
+}
+
+/** The square's first three sides, open, with no region to fill. */
+const OPEN: VectorNetwork = {
+ vertices: SQUARE.vertices,
+ segments: SQUARE.segments.slice(0, 3),
+ regions: []
+}
+
+/** The closed square with a separate open line at x = 60 beside it. */
+const MIXED: VectorNetwork = {
+ vertices: [...SQUARE.vertices, { x: 60, y: 0 }, { x: 60, y: SIDE }],
+ segments: [...SQUARE.segments, { start: 4, end: 5, tangentStart: corner, tangentEnd: corner }],
+ regions: SQUARE.regions
+}
+
+/** Whether the shape's 8 px stroke inks the row through its middle `x` px from its left edge. */
+function inks(align: Stroke['align'], network = SQUARE, span = SIDE): (x: number) => boolean {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const vector = graph.createNode('VECTOR', page.id, {
+ width: span,
+ height: SIDE,
+ vectorNetwork: network,
+ fills: [],
+ strokes: [
+ {
+ type: 'SOLID',
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ weight: 8,
+ opacity: 1,
+ visible: true,
+ align,
+ cap: 'NONE',
+ join: 'MITER',
+ dashPattern: []
+ }
+ ]
+ })
+ const surface = expectDefined(ck.MakeSurface(1, 1), 'surface')
+ const renderer = new SkiaRenderer(ck, surface)
+ try {
+ const png = expectDefined(
+ renderNodesToImage(ck, renderer, graph, page.id, [vector.id], { scale: 1, format: 'PNG' }),
+ 'png'
+ )
+ 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'
+ )
+ // The export starts where the stroke's ink can reach, outside the square's left edge.
+ const left = (image.width() - span) / 2
+ const row = Math.floor(image.height() / 2)
+ const width = image.width()
+ image.delete()
+ return (x) => pixels[(row * width + Math.floor(left + x)) * 4 + 3] > 128
+ } finally {
+ surface.delete()
+ }
+}
+
+// Figma 126 strokes inside or outside a path as a centred stroke twice as wide, clipped.
+test('a vector stroked from its path keeps the stroke on the side its alignment takes', () => {
+ const center = inks('CENTER')
+ expect([center(-6), center(2), center(6)]).toEqual([false, true, false])
+ const inside = inks('INSIDE')
+ expect([inside(2), inside(6), inside(10)]).toEqual([true, true, false])
+ const outside = inks('OUTSIDE')
+ expect([outside(-6), outside(2), outside(6)]).toEqual([true, false, false])
+})
+
+// An open path encloses nothing to take a side of, so its stroke stays centred at its weight.
+test('an open vector path strokes centred whatever its alignment', () => {
+ for (const align of ['INSIDE', 'OUTSIDE'] as const) {
+ const open = inks(align, OPEN)
+ expect([open(34), open(38), open(42), open(46)]).toEqual([false, true, true, false])
+ }
+})
+
+// Closed regions take the stroke's side; an open line beside them strokes centred, not doubled.
+test('a vector with a closed region and an open line aligns only the region', () => {
+ const inside = inks('INSIDE', MIXED, 60)
+ expect([inside(2), inside(6), inside(54), inside(58), inside(62)]).toEqual([
+ true,
+ true,
+ false,
+ true,
+ true
+ ])
+ const outside = inks('OUTSIDE', MIXED, 60)
+ expect([outside(-6), outside(2), outside(54), outside(58), outside(62)]).toEqual([
+ true,
+ false,
+ false,
+ true,
+ true
+ ])
+})
+
+// Bounds reach as far as that ink: a full stroke out of a closed region, half one beside an open line.
+test('stroke bounds reach as far as the side each part of a vector strokes', () => {
+ const outside = (align: Stroke['align']): Stroke[] => [
+ {
+ type: 'SOLID',
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ weight: 8,
+ opacity: 1,
+ visible: true,
+ align,
+ cap: 'NONE',
+ join: 'ROUND',
+ dashPattern: []
+ }
+ ]
+ expect(strokeOverflow(outside('OUTSIDE'), 'NONE', OPEN)).toBe(4)
+ expect(strokeOverflow(outside('OUTSIDE'), 'NONE', MIXED)).toBe(8)
+ expect(strokeOverflow(outside('INSIDE'), 'NONE', MIXED)).toBe(4)
+ expect(strokeOverflow(outside('INSIDE'), 'NONE', SQUARE)).toBe(0)
+})
diff --git a/packages/core/tests/figma-api/accessors/basic/resize/vector-geometry.test.ts b/packages/core/tests/figma-api/accessors/basic/resize/vector-geometry.test.ts
index 3ca0e09e0..e223ea8fb 100644
--- a/packages/core/tests/figma-api/accessors/basic/resize/vector-geometry.test.ts
+++ b/packages/core/tests/figma-api/accessors/basic/resize/vector-geometry.test.ts
@@ -1,7 +1,5 @@
import { expect, test } from 'bun:test'
-import { uniqBy } from 'es-toolkit'
-
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { createSVGNodes } from '@open-pencil/core/io/formats/svg'
import { SceneGraph } from '@open-pencil/scene-graph'
@@ -47,12 +45,9 @@ for (const method of ['resize', 'resizeWithoutConstraints'] as const) {
if (!resizedNetwork) throw new Error('Resized vector has no vector network')
expect(vector.width).toBe(318)
expect(vector.height).toBe(64)
- // Our SVG import keeps the closing point as its own vertex, which Figma merges.
- const vertices = uniqBy(
- resizedNetwork.vertices.map(({ x, y }) => [round(x), round(y)]),
- (point) => point.join(',')
+ expect(resizedNetwork.vertices.map(({ x, y }) => [round(x), round(y)])).toEqual(
+ RESIZED_VERTICES
)
- expect(vertices).toEqual(RESIZED_VERTICES)
})
}
diff --git a/packages/scene-graph/package.json b/packages/scene-graph/package.json
index c1008a5b1..39c43ea44 100644
--- a/packages/scene-graph/package.json
+++ b/packages/scene-graph/package.json
@@ -242,6 +242,12 @@
"import": "./dist/plugin-data/index.js",
"default": "./dist/plugin-data/index.js"
},
+ "./clipping": {
+ "types": "./dist/clipping.d.ts",
+ "bun": "./src/clipping.ts",
+ "import": "./dist/clipping.js",
+ "default": "./dist/clipping.js"
+ },
"./polygon": {
"types": "./dist/polygon.d.ts",
"bun": "./src/polygon.ts",
diff --git a/packages/scene-graph/src/clipping.ts b/packages/scene-graph/src/clipping.ts
new file mode 100644
index 000000000..7c9298589
--- /dev/null
+++ b/packages/scene-graph/src/clipping.ts
@@ -0,0 +1,112 @@
+import { computeBounds, type VisualBounds } from './geometry'
+import type { Vector } from './primitives'
+
+/**
+ * Rotated-rectangle clipping: a polygon or an axis-aligned box cut by a convex polygon, such as
+ * the canvas corners of a rotated frame that clips its content.
+ */
+
+function crossProduct(a: Vector, b: Vector, p: Vector): number {
+ return (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x)
+}
+
+function lineSegmentIntersect(p1: Vector, p2: Vector, p3: Vector, p4: Vector): Vector {
+ const dx1 = p2.x - p1.x
+ const dy1 = p2.y - p1.y
+ const dx2 = p4.x - p3.x
+ const dy2 = p4.y - p3.y
+ const denom = dx1 * dy2 - dy1 * dx2
+ if (denom === 0) return p1
+ const t = ((p3.x - p1.x) * dy2 - (p3.y - p1.y) * dx2) / denom
+ return { x: p1.x + t * dx1, y: p1.y + t * dy1 }
+}
+
+function clipHalfPlane(polygon: Vector[], a: Vector, b: Vector, wantPositive: boolean): Vector[] {
+ const output: Vector[] = []
+ const isInside = (p: Vector): boolean => {
+ const cross = crossProduct(a, b, p)
+ return wantPositive ? cross >= 0 : cross <= 0
+ }
+ for (let i = 0; i < polygon.length; i++) {
+ const curr = polygon[i]
+ const prev = polygon[i === 0 ? polygon.length - 1 : i - 1]
+ const currInside = isInside(curr)
+ const prevInside = isInside(prev)
+ if (currInside) {
+ if (!prevInside) output.push(lineSegmentIntersect(prev, curr, a, b))
+ output.push(curr)
+ } else if (prevInside) {
+ output.push(lineSegmentIntersect(prev, curr, a, b))
+ }
+ }
+ return output
+}
+
+/**
+ * Clip a subject polygon against a convex polygon (e.g. the 4 canvas-space
+ * corners of a rotated clipping ancestor).
+ *
+ * Uses Sutherland–Hodgman polygon clipping with centroid-based interior
+ * detection, making it robust to either winding order of the clip polygon.
+ * Returns the clipped polygon, or null if the subject is fully outside the
+ * clip polygon. When `clipCorners` has fewer than 3 points the subject is
+ * returned unchanged (no clipping).
+ *
+ * Preserving the polygon (rather than collapsing to an AABB) lets callers
+ * chain multiple clips without reintroducing corners removed by an inner clip.
+ */
+export function clipPolygon(subject: Vector[], clipCorners: Vector[]): Vector[] | null {
+ if (clipCorners.length < 3) return subject
+
+ let cx = 0
+ let cy = 0
+ for (const c of clipCorners) {
+ cx += c.x
+ cy += c.y
+ }
+ cx /= clipCorners.length
+ cy /= clipCorners.length
+
+ let polygon: Vector[] = subject
+
+ for (let i = 0; i < clipCorners.length; i++) {
+ if (polygon.length === 0) return null
+ const a = clipCorners[i]
+ const b = clipCorners[(i + 1) % clipCorners.length]
+ const centroidCross = crossProduct(a, b, { x: cx, y: cy })
+ polygon = clipHalfPlane(polygon, a, b, centroidCross >= 0)
+ }
+
+ return polygon.length === 0 ? null : polygon
+}
+
+/**
+ * Clip an axis-aligned VisualBounds rectangle against a convex polygon
+ * (e.g. the 4 canvas-space corners of a rotated clipping ancestor).
+ *
+ * Returns the AABB of the intersection, or null if the bounds are fully
+ * outside the clip polygon. Delegates to {@link clipPolygon}.
+ *
+ * For a non-rotated clip (axis-aligned corners) the result is identical
+ * to `intersectVisualBounds`.
+ */
+export function clipBoundsToPolygon(
+ bounds: VisualBounds,
+ clipCorners: Vector[]
+): VisualBounds | null {
+ if (clipCorners.length < 3) return bounds
+
+ const subject: Vector[] = [
+ { x: bounds.minX, y: bounds.minY },
+ { x: bounds.maxX, y: bounds.minY },
+ { x: bounds.maxX, y: bounds.maxY },
+ { x: bounds.minX, y: bounds.maxY }
+ ]
+
+ const polygon = clipPolygon(subject, clipCorners)
+ if (!polygon) return null
+
+ const box = computeBounds(polygon.map(({ x, y }) => ({ x, y, width: 0, height: 0 })))
+ if (box.width <= 0 || box.height <= 0) return null
+ return { minX: box.x, minY: box.y, maxX: box.x + box.width, maxY: box.y + box.height }
+}
diff --git a/packages/scene-graph/src/geometry.ts b/packages/scene-graph/src/geometry.ts
index b761ecf7a..d5e95d202 100644
--- a/packages/scene-graph/src/geometry.ts
+++ b/packages/scene-graph/src/geometry.ts
@@ -156,12 +156,18 @@ export function strokeOverflow(
shape?: StrokeShape
): number {
const line = shape?.type === 'LINE'
+ // Open segments enclose nothing to take a side of, so their strokes draw centred; a network
+ // with closed regions still strokes those on their side.
+ const enclosed = new Set(network?.regions.flatMap((region) => region.loops.flat()))
+ const open = network?.segments.some((_, index) => !enclosed.has(index)) ?? false
+ const sided = !network || network.regions.length > 0
let overflow = 0
for (const stroke of strokes ?? []) {
if (!stroke.visible) continue
- let extra = 0
- if (line || stroke.align === 'OUTSIDE') extra = stroke.weight
- else if (stroke.align === 'CENTER') extra = stroke.weight / 2
+ const align = sided ? stroke.align : 'CENTER'
+ let extra = open ? stroke.weight / 2 : 0
+ if (line || align === 'OUTSIDE') extra = stroke.weight
+ else if (align === 'CENTER') extra = stroke.weight / 2
const miter = network
? miterRatio(network, stroke.join ?? shape?.strokeJoin, shape?.strokeMiterLimit)
: 1
@@ -482,118 +488,3 @@ export function computeDescendantVisualBounds(
}
return bounds
}
-
-// ── Rotated-rectangle clipping ──
-
-function crossProduct(a: Vector, b: Vector, p: Vector): number {
- return (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x)
-}
-
-function lineSegmentIntersect(p1: Vector, p2: Vector, p3: Vector, p4: Vector): Vector {
- const dx1 = p2.x - p1.x
- const dy1 = p2.y - p1.y
- const dx2 = p4.x - p3.x
- const dy2 = p4.y - p3.y
- const denom = dx1 * dy2 - dy1 * dx2
- if (denom === 0) return p1
- const t = ((p3.x - p1.x) * dy2 - (p3.y - p1.y) * dx2) / denom
- return { x: p1.x + t * dx1, y: p1.y + t * dy1 }
-}
-
-function clipHalfPlane(polygon: Vector[], a: Vector, b: Vector, wantPositive: boolean): Vector[] {
- const output: Vector[] = []
- const isInside = (p: Vector): boolean => {
- const cross = crossProduct(a, b, p)
- return wantPositive ? cross >= 0 : cross <= 0
- }
- for (let i = 0; i < polygon.length; i++) {
- const curr = polygon[i]
- const prev = polygon[i === 0 ? polygon.length - 1 : i - 1]
- const currInside = isInside(curr)
- const prevInside = isInside(prev)
- if (currInside) {
- if (!prevInside) output.push(lineSegmentIntersect(prev, curr, a, b))
- output.push(curr)
- } else if (prevInside) {
- output.push(lineSegmentIntersect(prev, curr, a, b))
- }
- }
- return output
-}
-
-/**
- * Clip a subject polygon against a convex polygon (e.g. the 4 canvas-space
- * corners of a rotated clipping ancestor).
- *
- * Uses Sutherland–Hodgman polygon clipping with centroid-based interior
- * detection, making it robust to either winding order of the clip polygon.
- * Returns the clipped polygon, or null if the subject is fully outside the
- * clip polygon. When `clipCorners` has fewer than 3 points the subject is
- * returned unchanged (no clipping).
- *
- * Preserving the polygon (rather than collapsing to an AABB) lets callers
- * chain multiple clips without reintroducing corners removed by an inner clip.
- */
-export function clipPolygon(subject: Vector[], clipCorners: Vector[]): Vector[] | null {
- if (clipCorners.length < 3) return subject
-
- let cx = 0
- let cy = 0
- for (const c of clipCorners) {
- cx += c.x
- cy += c.y
- }
- cx /= clipCorners.length
- cy /= clipCorners.length
-
- let polygon: Vector[] = subject
-
- for (let i = 0; i < clipCorners.length; i++) {
- if (polygon.length === 0) return null
- const a = clipCorners[i]
- const b = clipCorners[(i + 1) % clipCorners.length]
- const centroidCross = crossProduct(a, b, { x: cx, y: cy })
- polygon = clipHalfPlane(polygon, a, b, centroidCross >= 0)
- }
-
- return polygon.length === 0 ? null : polygon
-}
-
-/**
- * Clip an axis-aligned VisualBounds rectangle against a convex polygon
- * (e.g. the 4 canvas-space corners of a rotated clipping ancestor).
- *
- * Returns the AABB of the intersection, or null if the bounds are fully
- * outside the clip polygon. Delegates to {@link clipPolygon}.
- *
- * For a non-rotated clip (axis-aligned corners) the result is identical
- * to `intersectVisualBounds`.
- */
-export function clipBoundsToPolygon(
- bounds: VisualBounds,
- clipCorners: Vector[]
-): VisualBounds | null {
- if (clipCorners.length < 3) return bounds
-
- const subject: Vector[] = [
- { x: bounds.minX, y: bounds.minY },
- { x: bounds.maxX, y: bounds.minY },
- { x: bounds.maxX, y: bounds.maxY },
- { x: bounds.minX, y: bounds.maxY }
- ]
-
- const polygon = clipPolygon(subject, clipCorners)
- if (!polygon) return null
-
- let minX = Infinity
- let minY = Infinity
- let maxX = -Infinity
- let maxY = -Infinity
- for (const p of polygon) {
- if (p.x < minX) minX = p.x
- if (p.y < minY) minY = p.y
- if (p.x > maxX) maxX = p.x
- if (p.y > maxY) maxY = p.y
- }
- return minX < maxX && minY < maxY ? { minX, minY, maxX, maxY } : null
-}
diff --git a/packages/scene-graph/src/parse-path.ts b/packages/scene-graph/src/parse-path.ts
index 483192cb2..c5b8b4e4e 100644
--- a/packages/scene-graph/src/parse-path.ts
+++ b/packages/scene-graph/src/parse-path.ts
@@ -9,6 +9,9 @@ interface SubPath {
}
export type VectorPathWindingRule = WindingRule | 'NONE'
+
+/** How far apart an end and its subpath's start can be from rounding alone. */
+const CLOSING_ROUNDING = 1e-6
export type SVGPathParseResult = { ok: true; network: VectorNetwork } | { ok: false; error: string }
interface ParseOptions {
@@ -76,6 +79,8 @@ function parsePath(
let cy = 0
const vertexMap = new Map<string, number>()
+ /** How many segment ends sit on each vertex. */
+ const uses: number[] = []
function getOrCreateVertex(x: number, y: number): number {
const key = `${x},${y}`
@@ -99,6 +104,8 @@ function parsePath(
): void {
const startIdx = getOrCreateVertex(x1, y1)
const endIdx = getOrCreateVertex(x2, y2)
+ uses[startIdx] = (uses[startIdx] ?? 0) + 1
+ uses[endIdx] = (uses[endIdx] ?? 0) + 1
const segIdx = segments.length
segments.push({
start: startIdx,
@@ -128,6 +135,27 @@ function parsePath(
addSegment(x1, y1, x2, y2, cp1x, cp1y, cp2x, cp2y)
}
+ /**
+ * A subpath that ends a hair off its start, as an arc turned into curves does, ends on the start
+ * vertex, as Figma merges them; the point it ended on goes when no other segment uses it.
+ */
+ function closeOnStart(subPath: SubPath): void {
+ const lastIndex = subPath.segmentIndices.at(-1)
+ if (lastIndex === undefined) return
+ const last = segments[lastIndex]
+ if (last.end === subPath.startVertexIndex) return
+ const stray = last.end
+ last.end = subPath.startVertexIndex
+ uses[subPath.startVertexIndex] += 1
+ uses[stray] -= 1
+ // Only the newest vertex can go without renumbering the others.
+ if (uses[stray] > 0 || stray !== vertices.length - 1) return
+ const point = vertices[stray]
+ vertices.pop()
+ uses.pop()
+ vertexMap.delete(`${point.x},${point.y}`)
+ }
+
const parsed = svgpath(d)
const parseError = 'err' in parsed && typeof parsed.err === 'string' ? parsed.err : null
if (parseError) return { ok: false, error: parseError }
@@ -184,9 +212,13 @@ function parsePath(
} else if (cmd === 'Z' || cmd === 'z') {
if (currentSubPath) {
const startVert = vertices[currentSubPath.startVertexIndex]
- if (Math.abs(cx - startVert.x) > 0.001 || Math.abs(cy - startVert.y) > 0.001) {
- addLine(cx, cy, startVert.x, startVert.y)
- }
+ // Only rounding, such as an arc turned into curves leaves, merges an end into the start;
+ // a point the path drew, however close, keeps its own closing segment.
+ const rounding =
+ Math.abs(cx - startVert.x) <= CLOSING_ROUNDING &&
+ Math.abs(cy - startVert.y) <= CLOSING_ROUNDING
+ if (rounding) closeOnStart(currentSubPath)
+ else addLine(cx, cy, startVert.x, startVert.y)
currentSubPath.closed = true
cx = startVert.x
cy = startVert.y
diff --git a/packages/scene-graph/src/resize.ts b/packages/scene-graph/src/resize.ts
index 9387fd90e..975530435 100644
--- a/packages/scene-graph/src/resize.ts
+++ b/packages/scene-graph/src/resize.ts
@@ -18,6 +18,7 @@ import { cloneVectorNetwork } from './vector-network'
*/
export type ResizeSnapshot = Pick<
SceneNode,
+ | 'type'
| 'x'
| 'y'
| 'width'
@@ -223,6 +224,7 @@ export function scaleVectorNetworkForResize(
/** Snapshot one node's resize-relevant state (rect + geometry that must scale with it). */
export function createResizeSnapshot(node: SceneNode): ResizeSnapshot {
return {
+ type: node.type,
x: node.x,
y: node.y,
width: node.width,
@@ -253,6 +255,10 @@ function scaleDerivedGlyphs(
}))
}
+function hasPath(orig: Pick<ResizeSnapshot, 'vectorNetwork'>): boolean {
+ return (orig.vectorNetwork?.segments.length ?? 0) > 0
+}
+
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.
@@ -269,6 +275,7 @@ function scaleStrokes(strokes: Stroke[], sx: number, sy: number): Stroke[] {
export function scaledGeometryChanges(
orig: Pick<
ResizeSnapshot,
+ | 'type'
| 'vectorNetwork'
| 'fillGeometry'
| 'strokeGeometry'
@@ -300,8 +307,12 @@ export function scaledGeometryChanges(
if (orig.fillGeometry.length > 0) {
changes.fillGeometry = scaleGeometryPaths(orig.fillGeometry, sx, sy)
}
+ // A stroke keeps its weight through a resize, as in Figma, so a saved stroke outline goes where
+ // the stroke can be drawn again at its weight: from a path, or from a shape's own outline.
+ // Text and a vector with only its outline keep scaling the outline, which is all they have.
+ const outlineOnly = orig.type === 'TEXT' || (orig.type === 'VECTOR' && !hasPath(orig))
if (orig.strokeGeometry.length > 0) {
- changes.strokeGeometry = scaleGeometryPaths(orig.strokeGeometry, sx, sy)
+ changes.strokeGeometry = outlineOnly ? scaleGeometryPaths(orig.strokeGeometry, sx, sy) : []
}
// Path text scales with its path, including baked path text that kept only rotated glyphs;
// other text reflows in the new box, so its glyphs are dropped.
@@ -322,7 +333,9 @@ export function scaledGeometryChanges(
}
}
}
- if (orig.strokes.length > 0) {
+ // Glyphs scaled as a picture take their strokes along; any other stroke keeps its weight, as
+ // Figma reports it, even where only a scaled outline can draw it.
+ if (orig.strokes.length > 0 && glyphs.length > 0 && pathText) {
changes.strokes = scaleStrokes(orig.strokes, sx, sy)
}
return changes
diff --git a/packages/scene-graph/tests/parse-path.test.ts b/packages/scene-graph/tests/parse-path.test.ts
index 17a29bb17..89f5f1119 100644
--- a/packages/scene-graph/tests/parse-path.test.ts
+++ b/packages/scene-graph/tests/parse-path.test.ts
@@ -26,4 +26,37 @@ describe('parseSVGPath', () => {
}
])
})
+
+ // Figma 126 imports a 318×80 rectangle with rx 12 as 8 vertices.
+ test('closes a subpath whose last arc ends a hair off its start on the start vertex', () => {
+ const network = parseSVGPath(
+ 'M12 0H306A12 12 0 0 1 318 12V68A12 12 0 0 1 306 80H12A12 12 0 0 1 0 68V12A12 12 0 0 1 12 0Z'
+ )
+
+ expect(network.vertices).toHaveLength(8)
+ expect(network.segments.at(-1)?.end).toBe(0)
+ })
+
+ test('keeps the point a subpath ended on when other segments use it', () => {
+ const network = parseSVGPath('M0 0L5 5L0.0000001 0L5 5L0.0000001 0Z')
+
+ expect(network.vertices).toHaveLength(3)
+ expect(network.segments.map(({ start, end }) => [start, end])).toEqual([
+ [0, 1],
+ [1, 2],
+ [2, 1],
+ [1, 0]
+ ])
+ })
+
+ test('closes a tiny shape with a segment of its own rather than merging its points', () => {
+ const network = parseSVGPath('M0 0L0.0005 0L0 0.0005Z')
+
+ expect(network.vertices).toHaveLength(3)
+ expect(network.segments.map(({ start, end }) => [start, end])).toEqual([
+ [0, 1],
+ [1, 2],
+ [2, 0]
+ ])
+ })
})
diff --git a/packages/scene-graph/tests/resize.test.ts b/packages/scene-graph/tests/resize.test.ts
index e0f165515..222f6f691 100644
--- a/packages/scene-graph/tests/resize.test.ts
+++ b/packages/scene-graph/tests/resize.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, test } from 'bun:test'
import type { ConstraintType } from '@open-pencil/scene-graph'
-import { constrainedChildRect } from '@open-pencil/scene-graph/resize'
+import { constrainedChildRect, scaledGeometryChanges } from '@open-pencil/scene-graph/resize'
// Live Figma, 2026-10-10: a locked 100×50 rectangle at 50,50 in a 200×200 frame.
const child = { x: 50, y: 50, width: 100, height: 50 }
@@ -63,3 +63,34 @@ describe('constraints with a locked aspect ratio', () => {
})
})
})
+
+describe('saved stroke outlines through a resize', () => {
+ const outline = { windingRule: 'NONZERO' as const, commandsBlob: new Uint8Array([0]) }
+ const vector = (segments: number) => ({
+ type: 'VECTOR' as const,
+ vectorNetwork: {
+ vertices: [
+ { x: 0, y: 0 },
+ { x: 10, y: 0 }
+ ],
+ segments: Array.from({ length: segments }, () => ({
+ start: 0,
+ end: 1,
+ tangentStart: { x: 0, y: 0 },
+ tangentEnd: { x: 0, y: 0 }
+ })),
+ regions: []
+ },
+ fillGeometry: [],
+ strokeGeometry: [outline],
+ derivedTextGlyphs: null,
+ strokes: [],
+ textPathData: null,
+ textPathBox: null
+ })
+
+ test('go where a path can draw the stroke again, and stay where only the outline can', () => {
+ expect(scaledGeometryChanges(vector(1), 10, 10, 20, 10).strokeGeometry).toEqual([])
+ expect(scaledGeometryChanges(vector(0), 10, 10, 20, 10).strokeGeometry).toHaveLength(1)
+ })
+})
diff --git a/packages/scene-graph/tsdown.config.ts b/packages/scene-graph/tsdown.config.ts
index 7db15f8c0..48bc5d784 100644
--- a/packages/scene-graph/tsdown.config.ts
+++ b/packages/scene-graph/tsdown.config.ts
@@ -39,6 +39,7 @@ export default defineConfig({
'paints/index': './src/paints/index.ts',
'parse-path': './src/parse-path.ts',
'plugin-data/index': './src/plugin-data/index.ts',
+ clipping: './src/clipping.ts',
polygon: './src/polygon.ts',
preview: './src/preview.ts',
'primitives/index': './src/primitives/index.ts',
diff --git a/packages/vue/src/controls/typography/actions.ts b/packages/vue/src/controls/typography/actions.ts
index 9a3060a01..98bafb842 100644
--- a/packages/vue/src/controls/typography/actions.ts
+++ b/packages/vue/src/controls/typography/actions.ts
@@ -410,6 +410,18 @@ export function createTypographyActions({
batch.flush()
}
+ /** Puts back what a cancelled field previewed, as `cancelAxis` does for a font axis. */
+ function cancelProp(key: keyof SceneNode) {
+ if (previewKey === key) {
+ for (const [id, before] of beforePreview)
+ editor.updateNode(id, { [key]: before.value, textStyleId: before.textStyleId })
+ }
+ previewKey = undefined
+ beforePreview.clear()
+ batch.flush()
+ editor.requestRender()
+ }
+
return {
setFamily,
setWeight,
@@ -428,6 +440,7 @@ export function createTypographyActions({
toggleDecoration,
onFormattingChange,
updateProp,
- commitProp
+ commitProp,
+ cancelProp
}
}
diff --git a/packages/vue/src/primitives/NumberField/NumberFieldRoot.vue b/packages/vue/src/primitives/NumberField/NumberFieldRoot.vue
index da4a44b93..3748b07d0 100644
--- a/packages/vue/src/primitives/NumberField/NumberFieldRoot.vue
+++ b/packages/vue/src/primitives/NumberField/NumberFieldRoot.vue
@@ -37,7 +37,8 @@ const {
ariaLabel,
disabled: disabledProp = false,
bound: boundProp = false,
- editPolicy = 'editable'
+ editPolicy = 'editable',
+ units = []
} = defineProps<NumberFieldRootProps>()
const emit = defineEmits<NumberFieldRootEmits>()
defineSlots<NumberFieldRootSlots>()
@@ -80,6 +81,11 @@ const ariaLabelValue = computed(() => ariaLabel)
let interactionStartValue = 0
let interactionStartedMixed = false
let mutationRequested = false
+/**
+ * The draft the field itself last wrote, on focus or with the arrow keys, whose value is already
+ * absolute: `-1` there is not "minus 1". A draft the user types is an expression.
+ */
+let absoluteDraft: string | null = null
let stopMove: (() => void) | undefined
let stopUp: (() => void) | undefined
let stopCancel: (() => void) | undefined
@@ -107,14 +113,16 @@ function beginInteraction() {
interactionStartedMixed = isMixed.value
workingValue.value = numericValue.value
mutationRequested = false
+ absoluteDraft = null
invalidReason.value = null
}
-function updateValue(value: number) {
+/** Shows `value` live, in the unit typed after it when there is one. */
+function updateValue(value: number, unit?: string) {
const normalized = normalizeNumberValue(clampNumberValue(value, min, max))
workingValue.value = normalized
if (binding?.actions.applyValue(normalized)) return
- if (modelValue !== normalized) emit('update:modelValue', normalized)
+ if (modelValue !== normalized || unit) emit('update:modelValue', normalized, unit)
}
function restoreInteractionValue() {
@@ -127,15 +135,15 @@ function restoreInteractionValue() {
}
}
-function finishCommit(value: number) {
- updateValue(value)
+function finishCommit(value: number, unit?: string) {
+ updateValue(value, unit)
editing.value = false
if (
mutationRequested ||
workingValue.value !== interactionStartValue ||
interactionStartedMixed
) {
- emit('commit', workingValue.value, interactionStartValue)
+ emit('commit', workingValue.value, interactionStartValue, unit)
}
binding?.actions.commitMutation()
}
@@ -144,6 +152,8 @@ function startEdit() {
if (editing.value || !canMutate()) return
beginInteraction()
draftValue.value = interactionStartedMixed ? '' : String(interactionStartValue)
+ // A mixed field's empty draft stays an expression, which Enter rejects.
+ absoluteDraft = interactionStartedMixed ? null : draftValue.value
editing.value = true
void nextTick(() => {
inputRef.value?.focus()
@@ -162,10 +172,24 @@ function onInput(event: Event) {
setDraft(inputValue(event))
}
+/** The typed expression without a unit from `units` it ends with, and that unit. */
+function splitUnit(expression: string): { value: string; unit?: string } {
+ const source = expression.trim()
+ const unit = [...units]
+ .sort((a, b) => b.length - a.length)
+ .find((candidate) => source.toLowerCase().endsWith(candidate.toLowerCase()))
+ return unit ? { value: source.slice(0, -unit.length), unit } : { value: source }
+}
+
function commitEdit() {
if (!editing.value) return
const expression = draftValue.value
- const result = evaluateNumberExpression(expression, {
+ const { value, unit } = splitUnit(expression)
+ if (expression === absoluteDraft) {
+ finishCommit(workingValue.value, unit)
+ return
+ }
+ const result = evaluateNumberExpression(value, {
current: interactionStartValue,
max,
mixed: interactionStartedMixed
@@ -179,7 +203,7 @@ function commitEdit() {
emit('invalid', expression, result.error)
return
}
- finishCommit(result.value)
+ finishCommit(result.value, unit)
}
function cancelEdit() {
@@ -270,13 +294,16 @@ function stepValueFromKeyboard(event: KeyboardEvent) {
if (!requestMutation('step')) return true
event.preventDefault()
- const draftResult = editing.value
- ? evaluateNumberExpression(draftValue.value, {
- current: interactionStartValue,
- max,
- mixed: interactionStartedMixed
- })
- : undefined
+ // A unit typed after the value stays on it, for the commit to report.
+ const draft = editing.value ? splitUnit(draftValue.value) : undefined
+ const draftResult =
+ draft && draftValue.value !== absoluteDraft
+ ? evaluateNumberExpression(draft.value, {
+ current: interactionStartValue,
+ max,
+ mixed: interactionStartedMixed
+ })
+ : undefined
const base = draftResult?.ok ? draftResult.value : workingValue.value
const next = stepNumberValue(
base,
@@ -286,8 +313,9 @@ function stepValueFromKeyboard(event: KeyboardEvent) {
min,
max
)
- updateValue(next)
- draftValue.value = String(next)
+ updateValue(next, draft?.unit)
+ draftValue.value = `${next}${draft?.unit ?? ''}`
+ absoluteDraft = draftValue.value
if (!editing.value) {
emit('commit', next, interactionStartValue)
diff --git a/packages/vue/src/primitives/NumberField/types.ts b/packages/vue/src/primitives/NumberField/types.ts
index 6238bfcb0..24df93df4 100644
--- a/packages/vue/src/primitives/NumberField/types.ts
+++ b/packages/vue/src/primitives/NumberField/types.ts
@@ -28,13 +28,18 @@ export interface NumberFieldRootProps {
bound?: boolean
/** Mutation policy used when the value is bound. */
editPolicy?: NumberFieldEditPolicy
+ /**
+ * Units a typed value may end with, such as `%` or `px`; the commit reports the one typed. A
+ * unit listed here is read as that unit, not as a percent of `max`.
+ */
+ units?: readonly string[]
}
export interface NumberFieldRootEmits {
/** Emitted for live numeric updates and committed expression results. */
- (event: 'update:modelValue', value: number): void
- /** Emitted once after a changed interaction is committed. */
- (event: 'commit', value: number, previous: number): void
+ (event: 'update:modelValue', value: number, unit?: string): void
+ /** Emitted once after a changed interaction is committed, with the unit typed after the value. */
+ (event: 'commit', value: number, previous: number, unit?: string): void
/** Emitted after restoring a cancelled or invalid interaction. */
(event: 'cancel'): void
/** Emitted when the inline editing state changes. */
diff --git a/packages/vue/src/primitives/TypographyControls/TypographyControlsRoot.vue b/packages/vue/src/primitives/TypographyControls/TypographyControlsRoot.vue
index 0157cb2a7..ecd8363c6 100644
--- a/packages/vue/src/primitives/TypographyControls/TypographyControlsRoot.vue
+++ b/packages/vue/src/primitives/TypographyControls/TypographyControlsRoot.vue
@@ -32,6 +32,7 @@ const actions = {
setParagraphSpacing: ctx.setParagraphSpacing,
updateProp: ctx.updateProp,
commitProp: ctx.commitProp,
+ cancelProp: ctx.cancelProp,
align: onAlignChange,
formatting: onFormattingChange,
toggleBold: ctx.toggleBold,
diff --git a/packages/vue/src/shared/input/resize.ts b/packages/vue/src/shared/input/resize.ts
index 634156667..010087469 100644
--- a/packages/vue/src/shared/input/resize.ts
+++ b/packages/vue/src/shared/input/resize.ts
@@ -91,6 +91,7 @@ function keptAspectRatio(d: DragResize, shiftKey: boolean, ctrlKey: boolean): nu
function resizeChanges(
d: DragResize,
+ type: SceneNode['type'],
cx: number,
cy: number,
shiftKey: boolean,
@@ -115,6 +116,7 @@ function resizeChanges(
...newRect,
...scaledGeometryChanges(
{
+ type,
vectorNetwork: d.origVectorNetwork,
fillGeometry: d.origFillGeometry,
strokeGeometry: d.origStrokeGeometry,
@@ -183,14 +185,13 @@ export function applyResize(
// 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, shiftKey, editor, ctrlKey)
- d.appliedRect = { ...newRect }
const node = editor.graph.getNode(d.nodeId)
- if (node) {
- d.origSizing ??= layerSizing(node)
- d.appliedSizing = draggedSizing(editor.graph, node, d.origSizing, d.origRect, newRect)
- Object.assign(changes, d.appliedSizing)
- }
+ if (!node) return
+ const { changes, newRect } = resizeChanges(d, node.type, cx, cy, shiftKey, editor, ctrlKey)
+ d.appliedRect = { ...newRect }
+ d.origSizing ??= layerSizing(node)
+ d.appliedSizing = draggedSizing(editor.graph, node, d.origSizing, d.origRect, newRect)
+ Object.assign(changes, d.appliedSizing)
markResized(d, newRect, editor)
if (d.origRect.width > 0 && d.origRect.height > 0) {
const reflow = reflowedPathTextChanges(
@@ -225,7 +226,7 @@ export function applyResize(
* be reactivity-wrapped, and storing proxies breaks structuredClone snapshots
* (delete/undo would throw DataCloneError).
*/
-function snapshotResizeFinal(node: SceneNode): Partial<SceneNode> {
+function snapshotResizeFinal(node: SceneNode, hadStrokeGeometry: boolean): Partial<SceneNode> {
const final: Partial<SceneNode> = {
x: node.x,
y: node.y,
@@ -234,11 +235,10 @@ function snapshotResizeFinal(node: SceneNode): Partial<SceneNode> {
}
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) {
+ // Path-text reflow and a resize that redraws a stroke at its weight legitimately EMPTY
+ // strokeGeometry — commit it so the pre-resize outlines don't resurrect. A node that had none
+ // keeps the length guard: a spurious strokeGeometry key would clear its raw Figma payload.
+ if (node.strokeGeometry.length > 0 || node.textPathBox || hadStrokeGeometry) {
final.strokeGeometry = copyGeometryPaths(node.strokeGeometry)
}
if (node.derivedTextGlyphs?.length) {
@@ -395,14 +395,14 @@ function commitResizeGeometry(d: DragResize, editor: Editor) {
const node = editor.graph.getNode(d.nodeId)
if (!node) return
if (!d.appliedRect || sameRect(d.appliedRect, d.origRect)) restoreEditedFields(d, editor)
- const finalChanges = snapshotResizeFinal(node)
+ const finalChanges = snapshotResizeFinal(node, d.origStrokeGeometry.length > 0)
if (d.origChildren) {
const finalChildren = new Map<string, Partial<SceneNode>>()
- for (const [childId] of d.origChildren) {
+ for (const [childId, original] of d.origChildren) {
const child = editor.graph.getNode(childId)
if (!child) continue
- finalChildren.set(childId, snapshotResizeFinal(child))
+ finalChildren.set(childId, snapshotResizeFinal(child, original.strokeGeometry.length > 0))
}
restoreResizePreview(d, editor)
// Resize is geometric — the raw Figma import payload (vectorData,
diff --git a/src/components/inputs/NumberField.vue b/src/components/inputs/NumberField.vue
index e7842f964..b96922098 100644
--- a/src/components/inputs/NumberField.vue
+++ b/src/components/inputs/NumberField.vue
@@ -26,6 +26,8 @@ export interface NumberFieldProps {
inheritBinding?: boolean
bound?: boolean
editPolicy?: NumberFieldEditPolicy
+ /** Units a typed value may end with; the commit reports the one typed. */
+ units?: readonly string[]
ui?: NumberFieldUI
}
@@ -70,6 +72,7 @@ const {
inheritBinding = true,
bound,
editPolicy,
+ units,
ui
} = defineProps<NumberFieldProps>()
const accessibleLabel = computed(() => {
@@ -79,9 +82,9 @@ const accessibleLabel = computed(() => {
const styles = computed(() => tv(theme)({ suffix: Boolean(slots.suffix) }))
const emit = defineEmits<{
- 'update:modelValue': [value: number]
+ 'update:modelValue': [value: number, unit?: string]
'editing-change': [editing: boolean]
- commit: [value: number, previous: number]
+ commit: [value: number, previous: number, unit?: string]
cancel: []
invalid: [expression: string, reason: NumberExpressionError]
'detach-request': [source: 'edit' | 'scrub' | 'step']
@@ -104,8 +107,9 @@ defineOptions({ inheritAttrs: false })
:inherit-binding="inheritBinding"
:bound="bound"
:edit-policy="editPolicy"
- @update:model-value="emit('update:modelValue', $event)"
- @commit="(val: number, prev: number) => emit('commit', val, prev)"
+ :units="units"
+ @update:model-value="(value: number, unit?: string) => emit('update:modelValue', value, unit)"
+ @commit="(val: number, prev: number, unit?: string) => emit('commit', val, prev, unit)"
@cancel="emit('cancel')"
@invalid="
(expression: string, reason: NumberExpressionError) => emit('invalid', expression, reason)
diff --git a/src/components/properties/TypographySection.vue b/src/components/properties/TypographySection.vue
index 75e2b55ab..1193d944e 100644
--- a/src/components/properties/TypographySection.vue
+++ b/src/components/properties/TypographySection.vue
@@ -169,6 +169,7 @@ function picked<T>(value: MixedValue<T>): T | '' {
:nodes="ctx.nodes.value"
@update="ctx.actions.updateProp('lineHeight', $event)"
@commit="(v, p) => ctx.actions.commitProp('lineHeight', v, p)"
+ @cancel="ctx.actions.cancelProp('lineHeight')"
/>
</PanelFieldGroup>
<PanelFieldGroup :label="panels.letterSpacing">
@@ -176,6 +177,7 @@ function picked<T>(value: MixedValue<T>): T | '' {
:nodes="ctx.nodes.value"
@update="ctx.actions.updateProp('letterSpacing', $event)"
@commit="(v, p) => ctx.actions.commitProp('letterSpacing', v, p)"
+ @cancel="ctx.actions.cancelProp('letterSpacing')"
/>
</PanelFieldGroup>
</PanelGrid>
diff --git a/src/components/properties/VariableNumberField.vue b/src/components/properties/VariableNumberField.vue
index e15670e68..ac7fba322 100644
--- a/src/components/properties/VariableNumberField.vue
+++ b/src/components/properties/VariableNumberField.vue
@@ -26,7 +26,8 @@ const {
nodeId,
nodeIds,
bindingPath,
- bindingPaths
+ bindingPaths,
+ units
} = defineProps<{
modelValue: number | symbol
min?: number
@@ -42,11 +43,13 @@ const {
nodeIds?: readonly string[]
bindingPath: NumberBindingPath
bindingPaths?: readonly NumberBindingPath[]
+ /** Units a typed value may end with; the commit reports the one typed. */
+ units?: readonly string[]
}>()
const emit = defineEmits<{
- 'update:modelValue': [value: number]
- commit: [value: number, previous: number]
+ 'update:modelValue': [value: number, unit?: string]
+ commit: [value: number, previous: number, unit?: string]
cancel: []
}>()
@@ -90,11 +93,14 @@ defineOptions({ inheritAttrs: false })
:min="min"
:max="max"
:step="step"
+ :units="units"
:ui="{ root: bindingStyles.root }"
:data-property="bindingPath"
:aria-label="accessibleLabel"
- @update:model-value="emit('update:modelValue', $event)"
- @commit="(value: number, previous: number) => emit('commit', value, previous)"
+ @update:model-value="(value: number, unit?: string) => emit('update:modelValue', value, unit)"
+ @commit="
+ (value: number, previous: number, unit?: string) => emit('commit', value, previous, unit)
+ "
@cancel="emit('cancel')"
>
<template v-if="$slots.icon" #icon>
diff --git a/src/components/properties/typography/LetterSpacingField.vue b/src/components/properties/typography/LetterSpacingField.vue
index 0642b83eb..a8753a0ff 100644
--- a/src/components/properties/typography/LetterSpacingField.vue
+++ b/src/components/properties/typography/LetterSpacingField.vue
@@ -4,13 +4,14 @@ import { useI18n } from '@open-pencil/vue/i18n'
import VariableNumberField from '@/components/properties/VariableNumberField.vue'
-import { useTextLength } from './useTextLength'
+import { TEXT_LENGTH_UNITS, useTextLength } from './useTextLength'
/** Every selected text layer; the field reads Mixed when their letter spacings differ. */
const { nodes } = defineProps<{ nodes: readonly SceneNode[] }>()
const emit = defineEmits<{
update: [value: TextLength]
commit: [value: TextLength, previous: TextLength]
+ cancel: []
}>()
const { panels } = useI18n()
const { value, suffix, length } = useTextLength(
@@ -18,6 +19,11 @@ const { value, suffix, length } = useTextLength(
'letterSpacing',
() => 0
)
+/** The panel commits what it previewed, so a typed unit is previewed first. */
+function commit(current: number, previous: number, unit?: string) {
+ if (unit) emit('update', length(current, unit))
+ emit('commit', length(current, unit), length(previous))
+}
</script>
<template>
@@ -27,9 +33,11 @@ const { value, suffix, length } = useTextLength(
:aria-label="panels.letterSpacing"
:node-id="nodes.at(0)?.id ?? ''"
:node-ids="nodes.map((node) => node.id)"
+ :units="TEXT_LENGTH_UNITS"
binding-path="letterSpacing"
- @update:model-value="emit('update', length($event))"
- @commit="(current, previous) => emit('commit', length(current), length(previous))"
+ @update:model-value="(value, unit) => emit('update', length(value, unit))"
+ @commit="commit"
+ @cancel="emit('cancel')"
>
<template #icon>
<icon-lucide-a-large-small class="size-3" />
diff --git a/src/components/properties/typography/LineHeightField.vue b/src/components/properties/typography/LineHeightField.vue
index d00a34f2e..959dbee47 100644
--- a/src/components/properties/typography/LineHeightField.vue
+++ b/src/components/properties/typography/LineHeightField.vue
@@ -12,13 +12,14 @@ import VariableNumberField from '@/components/properties/VariableNumberField.vue
import AppSelectContent from '@/components/ui/select/AppSelectContent.vue'
import AppSelectItem from '@/components/ui/select/AppSelectItem.vue'
-import { useTextLength } from './useTextLength'
+import { TEXT_LENGTH_UNITS, useTextLength } from './useTextLength'
/** Every selected text layer; the field reads Mixed when their line heights differ. */
const { nodes } = defineProps<{ nodes: readonly SceneNode[] }>()
const emit = defineEmits<{
update: [value: TextLength]
commit: [value: TextLength, previous: TextLength]
+ cancel: []
}>()
const editor = useEditor()
const { open: popupOpen, portalActive } = useRetainedPopup()
@@ -28,6 +29,11 @@ const isAutomatic = (node: SceneNode) => node.lineHeight == null && !node.boundV
const automaticPixels = (node: SceneNode) => Math.round((node.fontSize || 14) * 1.2)
const automatic = computed(() => nodes.length > 0 && nodes.every(isAutomatic))
const { value, suffix, length } = useTextLength(() => nodes, 'lineHeight', automaticPixels)
+/** The panel commits what it previewed, so a typed unit is previewed first. */
+function commit(current: number, previous: number, unit?: string) {
+ if (unit) emit('update', length(current, unit))
+ emit('commit', length(current, unit), length(previous))
+}
const nodeId = computed(() => nodes.at(0)?.id ?? '')
const nodeIds = computed(() => nodes.map((node) => node.id))
function setMode(mode: string) {
@@ -59,9 +65,11 @@ function setMode(mode: string) {
:min="0"
:node-id="nodeId"
:node-ids="nodeIds"
+ :units="TEXT_LENGTH_UNITS"
binding-path="lineHeight"
- @update:model-value="emit('update', length($event))"
- @commit="(current, previous) => emit('commit', length(current), length(previous))"
+ @update:model-value="(value, unit) => emit('update', length(value, unit))"
+ @commit="commit"
+ @cancel="emit('cancel')"
>
<template #icon><icon-lucide-baseline class="size-3" /></template>
<template v-if="automatic" #display
diff --git a/src/components/properties/typography/useTextLength.ts b/src/components/properties/typography/useTextLength.ts
index 0ff5a7e84..ba9758e3e 100644
--- a/src/components/properties/typography/useTextLength.ts
+++ b/src/components/properties/typography/useTextLength.ts
@@ -6,9 +6,16 @@ import { MIXED } from '@open-pencil/vue/controls/node-props'
type LengthField = 'lineHeight' | 'letterSpacing'
+/** What a typed unit switches the field to, as Figma's `150%` or `24px` does. */
+const TYPED_UNITS: Record<string, TextLength['unit']> = { '%': 'PERCENT', px: 'PIXELS' }
+
+/** The units a line height or letter spacing field reads after a typed value. */
+export const TEXT_LENGTH_UNITS = Object.keys(TYPED_UNITS)
+
/**
* A line height or letter spacing as the panel edits it: in the unit the layers share, pixels or
- * a percent of the font size, so an edit keeps that unit. Layers in other units read Mixed.
+ * a percent of the font size, so an edit keeps that unit unless it types another. Layers in other
+ * units read Mixed.
*/
export function useTextLength(
nodes: () => readonly SceneNode[],
@@ -30,6 +37,9 @@ export function useTextLength(
return first != null && values.every((current) => current === first) ? first : MIXED
})
const suffix = computed(() => (unit.value === 'PERCENT' ? '%' : 'px'))
- const length = (value: number): TextLength => ({ value, unit: unit.value })
+ const length = (value: number, typed?: string): TextLength => ({
+ value,
+ unit: (typed && TYPED_UNITS[typed.toLowerCase()]) || unit.value
+ })
return { unit, value, suffix, length }
}
diff --git a/tests/e2e/canvas/saved-glyph-visual.spec.ts-snapshots/typed-emoji-openpencil-darwin.png b/tests/e2e/canvas/saved-glyph-visual.spec.ts-snapshots/typed-emoji-openpencil-darwin.png
index e481276a5..caa2b14a3 100644
Binary files a/tests/e2e/canvas/saved-glyph-visual.spec.ts-snapshots/typed-emoji-openpencil-darwin.png and b/tests/e2e/canvas/saved-glyph-visual.spec.ts-snapshots/typed-emoji-openpencil-darwin.png differ
diff --git a/tests/e2e/canvas/saved-glyph-visual.spec.ts-snapshots/typed-keycap-openpencil-darwin.png b/tests/e2e/canvas/saved-glyph-visual.spec.ts-snapshots/typed-keycap-openpencil-darwin.png
index 99cdb8c51..1553c4b5a 100644
Binary files a/tests/e2e/canvas/saved-glyph-visual.spec.ts-snapshots/typed-keycap-openpencil-darwin.png and b/tests/e2e/canvas/saved-glyph-visual.spec.ts-snapshots/typed-keycap-openpencil-darwin.png differ
diff --git a/tests/e2e/canvas/vector/stroke-align-visual.spec.ts b/tests/e2e/canvas/vector/stroke-align-visual.spec.ts
new file mode 100644
index 000000000..08a6c9fa7
--- /dev/null
+++ b/tests/e2e/canvas/vector/stroke-align-visual.spec.ts
@@ -0,0 +1,14 @@
+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'
+import { strokeSceneDriver } from '#tests/helpers/canvas/strokes/driver'
+
+const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')
+const scene = strokeSceneDriver(() => editor.page, 'createVectorStrokeAlignScene')
+
+// Figma 126 strokes inside or outside a path as a centred stroke twice as wide, clipped; the pixels
+// are checked in packages/core/tests/canvas/strokes/vector-align.test.ts.
+test('a vector drawn from its path strokes on the side its alignment takes', async () => {
+ await scene.show()
+ await editor.canvas.waitForRender()
+ editor.canvas.assertNoErrors()
+ expect(await editor.canvas.screenshotCanvasRegion()).toMatchSnapshot('vector-stroke-align.png')
+})
diff --git a/tests/e2e/canvas/vector/stroke-align-visual.spec.ts-snapshots/vector-stroke-align-openpencil-darwin.png b/tests/e2e/canvas/vector/stroke-align-visual.spec.ts-snapshots/vector-stroke-align-openpencil-darwin.png
new file mode 100644
index 000000000..5e32f3b57
Binary files /dev/null and b/tests/e2e/canvas/vector/stroke-align-visual.spec.ts-snapshots/vector-stroke-align-openpencil-darwin.png differ
diff --git a/tests/e2e/properties/line-height.spec.ts b/tests/e2e/properties/line-height.spec.ts
index 31a2ce3e5..1da8d177c 100644
--- a/tests/e2e/properties/line-height.spec.ts
+++ b/tests/e2e/properties/line-height.spec.ts
@@ -59,3 +59,95 @@ test('automatic line height survives focus and can be restored with undo', async
await page.keyboard.press(process.platform === 'darwin' ? 'Meta+z' : 'Control+z')
await expect(field).toHaveAttribute('data-bound')
})
+
+test('a typed % or px switches the unit of line height and letter spacing', async ({ page }) => {
+ await page.setViewportSize({ width: 1280, height: 1200 })
+ await page.goto('/?test')
+ await new CanvasHelper(page).waitForInit()
+ const id = await page.evaluate(() => {
+ const e = window.openPencil?.getStore?.()
+ if (!e) throw new Error('No editor')
+ const id = e.createShape('TEXT', 100, 100, 240, 80)
+ e.updateNode(id, {
+ text: 'Units',
+ fontSize: 20,
+ lineHeight: { value: 24, unit: 'PIXELS' },
+ letterSpacing: { value: 0, unit: 'PIXELS' }
+ })
+ e.select([id])
+ return id
+ })
+ const read = (field: 'lineHeight' | 'letterSpacing') =>
+ page.evaluate(({ id, field }) => window.openPencil?.getStore?.().graph.getNode(id)?.[field], {
+ id,
+ field
+ })
+ const type = async (name: string, text: string) => {
+ const input = page.getByRole('spinbutton', { name, exact: true })
+ await input.focus()
+ await input.fill(text)
+ await input.press('Enter')
+ }
+
+ await type('Line height', '150%')
+ await expect.poll(() => read('lineHeight')).toEqual({ value: 150, unit: 'PERCENT' })
+ await expect(page.locator('[data-property="lineHeight"]')).toContainText('%')
+ await type('Line height', '30px')
+ await expect.poll(() => read('lineHeight')).toEqual({ value: 30, unit: 'PIXELS' })
+ // Stepping a typed value keeps the unit typed after it.
+ const lineHeight = page.getByRole('spinbutton', { name: 'Line height', exact: true })
+ await lineHeight.focus()
+ await lineHeight.fill('150%')
+ await lineHeight.press('ArrowUp')
+ // The canvas previews the stepped value in the unit typed, before Enter commits it.
+ await expect.poll(() => read('lineHeight')).toEqual({ value: 151, unit: 'PERCENT' })
+ await lineHeight.press('Enter')
+ await expect.poll(() => read('lineHeight')).toEqual({ value: 151, unit: 'PERCENT' })
+ await type('Line height', '30px')
+ await expect.poll(() => read('lineHeight')).toEqual({ value: 30, unit: 'PIXELS' })
+ await type('Letter spacing', '2%')
+ await expect.poll(() => read('letterSpacing')).toEqual({ value: 2, unit: 'PERCENT' })
+
+ await page.getByRole('heading', { name: 'Typography', exact: true }).click()
+ await page.keyboard.press(process.platform === 'darwin' ? 'Meta+z' : 'Control+z')
+ await expect.poll(() => read('letterSpacing')).toEqual({ value: 0, unit: 'PIXELS' })
+ await page.keyboard.press(process.platform === 'darwin' ? 'Meta+z' : 'Control+z')
+ await expect.poll(() => read('lineHeight')).toEqual({ value: 151, unit: 'PERCENT' })
+
+ // A value stepped below zero stays that value, not an expression subtracting from the start.
+ await type('Letter spacing', '2px')
+ await expect.poll(() => read('letterSpacing')).toEqual({ value: 2, unit: 'PIXELS' })
+ const letterSpacing = page.getByRole('spinbutton', { name: 'Letter spacing', exact: true })
+ await letterSpacing.focus()
+ await letterSpacing.fill('0px')
+ await letterSpacing.press('ArrowDown')
+ await letterSpacing.press('ArrowDown')
+ await letterSpacing.press('Enter')
+ await expect.poll(() => read('letterSpacing')).toEqual({ value: -2, unit: 'PIXELS' })
+
+ // The value a field opens with is that value, not an expression: Enter keeps it, ArrowUp steps up.
+ await letterSpacing.blur()
+ await letterSpacing.focus()
+ await letterSpacing.press('Enter')
+ await expect.poll(() => read('letterSpacing')).toEqual({ value: -2, unit: 'PIXELS' })
+ await letterSpacing.focus()
+ await letterSpacing.press('ArrowUp')
+ await letterSpacing.press('Enter')
+ await expect.poll(() => read('letterSpacing')).toEqual({ value: -1, unit: 'PIXELS' })
+
+ // Escape puts back the value and unit the layer had, whatever unit the preview showed.
+ await letterSpacing.focus()
+ await letterSpacing.fill('3%')
+ await letterSpacing.press('ArrowUp')
+ await expect.poll(() => read('letterSpacing')).toEqual({ value: 4, unit: 'PERCENT' })
+ await letterSpacing.press('Escape')
+ await expect.poll(() => read('letterSpacing')).toEqual({ value: -1, unit: 'PIXELS' })
+
+ // A change of unit alone, with the number kept, is a commit and an undo step of its own.
+ await expect.poll(() => read('lineHeight')).toEqual({ value: 151, unit: 'PERCENT' })
+ await type('Line height', '151px')
+ await expect.poll(() => read('lineHeight')).toEqual({ value: 151, unit: 'PIXELS' })
+ await page.getByRole('heading', { name: 'Typography', exact: true }).click()
+ await page.keyboard.press(process.platform === 'darwin' ? 'Meta+z' : 'Control+z')
+ await expect.poll(() => read('lineHeight')).toEqual({ value: 151, unit: 'PERCENT' })
+})
diff --git a/tests/e2e/properties/typography-panel.spec.ts-snapshots/typography-groups-dark-openpencil-darwin.png b/tests/e2e/properties/typography-panel.spec.ts-snapshots/typography-groups-dark-openpencil-darwin.png
index e430814f9..61a366469 100644
Binary files a/tests/e2e/properties/typography-panel.spec.ts-snapshots/typography-groups-dark-openpencil-darwin.png and b/tests/e2e/properties/typography-panel.spec.ts-snapshots/typography-groups-dark-openpencil-darwin.png differ
diff --git a/tests/e2e/properties/typography-panel.spec.ts-snapshots/typography-groups-light-openpencil-darwin.png b/tests/e2e/properties/typography-panel.spec.ts-snapshots/typography-groups-light-openpencil-darwin.png
index d35c5988a..823197ebe 100644
Binary files a/tests/e2e/properties/typography-panel.spec.ts-snapshots/typography-groups-light-openpencil-darwin.png and b/tests/e2e/properties/typography-panel.spec.ts-snapshots/typography-groups-light-openpencil-darwin.png differ
diff --git a/tests/e2e/text/formatting.spec.ts-snapshots/typography-panel-openpencil-darwin.png b/tests/e2e/text/formatting.spec.ts-snapshots/typography-panel-openpencil-darwin.png
index 88675c05f..e2dfca9c0 100644
Binary files a/tests/e2e/text/formatting.spec.ts-snapshots/typography-panel-openpencil-darwin.png and b/tests/e2e/text/formatting.spec.ts-snapshots/typography-panel-openpencil-darwin.png differ
diff --git a/tests/engine/geometry/clip-polygon.test.ts b/tests/engine/geometry/clip-polygon.test.ts
index b16def3e7..418f00f12 100644
--- a/tests/engine/geometry/clip-polygon.test.ts
+++ b/tests/engine/geometry/clip-polygon.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import { clipBoundsToPolygon, clipPolygon } from '@open-pencil/scene-graph/geometry'
+import { clipBoundsToPolygon, clipPolygon } from '@open-pencil/scene-graph/clipping'
import type { Vector } from '@open-pencil/scene-graph/primitives'
describe('clipPolygon', () => {
diff --git a/tests/engine/vue/controls/constraints.test.ts b/tests/engine/vue/controls/constraints.test.ts
index 790f497d7..04fa1c7fa 100644
--- a/tests/engine/vue/controls/constraints.test.ts
+++ b/tests/engine/vue/controls/constraints.test.ts
@@ -19,6 +19,7 @@ import type { DragResize } from '#vue/shared/input/types'
import { createRect, firstPageId, makeSceneGraph } from '#tests/helpers/scene'
function original(node: {
+ type: ResizeSnapshot['type']
x: number
y: number
width: number
@@ -26,6 +27,7 @@ function original(node: {
vectorNetwork: ResizeSnapshot['vectorNetwork']
}): ResizeSnapshot {
return {
+ type: node.type,
x: node.x,
y: node.y,
width: node.width,
@@ -69,6 +71,7 @@ describe('constraint control model', () => {
describe('constraint resize geometry', () => {
const child: ResizeSnapshot = {
+ type: 'RECTANGLE',
x: 20,
y: 30,
width: 40,
diff --git a/tests/engine/vue/input/resize/geometry.test.ts b/tests/engine/vue/input/resize/geometry.test.ts
index 221fc1db6..a8db3e10d 100644
--- a/tests/engine/vue/input/resize/geometry.test.ts
+++ b/tests/engine/vue/input/resize/geometry.test.ts
@@ -1,8 +1,8 @@
import { describe, expect, test } from 'bun:test'
import { createEditor } from '@open-pencil/core'
-import type { Fill, GeometryPath, SceneNode, VectorNetwork } from '@open-pencil/scene-graph'
-import { copyGeometryPaths } from '@open-pencil/scene-graph/copy'
+import type { Fill, GeometryPath, SceneNode, Stroke, VectorNetwork } from '@open-pencil/scene-graph'
+import { copyGeometryPaths, copyStrokes } from '@open-pencil/scene-graph/copy'
import { collectResizeDescendants } from '@open-pencil/scene-graph/resize'
import { cloneVectorNetwork } from '@open-pencil/scene-graph/vector-network'
@@ -35,6 +35,18 @@ const NETWORK: VectorNetwork = {
regions: [{ windingRule: 'NONZERO', loops: [[0, 1, 2, 3]] }]
}
+const STROKE: Stroke = {
+ type: 'SOLID',
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ weight: 4,
+ opacity: 1,
+ visible: true,
+ align: 'CENTER',
+ cap: 'NONE',
+ join: 'MITER',
+ dashPattern: []
+}
+
function movePath(x: number, y: number, fills?: Fill[]): GeometryPath {
const commandsBlob = new Uint8Array(9)
const view = new DataView(commandsBlob.buffer)
@@ -75,7 +87,7 @@ function dragFor(node: SceneNode, origChildren: DragResize['origChildren'] = nul
origFillGeometry: geometry.fills,
origStrokeGeometry: geometry.strokes,
origDerivedTextGlyphs: null,
- origStrokes: [],
+ origStrokes: copyStrokes(node.strokes),
origTextPathData: null,
origTextPathBox: null,
lockedAspectRatio: null,
@@ -83,12 +95,17 @@ function dragFor(node: SceneNode, origChildren: DragResize['origChildren'] = nul
}
}
+/**
+ * The vector at `size`. Resized, its saved stroke outline is gone, so the stroke draws from the
+ * scaled path at its own weight; undo brings the outline back.
+ */
function expectGeometry(node: SceneNode, size: number) {
expect(node.width).toBe(size)
expect(node.height).toBe(size)
expect(node.vectorNetwork?.vertices[2]).toMatchObject({ x: size, y: size })
expect(pathPoint(node.fillGeometry[0])).toEqual([size, size])
- expect(pathPoint(node.strokeGeometry[0])).toEqual([size / 2, size / 2])
+ if (size === 10) expect(pathPoint(node.strokeGeometry[0])).toEqual([5, 5])
+ else expect(node.strokeGeometry).toEqual([])
expect(node.fillGeometry[0]?.fills?.[0]?.color.r).toBe(1)
}
@@ -141,4 +158,37 @@ describe('vector resize geometry', () => {
editor.undo.redo()
expectGeometry(getNodeOrThrow(editor.graph, vector.id), 20)
})
+
+ // Figma keeps the weight through a resize; only its Scale tool (K) changes it.
+ test('keeps the stroke weight of a resized vector and of one in a resized group', () => {
+ const editor = createEditor()
+ const page = editor.graph.getPages()[0]
+ const vector = editor.graph.createNode('VECTOR', page.id, {
+ width: 10,
+ height: 10,
+ vectorNetwork: cloneVectorNetwork(NETWORK),
+ strokes: [STROKE]
+ })
+ const group = editor.graph.createNode('GROUP', page.id, { width: 10, height: 10 })
+ const grouped = editor.graph.createNode('VECTOR', group.id, {
+ width: 10,
+ height: 10,
+ vectorNetwork: cloneVectorNetwork(NETWORK),
+ strokes: [STROKE]
+ })
+
+ for (const drag of [
+ dragFor(vector),
+ dragFor(group, collectResizeDescendants(editor.graph, group.id))
+ ]) {
+ applyResize(drag, 20, 40, false, editor)
+ commitResizePreview(drag, editor)
+ }
+
+ for (const id of [vector.id, grouped.id]) {
+ const node = getNodeOrThrow(editor.graph, id)
+ expect([node.width, node.height]).toEqual([20, 40])
+ expect(node.strokes[0]?.weight).toBe(4)
+ }
+ })
})
diff --git a/tests/engine/vue/input/resize/path-text/basic.test.ts b/tests/engine/vue/input/resize/path-text/basic.test.ts
index 7c3e449cc..0e1baadea 100644
--- a/tests/engine/vue/input/resize/path-text/basic.test.ts
+++ b/tests/engine/vue/input/resize/path-text/basic.test.ts
@@ -104,6 +104,7 @@ describe('resize scales path-text stroke geometry and glyphs', () => {
} as Editor
const origChild: ResizeSnapshot = {
+ type: 'TEXT',
x: text.x,
y: text.y,
width: text.width,
@@ -193,6 +194,7 @@ describe('resize scales path-text stroke geometry and glyphs', () => {
} as Editor
const origChild: ResizeSnapshot = {
+ type: 'TEXT',
x: text.x,
y: text.y,
width: text.width,
diff --git a/tests/engine/vue/input/resize/path-text/reflow.test.ts b/tests/engine/vue/input/resize/path-text/reflow.test.ts
index e341d1e5a..2ed46979e 100644
--- a/tests/engine/vue/input/resize/path-text/reflow.test.ts
+++ b/tests/engine/vue/input/resize/path-text/reflow.test.ts
@@ -149,6 +149,7 @@ describe('group resize reflows path text instead of squashing it', () => {
} as Editor
const origChild: ResizeSnapshot = {
+ type: 'TEXT',
x: 0,
y: 0,
width: 256,
diff --git a/tests/helpers/canvas/strokes/scene.ts b/tests/helpers/canvas/strokes/scene.ts
index 6d90f9382..e28a2768a 100644
--- a/tests/helpers/canvas/strokes/scene.ts
+++ b/tests/helpers/canvas/strokes/scene.ts
@@ -173,3 +173,52 @@ export function createGradientLinesScene(graph: SceneGraph, pageId: string): voi
})
}
}
+
+/**
+ * Translucent squares drawn from their paths with a centred, an inside, and an outside stroke, as
+ * a vector without a saved stroke outline draws, such as one drawn or resized on the canvas.
+ */
+export function createVectorStrokeAlignScene(graph: SceneGraph, pageId: string): void {
+ const side = 80
+ const corner = { x: 0, y: 0 }
+ for (const [column, align] of (['CENTER', 'INSIDE', 'OUTSIDE'] as const).entries()) {
+ graph.createNode('VECTOR', pageId, {
+ name: align,
+ x: 60 + column * 160,
+ y: 60,
+ width: side,
+ height: side,
+ vectorNetwork: {
+ vertices: [
+ { x: 0, y: 0 },
+ { x: side, y: 0 },
+ { x: side, y: side },
+ { x: 0, y: side }
+ ],
+ segments: [0, 1, 2, 3].map((start) => ({
+ start,
+ end: (start + 1) % 4,
+ tangentStart: corner,
+ tangentEnd: corner
+ })),
+ regions: [{ windingRule: 'NONZERO', loops: [[0, 1, 2, 3]] }]
+ },
+ fills: [
+ { type: 'SOLID', color: { r: 0.86, g: 0.91, b: 0.98, a: 1 }, opacity: 1, visible: true }
+ ],
+ strokes: [
+ {
+ type: 'SOLID',
+ color: { r: 0.1, g: 0.1, b: 0.2, a: 1 },
+ weight: 12,
+ opacity: 0.6,
+ visible: true,
+ align,
+ cap: 'NONE',
+ join: 'MITER',
+ dashPattern: []
+ }
+ ]
+ })
+ }
+}