Skip to content

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

fix(canvas): dash rectangles as Figma does and shadow turned children without a layer (#1306)

Danila Poyarkovba9c0392fdb3
diff --git a/changes/1306/fixed.md b/changes/1306/fixed.md
new file mode 100644
index 000000000..c0dc9ee4f
--- /dev/null
+++ b/changes/1306/fixed.md
@@ -0,0 +1 @@
+- Dashed strokes on rectangles and frames are laid out as in Figma: each straight side and each rounded corner holds whole dashes with half a dash at each end, and sharp corners are filled, so dashes no longer start wherever the outline does or run straight past rounded corners.
diff --git a/changes/1306/performance.md b/changes/1306/performance.md
new file mode 100644
index 000000000..4dfeeb4cd
--- /dev/null
+++ b/changes/1306/performance.md
@@ -0,0 +1 @@
+- Shadows of a frame or group whose only content is one rotated or flipped layer render about four times faster.
diff --git a/packages/core/src/canvas/scene.ts b/packages/core/src/canvas/scene.ts
index dbcf19445..d476e43ad 100644
--- a/packages/core/src/canvas/scene.ts
+++ b/packages/core/src/canvas/scene.ts
@@ -50,6 +50,7 @@ import {
getStrokeJoinEntity,
normalizeDashPattern
} from './strokes'
+import { drawDashedRectStroke, strokeDashesByOutline, strokeSideWeights } from './strokes/sides'
import { textVerticalOffset, withTextParagraph } from './text'
import { drawTextLayout } from './text/decorations'
import {
@@ -755,6 +756,12 @@ function drawRegularStroke(
if (node.independentStrokeWeights && r.isRectangularType(node.type)) {
r.drawIndividualSideStrokes(canvas, node, stroke)
+ } else if (
+ dash.length > 0 &&
+ r.isRectangularType(node.type) &&
+ strokeDashesByOutline(node, stroke)
+ ) {
+ drawDashedRectStroke(r, canvas, node, stroke, strokeSideWeights(node, stroke), dash)
} else {
r.drawStrokeWithAlign(canvas, node, rect, hasRadius, stroke.align)
}
diff --git a/packages/core/src/canvas/shadows.ts b/packages/core/src/canvas/shadows.ts
index b9ff96a17..d7bf2a661 100644
--- a/packages/core/src/canvas/shadows.ts
+++ b/packages/core/src/canvas/shadows.ts
@@ -1,6 +1,9 @@
import type { BlendMode, Canvas, ImageFilter } from 'canvaskit-wasm'
import type { Effect, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import Matrix from '@open-pencil/scene-graph/matrix'
+
+import { nodeOrientationMatrix } from '#core/geometry'
import { figmaBlendModeToSkia } from './blend'
import { blurSigma, renderNoiseEffects } from './effects'
@@ -158,12 +161,26 @@ function drawOwnShapeDropShadow(
return true
}
-/** Draws a shadow cast by `child`, in its parent's coordinates. */
-function withChildCoordinates<T>(canvas: Canvas, child: SceneNode, draw: () => T): T {
+/**
+ * Draws a shadow cast by `child`, in its parent's coordinates. The parent's effect is drawn in the
+ * child's own space, so its offset is turned back by the child's rotation and flips; blur and
+ * spread are the same in every direction.
+ */
+function withChildCoordinates<T>(
+ canvas: Canvas,
+ child: SceneNode,
+ effect: Effect,
+ draw: (local: Effect) => T
+): T {
+ const orientation = nodeOrientationMatrix(child)
+ const inverse = Matrix.invert(orientation) ?? Matrix.identity()
+ const origin = Matrix.mapPoint(inverse, { x: 0, y: 0 })
+ const offset = Matrix.mapPoint(inverse, effect.offset)
canvas.save()
try {
canvas.translate(child.x, child.y)
- return draw()
+ canvas.concat(orientation)
+ return draw({ ...effect, offset: { x: offset.x - origin.x, y: offset.y - origin.y } })
} finally {
canvas.restore()
}
@@ -184,8 +201,8 @@ function renderDropShadow(
effect.showShadowBehindNode === false && !paintsOverKnockout(graph, node, includeChildren)
const sole = includeChildren ? soleShadowChild(graph, node) : null
const drawnAlone = sole
- ? withChildCoordinates(canvas, sole, () =>
- drawOwnShapeDropShadow(r, canvas, sole, effect, spread, blendMode, knockout)
+ ? withChildCoordinates(canvas, sole, effect, (local) =>
+ drawOwnShapeDropShadow(r, canvas, sole, local, spread, blendMode, knockout)
)
: !includeChildren &&
drawOwnShapeDropShadow(r, canvas, node, effect, spread, blendMode, knockout)
@@ -300,13 +317,13 @@ function renderInnerShadow(
if (!includeChildren && !paintsCastShadow(node)) return
const sole = includeChildren ? soleShadowChild(graph, node) : null
if (sole && castsFromOwnShape(sole)) {
- withChildCoordinates(canvas, sole, () =>
+ withChildCoordinates(canvas, sole, effect, (local) =>
drawShapeInnerShadow(
r,
canvas,
sole,
r.ck.LTRBRect(0, 0, sole.width, sole.height),
- effect,
+ local,
nodeHasRadius(sole)
)
)
diff --git a/packages/core/src/canvas/shadows/silhouette.ts b/packages/core/src/canvas/shadows/silhouette.ts
index 158793440..225085c05 100644
--- a/packages/core/src/canvas/shadows/silhouette.ts
+++ b/packages/core/src/canvas/shadows/silhouette.ts
@@ -349,7 +349,7 @@ export function shadowIncludesChildren(graph: SceneGraph, node: SceneNode): bool
/**
* The one child a container's shadows come from when the container paints nothing itself and
- * draws only that child, unturned, so the shadow is that child's own; null otherwise.
+ * draws only that child, so the shadow is that child's own, turned with it; null otherwise.
*/
export function soleShadowChild(graph: SceneGraph, node: SceneNode): SceneNode | null {
if (!isLayerContainer(node) || paintsCastShadow(node) || clipsChildren(node)) return null
@@ -361,7 +361,6 @@ export function soleShadowChild(graph: SceneGraph, node: SceneNode): SceneNode |
sole = child
}
if (!sole) return null
- if (sole.rotation !== 0 || sole.flipX || sole.flipY) return null
if (isLayerContainer(sole) && shadowIncludesChildren(graph, sole)) return null
return sole
}
diff --git a/packages/core/src/canvas/strokes/sides.ts b/packages/core/src/canvas/strokes/sides.ts
index 8cbb738e0..31f203315 100644
--- a/packages/core/src/canvas/strokes/sides.ts
+++ b/packages/core/src/canvas/strokes/sides.ts
@@ -1,10 +1,29 @@
-import type { Canvas, Path } from 'canvaskit-wasm'
+import type { Canvas } from 'canvaskit-wasm'
import type { SceneNode, Stroke } from '@open-pencil/scene-graph'
import type { SkiaRenderer } from '#core/canvas/renderer'
+import { nodeHasSmoothCorners } from '#core/canvas/shapes'
import { normalizeDashPattern } from '#core/canvas/strokes'
+/** Arc points per wedge: a chord across at most this many degrees stays clear of the ring. */
+const WEDGE_STEP = 30
+
+/** A rectangle's stroke weights, side by side: top, right, bottom, left. */
+export type SideWeights = readonly [number, number, number, number]
+
+/** The weight of each side of `node` under `stroke`, its own when its sides have their own. */
+export function strokeSideWeights(node: SceneNode, stroke: Stroke): SideWeights {
+ if (!node.independentStrokeWeights)
+ return [stroke.weight, stroke.weight, stroke.weight, stroke.weight]
+ return [
+ node.borderTopWeight,
+ node.borderRightWeight,
+ node.borderBottomWeight,
+ node.borderLeftWeight
+ ]
+}
+
/** The share of a stroke's weight that lies outside the shape it outlines. */
export function strokeAlignShare(align: Stroke['align']): number {
if (align === 'OUTSIDE') return 1
@@ -24,20 +43,21 @@ function cornerRadii(node: SceneNode): [number, number, number, number] {
* rectangles in CanvasKit's layout. Figma 126 strokes them as one ring: each inner corner
* shrinks by the width of its own side on each axis, and each outer corner is a circle grown by
* the narrower of its two sides, a side without a stroke not counting. `grow` pushes the outer
- * edge out and the inner edge in, as a shadow's spread grows a ring.
+ * edge out and the inner edge in, as a shadow's spread grows a ring. `weights` defaults to the
+ * node's own sides.
*/
export function sideStrokeRRects(
node: SceneNode,
align: Stroke['align'],
- grow = 0
-): { outer: Float32Array; inner: Float32Array | null } {
- const share = strokeAlignShare(align)
- const weights = [
+ grow = 0,
+ weights: SideWeights = [
node.borderTopWeight,
node.borderRightWeight,
node.borderBottomWeight,
node.borderLeftWeight
]
+): { outer: Float32Array; inner: Float32Array | null } {
+ const share = strokeAlignShare(align)
const [top, right, bottom, left] = weights.map((weight) => weight * share + grow)
const [topIn, rightIn, bottomIn, leftIn] = weights.map((weight) => weight * (1 - share) + grow)
const [tWeight, rWeight, bWeight, lWeight] = weights
@@ -86,27 +106,24 @@ export function sideStrokeRRects(
return { outer, inner }
}
-/** Strokes a frame whose sides have their own weights, as one ring like Figma, or side by side when dashed. */
+/** Strokes a frame whose sides have their own weights, as one ring like Figma, dashed or not. */
export function drawIndividualSideStrokes(
r: SkiaRenderer,
canvas: Canvas,
node: SceneNode,
stroke: Stroke
): void {
- const dashed = stroke.dashPattern && stroke.dashPattern.length > 0
- if (dashed && cornerRadii(node).some((radius) => radius > 0)) {
+ const pattern = normalizeDashPattern(stroke.dashPattern)
+ if (pattern.length > 0 && hasFlatDashes(node, stroke)) {
+ drawDashedRectStroke(r, canvas, node, stroke, strokeSideWeights(node, stroke), pattern)
+ return
+ }
+ if (pattern.length > 0) {
drawDashedSideLines(r, canvas, node, stroke.align)
return
}
r.strokePaint.setStyle(r.ck.PaintStyle.Fill)
try {
- if (dashed) {
- r.strokePaint.setPathEffect(null)
- const path = dashedSidesPath(r, node, stroke.align, normalizeDashPattern(stroke.dashPattern))
- canvas.drawPath(path, r.strokePaint)
- path.delete()
- return
- }
const { outer, inner } = sideStrokeRRects(node, stroke.align)
if (inner) canvas.drawDRRect(outer, inner, r.strokePaint)
else canvas.drawRRect(outer, r.strokePaint)
@@ -135,50 +152,219 @@ export function sideDashSpans(length: number, pattern: readonly number[]): Array
return spans
}
+/** Dashes with flat ends on corners without smoothing, which the layout below draws. */
+function hasFlatDashes(node: SceneNode, stroke: Stroke): boolean {
+ return !nodeHasSmoothCorners(node) && (stroke.cap ?? node.strokeCap) === 'NONE'
+}
+
+/**
+ * Whether Figma's dash layout below applies: a rectangle without smoothed corners whose
+ * dashes have flat ends, and on sharp corners a mitered join, which the corner squares are.
+ */
+export function strokeDashesByOutline(node: SceneNode, stroke: Stroke): boolean {
+ if (!hasFlatDashes(node, stroke)) return false
+ const rounded = fittedCornerRadii(node).some((radius) => radius > 0)
+ return rounded || (stroke.join ?? node.strokeJoin) === 'MITER'
+}
+
/**
- * A dashed stroke with sides of their own weights on sharp corners, as Figma 126 draws it: each
- * side dashed on its own, and a square filling each corner between two stroked sides.
+ * Draws a dashed stroke on a rectangle as Figma 126 does. The stroke is one ring, like an
+ * undashed one, and each part of the outline is dashed on its own: every straight side between
+ * its corners and every corner arc holds a whole number of periods, rounded to the nearest, with
+ * half a dash at each end. Arcs are measured on the shape's edge and cut through the corner's
+ * centre, and a sharp corner is filled when both of its sides are stroked.
*/
-function dashedSidesPath(
+export function drawDashedRectStroke(
r: SkiaRenderer,
+ canvas: Canvas,
node: SceneNode,
- align: Stroke['align'],
+ stroke: Stroke,
+ weights: SideWeights,
pattern: readonly number[]
-): Path {
+): void {
+ // Skia draws a stroke of width 0 as a hairline, so a ring without weight draws nothing.
+ if (weights.every((weight) => weight <= 0)) return
+ const dashed: DashedRect = {
+ node,
+ align: stroke.align,
+ weights,
+ pattern,
+ radii: fittedCornerRadii(node)
+ }
+ const inset = weights[0] * (1 - strokeAlignShare(stroke.align))
+ const even = weights.every((weight) => weight === weights[0])
+ r.strokePaint.setPathEffect(null)
+ drawDashRects(r, canvas, dashed)
+ if (even && dashed.radii.every((radius) => radius === 0 || radius >= inset)) {
+ drawDashedArcs(r, canvas, dashed)
+ } else {
+ drawClippedCornerDashes(r, canvas, dashed)
+ }
+}
+
+/** A dashed rectangle stroke: the node, its alignment and side weights, and the corners Skia draws. */
+interface DashedRect {
+ node: SceneNode
+ align: Stroke['align']
+ weights: SideWeights
+ pattern: readonly number[]
+ radii: [number, number, number, number]
+}
+
+/**
+ * The dashes along the straight sides, and the squares of sharp corners between stroked sides,
+ * filled as one path so a translucent stroke does not darken where they meet.
+ */
+function drawDashRects(r: SkiaRenderer, canvas: Canvas, dashed: DashedRect): void {
+ const { node, align, weights, pattern } = dashed
+ const [tl, tr, br, bl] = dashed.radii
const share = strokeAlignShare(align)
const w = node.width
const h = node.height
- const [top, right, bottom, left] = [
- node.borderTopWeight,
- node.borderRightWeight,
- node.borderBottomWeight,
- node.borderLeftWeight
- ]
+ const [top, right, bottom, left] = weights
+ const out = (weight: number) => weight * share
+ const into = (weight: number) => weight * (1 - share)
const builder = new r.ck.PathBuilder()
const rect = (l: number, t: number, rr: number, b: number) =>
builder.addRect(r.ck.LTRBRect(l, t, rr, b))
- if (top > 0)
- for (const [s, e] of sideDashSpans(w, pattern)) rect(s, -top * share, e, top * (1 - share))
- if (bottom > 0) {
- for (const [s, e] of sideDashSpans(w, pattern)) {
- rect(s, h - bottom * (1 - share), e, h + bottom * share)
+ // Each side: its weight, the length between its corners, and the rectangle of one dash on it.
+ const sides: Array<[number, number, (s: number, e: number) => void]> = [
+ [top, w - tl - tr, (s, e) => rect(tl + s, -out(top), tl + e, into(top))],
+ [bottom, w - bl - br, (s, e) => rect(bl + s, h - into(bottom), bl + e, h + out(bottom))],
+ [left, h - tl - bl, (s, e) => rect(-out(left), tl + s, into(left), tl + e)],
+ [right, h - tr - br, (s, e) => rect(w - into(right), tr + s, w + out(right), tr + e)]
+ ]
+ for (const [weight, length, dash] of sides) {
+ if (weight > 0) for (const [s, e] of sideDashSpans(length, pattern)) dash(s, e)
+ }
+ // Each sharp corner between two stroked sides: its square, outside the shape.
+ const corners: Array<[number, number, number, () => void]> = [
+ [tl, top, left, () => rect(-out(left), -out(top), 0, 0)],
+ [tr, top, right, () => rect(w, -out(top), w + out(right), 0)],
+ [br, bottom, right, () => rect(w, h, w + out(right), h + out(bottom))],
+ [bl, bottom, left, () => rect(-out(left), h, 0, h + out(bottom))]
+ ]
+ for (const [radius, a, b, square] of corners) if (radius === 0 && a > 0 && b > 0) square()
+ const path = builder.detachAndDelete()
+ // An outer corner grown by its narrower side starts curving before the shape's corner does.
+ const rounded = tl > 0 || tr > 0 || br > 0 || bl > 0
+ r.strokePaint.setStyle(r.ck.PaintStyle.Fill)
+ canvas.save()
+ try {
+ if (rounded) {
+ const { outer } = sideStrokeRRects(node, align, 0, weights)
+ canvas.clipRRect(outer, r.ck.ClipOp.Intersect, true)
+ }
+ canvas.drawPath(path, r.strokePaint)
+ } finally {
+ canvas.restore()
+ r.strokePaint.setStyle(r.ck.PaintStyle.Stroke)
+ path.delete()
+ }
+}
+
+/**
+ * The dashes around rounded corners of a stroke with one weight, as arcs with flat ends, which
+ * Skia cuts through the arc's centre as Figma does.
+ */
+function drawDashedArcs(r: SkiaRenderer, canvas: Canvas, dashed: DashedRect): void {
+ const { node, align, pattern } = dashed
+ const [weight] = dashed.weights
+ const [tl, tr, br, bl] = dashed.radii
+ const { width: w, height: h } = node
+ // The stroke's centre line runs this far outside the shape's edge.
+ const shift = weight * (strokeAlignShare(align) - 0.5)
+ r.strokePaint.setStrokeWidth(weight)
+ r.strokePaint.setStrokeCap(r.ck.StrokeCap.Butt)
+ const corner = (radius: number, cx: number, cy: number, startAngle: number) => {
+ if (radius <= 0) return
+ const arc = (Math.PI / 2) * radius
+ const line = radius + shift
+ const oval = r.ck.LTRBRect(cx - line, cy - line, cx + line, cy + line)
+ for (const [s, e] of sideDashSpans(arc, pattern)) {
+ canvas.drawArc(oval, startAngle + (s / arc) * 90, ((e - s) / arc) * 90, false, r.strokePaint)
}
}
- if (left > 0)
- for (const [s, e] of sideDashSpans(h, pattern)) rect(-left * share, s, left * (1 - share), e)
- if (right > 0) {
- for (const [s, e] of sideDashSpans(h, pattern)) {
- rect(w - right * (1 - share), s, w + right * share, e)
+ corner(tl, tl, tl, 180)
+ corner(tr, w - tr, tr, 270)
+ corner(br, w - br, h - br, 0)
+ corner(bl, bl, h - bl, 90)
+}
+
+/**
+ * The dashes around rounded corners of any other ring, as the ring clipped to each corner's box
+ * and to a wedge from the corner's centre for every dash along its arc.
+ */
+function drawClippedCornerDashes(r: SkiaRenderer, canvas: Canvas, dashed: DashedRect): void {
+ const { node, align, weights, pattern, radii } = dashed
+ const { width: w, height: h } = node
+ const share = strokeAlignShare(align)
+ const [top, right, bottom, left] = weights.map((weight) => weight * share)
+ const [tl, tr, br, bl] = radii
+ const { outer, inner } = sideStrokeRRects(node, align, 0, weights)
+ r.strokePaint.setStyle(r.ck.PaintStyle.Fill)
+ const corner = (
+ radius: number,
+ cx: number,
+ cy: number,
+ startAngle: number,
+ box: Float32Array
+ ) => {
+ if (radius <= 0) return
+ // Far enough that a chord across a wedge clears the corner's whole box.
+ const far = 2 * (radius + Math.max(top, right, bottom, left)) + 2
+ const builder = new r.ck.PathBuilder()
+ const arc = (Math.PI / 2) * radius
+ for (const [s, e] of sideDashSpans(arc, pattern)) {
+ const from = startAngle + (s / arc) * 90
+ const to = startAngle + (e / arc) * 90
+ const steps = Math.max(1, Math.ceil((to - from) / WEDGE_STEP))
+ const points = [cx, cy]
+ for (let step = 0; step <= steps; step++) {
+ const angle = ((from + ((to - from) * step) / steps) * Math.PI) / 180
+ points.push(cx + far * Math.cos(angle), cy + far * Math.sin(angle))
+ }
+ builder.addPolygon(points, true)
+ }
+ const wedges = builder.detachAndDelete()
+ canvas.save()
+ try {
+ canvas.clipRect(box, r.ck.ClipOp.Intersect, true)
+ canvas.clipPath(wedges, r.ck.ClipOp.Intersect, true)
+ if (inner) canvas.drawDRRect(outer, inner, r.strokePaint)
+ else canvas.drawRRect(outer, r.strokePaint)
+ } finally {
+ canvas.restore()
+ wedges.delete()
}
}
- if (top > 0 && left > 0) rect(-left * share, -top * share, 0, 0)
- if (top > 0 && right > 0) rect(w, -top * share, w + right * share, 0)
- if (bottom > 0 && right > 0) rect(w, h, w + right * share, h + bottom * share)
- if (bottom > 0 && left > 0) rect(-left * share, h, 0, h + bottom * share)
- return builder.detachAndDelete()
+ try {
+ corner(tl, tl, tl, 180, r.ck.LTRBRect(-left, -top, tl, tl))
+ corner(tr, w - tr, tr, 270, r.ck.LTRBRect(w - tr, -top, w + right, tr))
+ corner(br, w - br, h - br, 0, r.ck.LTRBRect(w - br, h - br, w + right, h + bottom))
+ corner(bl, bl, h - bl, 90, r.ck.LTRBRect(-left, h - bl, bl, h + bottom))
+ } finally {
+ r.strokePaint.setStyle(r.ck.PaintStyle.Stroke)
+ }
+}
+
+/** Corner radii as Skia draws them: scaled down together when two corners overflow a side. */
+function fittedCornerRadii(node: SceneNode): [number, number, number, number] {
+ const [tl, tr, br, bl] = cornerRadii(node)
+ const fit = (length: number, a: number, b: number) => (a + b > length ? length / (a + b) : 1)
+ const scale = Math.min(
+ fit(node.width, tl, tr),
+ fit(node.width, bl, br),
+ fit(node.height, tl, bl),
+ fit(node.height, tr, br)
+ )
+ return [tl * scale, tr * scale, br * scale, bl * scale]
}
-/** Dashed sides on rounded corners, drawn as straight dashed lines along each side. */
+/**
+ * Dashes with round or square ends, or on smoothed corners, which Figma's layout was not measured
+ * for: straight dashed lines along each side, with the stroke paint's own dash effect and caps.
+ */
function drawDashedSideLines(
r: SkiaRenderer,
canvas: Canvas,
diff --git a/packages/core/tests/canvas/shadows.test.ts b/packages/core/tests/canvas/shadows.test.ts
index ed5106f66..abf3f1216 100644
--- a/packages/core/tests/canvas/shadows.test.ts
+++ b/packages/core/tests/canvas/shadows.test.ts
@@ -2,7 +2,9 @@ import { afterAll, describe, expect, test } from 'bun:test'
import { SkiaRenderer } from '@open-pencil/core'
import { initCanvasKit } from '@open-pencil/core/io'
-import type { Effect, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import { SceneGraph, type Effect, type SceneNode } from '@open-pencil/scene-graph'
+
+import { soleShadowChild } from '#core/canvas/shadows/silhouette'
import { expectDefined } from '../helpers/assert'
import { expectFigmaRow, renderRow, type FigmaRowScene } from '../helpers/figma-rows'
@@ -91,6 +93,19 @@ const FIGMA: Record<string, number[]> = {
0, 0, 1, 13, 41, 85, 144, 195, 231, 251, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255
],
+ "turned-child-drop": [
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 248, 232, 201, 161,
+ 112, 64, 30, 11, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+ ],
+ "flipped-child-drop": [
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 250, 240, 224, 194, 154,
+ 108, 62, 28, 11, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+ ],
+ "turned-child-inner": [
+ 0, 0, 0, 0, 0, 0, 7, 36, 87, 154, 208, 242, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 0, 0, 0, 0, 0, 0, 0, 0
+ ],
}
const solid = (r: number, g: number, b: number, opacity = 1) => ({
@@ -402,3 +417,49 @@ describe('inner shadows sit where Figma draws them', () => {
expect(values.at(-1)).toBe(255)
})
})
+
+describe('a container with one turned child casts from that child alone, as in Figma', () => {
+ const turnedChild =
+ (effect: Effect, child: Partial<SceneNode>): FigmaRowScene =>
+ (graph, hostId) => {
+ const frame = graph.createNode('FRAME', hostId, {
+ ...square,
+ fills: [],
+ clipsContent: false,
+ effects: [effect]
+ })
+ graph.createNode('RECTANGLE', frame.id, {
+ x: 30,
+ y: 50,
+ width: 100,
+ height: 60,
+ fills: [RED],
+ ...child
+ })
+ }
+
+ test('takes the turned child as the source of its shadows', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ turnedChild(shadow('DROP_SHADOW'), { rotation: 30, flipX: true })(graph, page)
+ const frame = expectDefined(graph.getNode(expectDefined(graph.getNode(page)).childIds[0]))
+ expect(soleShadowChild(graph, frame)?.id).toBe(frame.childIds[0])
+ })
+
+ test('offsets the drop shadow in the container’s space, however the child turns', () => {
+ const drop = shadow('DROP_SHADOW', { offset: { x: 12, y: 0 } })
+ expectFigmaRow(row(turnedChild(drop, { rotation: 30 }), 150, 230, 300), FIGMA['turned-child-drop'])
+ expectFigmaRow(
+ row(turnedChild(drop, { rotation: 30, flipX: true }), 150, 230, 300),
+ FIGMA['flipped-child-drop']
+ )
+ })
+
+ test('offsets the inner shadow the same way (red channel)', () => {
+ const inner = shadow('INNER_SHADOW', { radius: 6, offset: { x: 10, y: 0 } })
+ expectFigmaRow(
+ row(turnedChild(inner, { rotation: 30 }), 140, 140, 260, 0),
+ FIGMA['turned-child-inner']
+ )
+ })
+})
diff --git a/packages/core/tests/canvas/strokes/sides.test.ts b/packages/core/tests/canvas/strokes/sides.test.ts
index 431d88f48..ce3bd2ac1 100644
--- a/packages/core/tests/canvas/strokes/sides.test.ts
+++ b/packages/core/tests/canvas/strokes/sides.test.ts
@@ -2,7 +2,7 @@ import { afterAll, describe, expect, test } from 'bun:test'
import { SkiaRenderer } from '@open-pencil/core'
import { initCanvasKit } from '@open-pencil/core/io'
-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import type { SceneGraph, SceneNode, Stroke } from '@open-pencil/scene-graph'
import { createDefaultNode } from '@open-pencil/scene-graph/node-defaults'
import { sideDashSpans, sideStrokeRRects } from '#core/canvas/strokes/sides'
@@ -21,6 +21,27 @@ const FIGMA = {
dashed: [
0, 0, 0, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 255
+ ],
+ evenSharp: [
+ 0, 0, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0,
+ 255
+ ],
+ evenRound: [
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 144, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0,
+ 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0
+ ],
+ evenRoundInside: [
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 16, 0, 239, 255, 128, 0, 0, 255, 255, 128, 0, 0,
+ 255, 255, 128, 0, 0, 255, 255, 128, 0, 0, 255, 255, 128, 0, 0, 255, 255, 128, 0, 0
+ ],
+ sidesRound: [
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 144, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0,
+ 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 223, 0, 0, 0, 0, 0, 0, 0, 0
]
}
@@ -102,6 +123,49 @@ describe('strokes with sides of their own weights, as in Figma', () => {
expect(values.filter((alpha) => alpha === 255).length).toBeGreaterThan(10)
})
+ test('keep round dash ends, which Figma’s flat-ended layout does not cover', () => {
+ const rounded = sidesFrame({ cornerRadius: 24 }, 1)
+ const dashedRow = (strokeCap: SceneNode['strokeCap']) =>
+ renderRow(
+ ck,
+ renderer,
+ (graph, hostId) => {
+ rounded(graph, hostId)
+ const frame = graph.getNode(expectDefined(graph.getNode(hostId)).childIds[0])
+ if (!frame) return
+ frame.strokeCap = strokeCap
+ frame.strokes = frame.strokes.map((stroke) => ({ ...stroke, dashPattern: [20, 10] }))
+ },
+ 70,
+ 160,
+ 240
+ )
+ expect(dashedRow('ROUND')).not.toEqual(dashedRow('NONE'))
+ })
+
+ test('draw nothing when no side has a weight', () => {
+ const empty = sidesFrame({
+ cornerRadius: 24,
+ borderTopWeight: 0,
+ borderRightWeight: 0,
+ borderBottomWeight: 0,
+ borderLeftWeight: 0
+ }, 1)
+ const values = renderRow(
+ ck,
+ renderer,
+ (graph, hostId) => {
+ empty(graph, hostId)
+ const frame = graph.getNode(expectDefined(graph.getNode(hostId)).childIds[0])
+ if (frame) frame.strokes = frame.strokes.map((stroke) => ({ ...stroke, dashPattern: [20, 10] }))
+ },
+ 70,
+ 112,
+ 170
+ )
+ expect(Math.max(...values)).toBe(0)
+ })
+
test('take Figma’s corner radii: inner by each side, outer by the narrower side', () => {
const node = createDefaultNode(() => 'frame', 'FRAME', {
width: 160,
@@ -141,3 +205,60 @@ describe('strokes with sides of their own weights, as in Figma', () => {
])
})
})
+
+describe('dashed rectangles, as in Figma', () => {
+ const dashedRect = (props: Partial<SceneNode>, align: Stroke['align'], dashPattern: number[]) =>
+ (graph: SceneGraph, hostId: string) => {
+ graph.createNode('RECTANGLE', hostId, {
+ x: 120,
+ y: 70,
+ fills: [],
+ strokes: [
+ {
+ type: 'SOLID',
+ color: { r: 0, g: 0, b: 1, a: 1 },
+ opacity: 1,
+ visible: true,
+ weight: 8,
+ align,
+ dashPattern
+ }
+ ],
+ strokeWeight: 8,
+ strokeAlign: align,
+ ...props
+ })
+ }
+
+ test('dash each side on its own and fill the sharp corners', () => {
+ const scene = dashedRect({ width: 150, height: 90 }, 'CENTER', [20, 10])
+ expectFigmaRow(renderRow(ck, renderer, scene, 70, 112, 200), FIGMA.evenSharp)
+ })
+
+ test('dash each corner arc on its own, between the dashes of the straight sides', () => {
+ const scene = dashedRect({ width: 168, height: 108, cornerRadius: 24 }, 'CENTER', [20, 10])
+ expectFigmaRow(renderRow(ck, renderer, scene, 70, 112, 290), FIGMA.evenRound)
+ })
+
+ test('measure corner arcs on the shape’s edge, whatever the stroke’s alignment', () => {
+ const scene = dashedRect({ width: 168, height: 168, cornerRadius: 24 }, 'INSIDE', [5, 5])
+ expectFigmaRow(renderRow(ck, renderer, scene, 74, 112, 200), FIGMA.evenRoundInside)
+ })
+
+ test('dash rounded corners between sides of their own weights the same way', () => {
+ const scene = sidesFrame({ width: 168, height: 168, cornerRadius: 24 }, 1)
+ const values = renderRow(
+ ck,
+ renderer,
+ (graph, hostId) => {
+ scene(graph, hostId)
+ const frame = graph.getNode(expectDefined(graph.getNode(hostId)).childIds[0])
+ if (frame) frame.strokes = frame.strokes.map((stroke) => ({ ...stroke, dashPattern: [20, 10] }))
+ },
+ 70,
+ 112,
+ 290
+ )
+ expectFigmaRow(values, FIGMA.sidesRound)
+ })
+})
diff --git a/tests/e2e/canvas/side-strokes-visual.spec.ts b/tests/e2e/canvas/side-strokes-visual.spec.ts
index 3fd4d1ddf..1b3379f91 100644
--- a/tests/e2e/canvas/side-strokes-visual.spec.ts
+++ b/tests/e2e/canvas/side-strokes-visual.spec.ts
@@ -9,8 +9,10 @@ test('strokes with sides of their own weights', async () => {
await scene.show()
await editor.canvas.waitForRender()
editor.canvas.assertNoErrors()
- // The corners are small next to the canvas: pin an absolute pixel budget below one corner.
+ // The corners are small next to the canvas: pin an absolute pixel budget below one corner,
+ // and a colour threshold under the gap between a translucent stroke and the canvas.
expect(await editor.canvas.screenshotCanvasRegion()).toMatchSnapshot('side-strokes.png', {
- maxDiffPixels: 24
+ maxDiffPixels: 24,
+ threshold: 0.05
})
})
diff --git a/tests/e2e/canvas/side-strokes-visual.spec.ts-snapshots/side-strokes-openpencil-darwin.png b/tests/e2e/canvas/side-strokes-visual.spec.ts-snapshots/side-strokes-openpencil-darwin.png
index 6303e1f4f..cd2874b80 100644
Binary files a/tests/e2e/canvas/side-strokes-visual.spec.ts-snapshots/side-strokes-openpencil-darwin.png and b/tests/e2e/canvas/side-strokes-visual.spec.ts-snapshots/side-strokes-openpencil-darwin.png differ
diff --git a/tests/helpers/canvas/strokes/scene.ts b/tests/helpers/canvas/strokes/scene.ts
index bc5868bdb..66f3df42d 100644
--- a/tests/helpers/canvas/strokes/scene.ts
+++ b/tests/helpers/canvas/strokes/scene.ts
@@ -4,15 +4,20 @@ const ALIGNS = ['INSIDE', 'CENTER', 'OUTSIDE'] as const
const CORNERS = [
{ name: 'sharp', cornerRadius: 0, dashPattern: undefined },
{ name: 'rounded', cornerRadius: 24, dashPattern: undefined },
- { name: 'dashed', cornerRadius: 0, dashPattern: [20, 10] }
+ { name: 'dashed', cornerRadius: 0, dashPattern: [20, 10] },
+ { name: 'rounded dashed', cornerRadius: 24, dashPattern: [20, 10] }
]
-/** Translucent frames with sides of their own weights: one row per alignment, sharp, rounded, and dashed. */
+/**
+ * Translucent frames with sides of their own weights, one row per alignment, then a row with
+ * every side at one weight: sharp, rounded, dashed, and rounded and dashed.
+ */
export function createSideStrokesScene(graph: SceneGraph, pageId: string): void {
- for (const [row, align] of ALIGNS.entries()) {
+ for (const [row, align] of [...ALIGNS, 'CENTER' as const].entries()) {
+ const even = row === ALIGNS.length
for (const [column, corner] of CORNERS.entries()) {
graph.createNode('FRAME', pageId, {
- name: `${align} ${corner.name}`,
+ name: `${even ? 'even' : align} ${corner.name}`,
x: 60 + column * 200,
y: 60 + row * 170,
width: 140,
@@ -33,7 +38,7 @@ export function createSideStrokesScene(graph: SceneGraph, pageId: string): void
],
strokeWeight: 8,
strokeAlign: align,
- independentStrokeWeights: true,
+ independentStrokeWeights: !even,
borderTopWeight: 8,
borderRightWeight: 0,
borderBottomWeight: 16,