AI-native design editor. Open-source Figma alternative.
fix(canvas): dash sections and component sets as Figma does, and speed up spaced shadows (#1311)
Danila Poyarkove0de19d13c39
diff --git a/changes/1311/fixed.md b/changes/1311/fixed.mdnew file mode 100644index 000000000..68ab65cf0--- /dev/null+++ b/changes/1311/fixed.md@@ -0,0 +1 @@+- Dashed strokes on sections and component sets are drawn as on rectangles, as in Figma: sections showed no dashes, and component sets drew solid corners.diff --git a/changes/1311/performance.md b/changes/1311/performance.mdnew file mode 100644index 000000000..f3184c39d--- /dev/null+++ b/changes/1311/performance.md@@ -0,0 +1 @@+- Shadows of a frame or group without a fill render about four times faster when its layers stand apart, as in rows of cards or buttons.diff --git a/packages/core/src/canvas/scene.ts b/packages/core/src/canvas/scene.tsindex d476e43ad..ba07fe433 100644--- a/packages/core/src/canvas/scene.ts+++ b/packages/core/src/canvas/scene.ts@@ -489,7 +489,9 @@ export function renderSection(configureStrokePaint(r, node, stroke, color)if (node.independentStrokeWeights) r.drawIndividualSideStrokes(canvas, node, stroke)- else r.drawRRectStrokeWithAlign(canvas, rrect, node, stroke)+ else if (!drawFigmaDashes(r, canvas, node, stroke)) {+ r.drawRRectStrokeWithAlign(canvas, rrect, node, stroke)+ }})}@@ -502,6 +504,8 @@ export function renderComponentSet(const rrect = fillRoundedBounds(r, canvas, node, graph)// A set without a stroke gets its dashed editing border from the overlay pass.forVisibleStrokes(r, node, graph, (stroke, color) => {+ configureStrokePaint(r, node, stroke, color)+ if (drawFigmaDashes(r, canvas, node, stroke)) returnconst dashPhase = stroke.dashPattern?.[1] ?? 0if (stroke.dashPattern && stroke.dashPattern.length > 0) {drawDashedRRectWithSolidCorners(@@ -741,6 +745,22 @@ function drawVectorPathStrokes(else for (const outline of outlines) outline.delete()}+/**+ * Draws a dashed stroke on a rectangle, frame, section, or component set with Figma's dash+ * layout, and returns false when the stroke has no dashes or the layout does not apply.+ */+function drawFigmaDashes(+ r: SkiaRenderer,+ canvas: Canvas,+ node: SceneNode,+ stroke: SceneNode['strokes'][0]+): boolean {+ const dash = normalizeDashPattern(stroke.dashPattern)+ if (dash.length === 0 || !strokeDashesByOutline(node, stroke)) return false+ drawDashedRectStroke(r, canvas, node, stroke, strokeSideWeights(node, stroke), dash)+ return true+}+function drawRegularStroke(r: SkiaRenderer,canvas: Canvas,@@ -756,13 +776,7 @@ 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 {+ } else if (!r.isRectangularType(node.type) || !drawFigmaDashes(r, canvas, node, stroke)) {r.drawStrokeWithAlign(canvas, node, rect, hasRadius, stroke.align)}}diff --git a/packages/core/src/canvas/shadows.ts b/packages/core/src/canvas/shadows.tsindex d7bf2a661..b25c49746 100644--- a/packages/core/src/canvas/shadows.ts+++ b/packages/core/src/canvas/shadows.ts@@ -10,6 +10,7 @@ import { blurSigma, renderNoiseEffects } from './effects'import type { SkiaRenderer } from './renderer'import {castsFromOwnShape,+ castsOwnShapeDropShadow,clipOutShapeKnockout,drawOutlineDropShadow,drawRingDropShadow,@@ -26,7 +27,7 @@ import {paintsOverKnockout,shadowIncludesChildren,silhouetteBounds,- soleShadowChild+ separateShadowChildren} from './shadows/silhouette'import { nodeHasRadius } from './shapes'function resetEffectLayerPaint(r: SkiaRenderer): void {@@ -161,6 +162,15 @@ function drawOwnShapeDropShadow(return true}+/**+ * How far apart a container's children must be for their shadows to reach neither each other nor+ * another child: the blur's reach from both, any spread, and the offset.+ */+function shadowGap(effect: Effect, spread: number): number {+ const reach = 3 * blurSigma(effect.radius) + Math.abs(spread) + 1+ return 2 * reach + Math.hypot(effect.offset.x, effect.offset.y)+}+/*** 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@@ -199,14 +209,23 @@ function renderDropShadow(const blendMode = figmaBlendModeToSkia(r.ck, effect.blendMode)const knockout =effect.showShadowBehindNode === false && !paintsOverKnockout(graph, node, includeChildren)- const sole = includeChildren ? soleShadowChild(graph, node) : null- const drawnAlone = sole- ? withChildCoordinates(canvas, sole, effect, (local) =>- drawOwnShapeDropShadow(r, canvas, sole, local, spread, blendMode, knockout)+ const children = includeChildren+ ? separateShadowChildren(graph, node, shadowGap(effect, spread))+ : null+ if (children?.every((child) => castsOwnShapeDropShadow(child, spread))) {+ for (const child of children) {+ withChildCoordinates(canvas, child, effect, (local) =>+ drawOwnShapeDropShadow(r, canvas, child, local, spread, blendMode, knockout))- : !includeChildren &&- drawOwnShapeDropShadow(r, canvas, node, effect, spread, blendMode, knockout)- if (drawnAlone) return+ }+ return+ }+ if (+ !includeChildren &&+ drawOwnShapeDropShadow(r, canvas, node, effect, spread, blendMode, knockout)+ ) {+ return+ }const bounds = shadowLayerBounds(r, graph, node, effect, spread, includeChildren)const isolation = knockout ? new r.ck.Paint() : null@@ -315,18 +334,22 @@ function renderInnerShadow(includeChildren: boolean): void {if (!includeChildren && !paintsCastShadow(node)) return- const sole = includeChildren ? soleShadowChild(graph, node) : null- if (sole && castsFromOwnShape(sole)) {- withChildCoordinates(canvas, sole, effect, (local) =>- drawShapeInnerShadow(- r,- canvas,- sole,- r.ck.LTRBRect(0, 0, sole.width, sole.height),- local,- nodeHasRadius(sole)+ const children = includeChildren+ ? separateShadowChildren(graph, node, shadowGap(effect, 0))+ : null+ if (children?.every(castsFromOwnShape)) {+ for (const child of children) {+ withChildCoordinates(canvas, child, effect, (local) =>+ drawShapeInnerShadow(+ r,+ canvas,+ child,+ r.ck.LTRBRect(0, 0, child.width, child.height),+ local,+ nodeHasRadius(child)+ ))- )+ }return}if (!includeChildren && castsFromOwnShape(node)) {diff --git a/packages/core/src/canvas/shadows/shape.ts b/packages/core/src/canvas/shadows/shape.tsindex 231b41928..d1c5dd47b 100644--- a/packages/core/src/canvas/shadows/shape.ts+++ b/packages/core/src/canvas/shadows/shape.ts@@ -30,6 +30,11 @@ export function castsFromOwnShape(node: SceneNode): boolean {)}+/** Whether a layer's drop shadow comes from its own outline alone, which the paths below draw. */+export function castsOwnShapeDropShadow(node: SceneNode, spread: number): boolean {+ return regularStrokeOutline(node, spread) !== null || castsFromOwnShape(node)+}+const OUTLINE_SHAPE_TYPES: ReadonlySet<SceneNode['type']> = new Set<SceneNode['type']>(['RECTANGLE','ROUNDED_RECTANGLE',diff --git a/packages/core/src/canvas/shadows/silhouette.ts b/packages/core/src/canvas/shadows/silhouette.tsindex 225085c05..9c42f9873 100644--- a/packages/core/src/canvas/shadows/silhouette.ts+++ b/packages/core/src/canvas/shadows/silhouette.ts@@ -347,20 +347,46 @@ export function shadowIncludesChildren(graph: SceneGraph, node: SceneNode): boolreturn bounds !== null && !shapeContainsBox(node, bounds)}+/** Most children `separateShadowChildren` compares pair by pair before it leaves them to the layer. */+const MAX_SEPARATE_CHILDREN = 32++/** Whether two boxes are more than `gap` apart along either axis. */+function apart(a: Rect, b: Rect, gap: number): boolean {+ return (+ a.x + a.width + gap < b.x ||+ b.x + b.width + gap < a.x ||+ a.y + a.height + gap < b.y ||+ b.y + b.height + gap < a.y+ )+}+/**- * The one child a container's shadows come from when the container paints nothing itself and- * draws only that child, so the shadow is that child's own, turned with it; null otherwise.+ * The children a container's shadows come from, each casting on its own, when the container+ * paints nothing itself and does not clip, no child is a mask or brings children of its own, and+ * every two children are more than `gap` apart; null otherwise. Shadows that reach neither each+ * other nor another child draw the same one by one, turned with each child, as from the whole+ * layer.*/-export function soleShadowChild(graph: SceneGraph, node: SceneNode): SceneNode | null {+export function separateShadowChildren(+ graph: SceneGraph,+ node: SceneNode,+ gap: number+): SceneNode[] | null {if (!isLayerContainer(node) || paintsCastShadow(node) || clipsChildren(node)) return null- let sole: SceneNode | null = null+ const children: SceneNode[] = []for (const id of node.childIds) {const child = graph.getNode(id)if (!child || !drawsSilhouette(child)) continue- if (child.isMask || sole) return null- sole = child+ if (child.isMask || children.length === MAX_SEPARATE_CHILDREN) return null+ if (isLayerContainer(child) && shadowIncludesChildren(graph, child)) return null+ children.push(child)+ }+ if (children.length < 2) return children.length === 1 ? children : null+ const boxes: Rect[] = []+ for (const child of children) {+ const box = childBox(graph, child.id)+ if (!box || boxes.some((other) => !apart(box, other, gap))) return null+ boxes.push(box)}- if (!sole) return null- if (isLayerContainer(sole) && shadowIncludesChildren(graph, sole)) return null- return sole+ return children}diff --git a/packages/core/tests/canvas/shadows.test.ts b/packages/core/tests/canvas/shadows.test.tsindex abf3f1216..ccd2445f3 100644--- a/packages/core/tests/canvas/shadows.test.ts+++ b/packages/core/tests/canvas/shadows.test.ts@@ -4,7 +4,7 @@ import { SkiaRenderer } from '@open-pencil/core'import { initCanvasKit } from '@open-pencil/core/io'import { SceneGraph, type Effect, type SceneNode } from '@open-pencil/scene-graph'-import { soleShadowChild } from '#core/canvas/shadows/silhouette'+import { separateShadowChildren } from '#core/canvas/shadows/silhouette'import { expectDefined } from '../helpers/assert'import { expectFigmaRow, renderRow, type FigmaRowScene } from '../helpers/figma-rows'@@ -106,6 +106,35 @@ const FIGMA: Record<string, number[]> = {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],+ "separate-children-drop": [+ 0, 0, 0, 0, 3, 13, 29, 58, 93, 124, 147, 162, 169, 171, 172, 171, 171, 171, 171, 171, 171,+ 172, 172, 171, 172, 171, 172, 171, 172, 172, 171, 171, 171, 171, 171, 172, 171, 171, 171, 172,+ 171, 171, 167, 156, 136, 109, 75, 43, 20, 7, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,+ 0, 0, 1, 8, 28, 57, 96, 132, 155, 168, 171, 171, 171, 171, 171, 171, 171, 171, 171, 171, 172,+ 172, 172, 172, 172, 172, 171, 171, 171, 172, 171, 172, 171, 171, 171, 172, 172, 171, 171, 171,+ 171, 171, 171, 163, 145, 115, 78, 42, 17, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,+ 0, 0, 0, 0, 0, 0, 0, 1, 3, 11, 22, 37, 57, 79, 101, 121, 138, 151, 159, 164, 165, 162, 156,+ 145, 130, 111, 89, 68, 47, 29, 16, 7, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0+ ],+ "separate-children-knockout": [+ 0, 0, 0, 1, 13, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,+ 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,+ 128, 128, 128, 128, 128, 128, 215, 171, 114, 62, 26, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,+ 0, 0, 0, 0, 1, 13, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,+ 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,+ 128, 128, 128, 128, 128, 128, 215, 171, 114, 62, 26, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,+ 0, 0, 0, 0, 1, 12, 36, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,+ 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 223, 209, 161, 104, 56,+ 21, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0+ ],+ "separate-children-inner": [+ 0, 0, 0, 0, 0, 1, 10, 43, 100, 164, 212, 237, 244, 245, 246, 247, 246, 247, 246, 247, 246,+ 246, 246, 246, 246, 247, 246, 246, 247, 246, 246, 247, 246, 247, 246, 247, 246, 247, 246, 247,+ 246, 246, 246, 245, 242, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,+ 0, 0, 2, 23, 70, 142, 203, 237, 246, 246, 247, 247, 246, 247, 247, 246, 247, 247, 246, 246,+ 246, 246, 246, 247, 246, 247, 246, 246, 246, 246, 246, 246, 247, 246, 246, 246, 246, 246, 246,+ 247, 247, 246, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0+ ],}const solid = (r: number, g: number, b: number, opacity = 1) => ({@@ -443,7 +472,7 @@ describe('a container with one turned child casts from that child alone, as in Fconst page = graph.getPages()[0].idturnedChild(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])+ expect(separateShadowChildren(graph, frame, 0)?.map((child) => child.id)).toEqual(frame.childIds)})test('offsets the drop shadow in the container’s space, however the child turns', () => {@@ -463,3 +492,47 @@ describe('a container with one turned child casts from that child alone, as in F)})})++describe('a container casts from each of its separate children on its own, as in Figma', () => {+ const HALF_BLUE = solid(0, 0, 1, 0.5)+ const separateChildren =+ (effect: Effect, fills: SceneNode['fills'], gap = 50): FigmaRowScene =>+ (graph, hostId) => {+ const frame = graph.createNode('FRAME', hostId, {+ x: 20,+ y: 60,+ width: 360,+ height: 160,+ fills: [],+ clipsContent: false,+ effects: [effect]+ })+ const child = { y: 20, height: 60, fills }+ graph.createNode('RECTANGLE', frame.id, { ...child, x: 10, width: 80, cornerRadius: 8 })+ graph.createNode('RECTANGLE', frame.id, { ...child, x: 90 + gap, width: 80 })+ graph.createNode('ELLIPSE', frame.id, { ...child, x: 170 + 2 * gap, width: 60 })+ }+ const drop = shadow('DROP_SHADOW', { offset: { x: 4, y: 8 } })++ test('takes children apart only when their shadows cannot reach each other', () => {+ for (const [gap, separate] of [[50, true], [10, false]] as const) {+ const graph = new SceneGraph()+ const page = graph.getPages()[0].id+ separateChildren(drop, [RED], gap)(graph, page)+ const frame = expectDefined(graph.getNode(expectDefined(graph.getNode(page)).childIds[0]))+ const children = separateShadowChildren(graph, frame, 30)+ expect(children?.length ?? 0).toBe(separate ? 3 : 0)+ }+ })++ test('casts the drop shadow and hides it under each translucent child', () => {+ const scene = separateChildren(drop, [HALF_BLUE])+ expectFigmaRow(row(scene, 146, 20, 380), FIGMA['separate-children-drop'])+ expectFigmaRow(row(scene, 120, 20, 380), FIGMA['separate-children-knockout'])+ })++ test('puts the inner shadow on each child (red channel)', () => {+ const inner = shadow('INNER_SHADOW', { radius: 6, offset: { x: 6, y: 6 } })+ expectFigmaRow(row(separateChildren(inner, [RED]), 90, 20, 290, 0), FIGMA['separate-children-inner'])+ })+})diff --git a/packages/core/tests/canvas/strokes/sides.test.ts b/packages/core/tests/canvas/strokes/sides.test.tsindex ce3bd2ac1..7ca010453 100644--- a/packages/core/tests/canvas/strokes/sides.test.ts+++ b/packages/core/tests/canvas/strokes/sides.test.ts@@ -207,9 +207,15 @@ 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[]) =>+ const dashedRect =+ (+ props: Partial<SceneNode>,+ align: Stroke['align'],+ dashPattern: number[],+ type: 'RECTANGLE' | 'SECTION' | 'COMPONENT_SET' = 'RECTANGLE'+ ) =>(graph: SceneGraph, hostId: string) => {- graph.createNode('RECTANGLE', hostId, {+ graph.createNode(type, hostId, {x: 120,y: 70,fills: [],@@ -230,6 +236,15 @@ describe('dashed rectangles, as in Figma', () => {})}+ test('dash sections and component sets as rectangles, as Figma exports them', () => {+ const props = { width: 168, height: 108, cornerRadius: 24 }+ const rectangle = renderRow(ck, renderer, dashedRect(props, 'CENTER', [20, 10]), 70, 112, 290)+ for (const type of ['SECTION', 'COMPONENT_SET'] as const) {+ const scene = dashedRect(props, 'CENTER', [20, 10], type)+ expect(renderRow(ck, renderer, scene, 70, 112, 290)).toEqual(rectangle)+ }+ })+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)diff --git a/tests/e2e/canvas/dashed-containers-visual.spec.ts b/tests/e2e/canvas/dashed-containers-visual.spec.tsnew file mode 100644index 000000000..237af2a2c--- /dev/null+++ b/tests/e2e/canvas/dashed-containers-visual.spec.ts@@ -0,0 +1,15 @@+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'+import { dashedContainersDriver } from '#tests/helpers/canvas/strokes/driver'++const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')+const scene = dashedContainersDriver(() => editor.page)++// The dash layout is checked against Figma in packages/core/tests/canvas/strokes/sides.test.ts.+test('sections and component sets dash their strokes as rectangles do', async () => {+ await scene.show()+ await editor.canvas.waitForRender()+ editor.canvas.assertNoErrors()+ expect(await editor.canvas.screenshotCanvasRegion()).toMatchSnapshot('dashed-containers.png', {+ threshold: 0.05+ })+})diff --git a/tests/e2e/canvas/dashed-containers-visual.spec.ts-snapshots/dashed-containers-openpencil-darwin.png b/tests/e2e/canvas/dashed-containers-visual.spec.ts-snapshots/dashed-containers-openpencil-darwin.pngnew file mode 100644index 000000000..6bb073e09Binary files /dev/null and b/tests/e2e/canvas/dashed-containers-visual.spec.ts-snapshots/dashed-containers-openpencil-darwin.png differdiff --git a/tests/helpers/canvas/strokes/driver.ts b/tests/helpers/canvas/strokes/driver.tsindex 08ec8099f..dd30c8e19 100644--- a/tests/helpers/canvas/strokes/driver.ts+++ b/tests/helpers/canvas/strokes/driver.ts@@ -18,3 +18,20 @@ export function sideStrokesDriver(page: () => Page) {}}}++/** Builds the dashed containers scene on the open page and leaves it unselected for a snapshot. */+export function dashedContainersDriver(page: () => Page) {+ return {+ show() {+ return page().evaluate(async () => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const sceneURL = '/tests/helpers/canvas/strokes/scene.ts'+ const scenes: typeof StrokeScenes = await import(sceneURL)+ scenes.createDashedContainersScene(store.graph, store.state.currentPageId)+ store.clearSelection()+ store.requestRender()+ })+ }+ }+}diff --git a/tests/helpers/canvas/strokes/scene.ts b/tests/helpers/canvas/strokes/scene.tsindex 66f3df42d..a1d730adf 100644--- a/tests/helpers/canvas/strokes/scene.ts+++ b/tests/helpers/canvas/strokes/scene.ts@@ -47,3 +47,34 @@ export function createSideStrokesScene(graph: SceneGraph, pageId: string): void}}}++/** A dashed rectangle, section, and component set side by side, each rounded and each sharp. */+export function createDashedContainersScene(graph: SceneGraph, pageId: string): void {+ const types = ['RECTANGLE', 'SECTION', 'COMPONENT_SET'] as const+ for (const [column, type] of types.entries()) {+ for (const [row, cornerRadius] of [0, 24].entries()) {+ graph.createNode(type, pageId, {+ name: `${type.toLowerCase()} ${cornerRadius ? 'rounded' : 'sharp'}`,+ x: 60 + column * 270,+ y: 80 + row * 300,+ width: 200,+ height: 200,+ cornerRadius,+ fills: [],+ strokes: [+ {+ type: 'SOLID',+ color: { r: 0.6, g: 0.2, b: 0.9, a: 1 },+ opacity: 1,+ visible: true,+ weight: 4,+ align: 'CENTER',+ dashPattern: [20, 10]+ }+ ],+ strokeWeight: 4,+ strokeAlign: 'CENTER'+ })+ }+ }+}