AI-native design editor. Open-source Figma alternative.
fix(core): clip boolean background blur to its shape and fix inner shadow edges (#1384)
Danila Poyarkov4b34c3900a6c
diff --git a/changes/1384/fixed.md b/changes/1384/fixed.mdnew file mode 100644index 000000000..62842116d--- /dev/null+++ b/changes/1384/fixed.md@@ -0,0 +1 @@+- A boolean's background blur stays inside its shape, and an inner shadow over a curved edge no longer lets the fill show through it, as in Figma.diff --git a/packages/core/src/canvas/effects.ts b/packages/core/src/canvas/effects.tsindex 71d487c9a..841c8530f 100644--- a/packages/core/src/canvas/effects.ts+++ b/packages/core/src/canvas/effects.ts@@ -1,4 +1,4 @@-import type { Canvas, ImageFilter, MaskFilter } from 'canvaskit-wasm'+import type { Canvas, ImageFilter, MaskFilter, Path } from 'canvaskit-wasm'import { readEffectiveFigmaRawField } from '@open-pencil/fig'import type { SceneNode } from '@open-pencil/scene-graph'@@ -62,11 +62,16 @@ export function getCachedMaskBlur(r: SkiaRenderer, sigma: number): MaskFilter {return filter}+/**+ * Blurs what lies behind the layer, inside its outline, or inside `shape` when the layer's outline+ * is not its box, as with a boolean's result.+ */export function applyClippedBlur(r: SkiaRenderer,canvas: Canvas,node: SceneNode,- sigma: number+ sigma: number,+ shape: Path | null = null): void {const rect = r.ck.LTRBRect(0, 0, node.width, node.height)// Entry guard: reset shared paint to known state@@ -75,7 +80,8 @@ export function applyClippedBlur(r.effectLayerPaint.setBlendMode(r.ck.BlendMode.SrcOver)canvas.save()- r.clipNodeShape(canvas, node)+ if (shape) canvas.clipPath(shape, r.ck.ClipOp.Intersect, true)+ else r.clipNodeShape(canvas, node)canvas.saveLayer(undefined, rect, r.getCachedBlur(sigma), undefined, r.ck.TileMode.Clamp)canvas.restore()// Exit guard: ensure shared paint is in clean statediff --git a/packages/core/src/canvas/renderer.ts b/packages/core/src/canvas/renderer.tsindex 1981f71c8..46d3d3b56 100644--- a/packages/core/src/canvas/renderer.ts+++ b/packages/core/src/canvas/renderer.ts@@ -410,7 +410,12 @@ export class SkiaRenderer {declare getCachedBlur: (sigma: number) => ImageFilterdeclare getCachedDecalBlur: (sigma: number) => ImageFilterdeclare getCachedMaskBlur: (sigma: number) => MaskFilter- declare applyClippedBlur: (canvas: Canvas, node: SceneNode, sigma: number) => void+ declare applyClippedBlur: (+ canvas: Canvas,+ node: SceneNode,+ sigma: number,+ shape?: Path | null+ ) => voidcolor4f(r: number, g: number, b: number, a: number): Float32Array {const c = this._tmpColorc[0] = rdiff --git a/packages/core/src/canvas/renderer/methods.ts b/packages/core/src/canvas/renderer/methods.tsindex cb7b17bb0..6b28dd4c4 100644--- a/packages/core/src/canvas/renderer/methods.ts+++ b/packages/core/src/canvas/renderer/methods.ts@@ -352,8 +352,8 @@ const rendererMethods: ThisType<SkiaRenderer> = {return Effects.getCachedMaskBlur(this, sigma)},- applyClippedBlur(canvas: Canvas, node: SceneNode, sigma: number): void {- Effects.applyClippedBlur(this, canvas, node, sigma)+ applyClippedBlur(canvas: Canvas, node: SceneNode, sigma: number, shape?: Path | null): void {+ Effects.applyClippedBlur(this, canvas, node, sigma, shape)}}diff --git a/packages/core/src/canvas/scene.ts b/packages/core/src/canvas/scene.tsindex cd8cb7008..b0a2cf33e 100644--- a/packages/core/src/canvas/scene.ts+++ b/packages/core/src/canvas/scene.ts@@ -35,7 +35,7 @@ import {effectRasterScaleMatches} from './renderer/effect-raster-cache'import { mapVisualBounds, subtreeVisualBounds } from './renderer/visual-bounds'-import { renderLayerShadows } from './shadows'+import { isolatesInnerShadows, renderLayerShadows } from './shadows'import { isLayerContainer } from './shadows/silhouette'import {configureStrokePaint,@@ -920,11 +920,14 @@ export function paintShapeContent()}+ const isolated = afterFills !== undefined && isolatesInnerShadows(node)+ if (isolated) canvas.saveLayer()if (!drawVectorMultiStyleFills(r, canvas, node, graph)) {drawVisibleFills(r, node, graph, (fill) => r.drawNodeFill(canvas, node, fill))}if (node.type === 'TEXT') drawTextEmoji(r, canvas, node)afterFills?.()+ if (isolated) canvas.restore()if (!pathTextStrokeFirst && !reflowedPathText) {paintNodeStrokes(r, canvas, node, graph, sg, vectorPaths, vectorStroke)diff --git a/packages/core/src/canvas/shadows.ts b/packages/core/src/canvas/shadows.tsindex aee1237a0..f97be877d 100644--- a/packages/core/src/canvas/shadows.ts+++ b/packages/core/src/canvas/shadows.ts@@ -5,7 +5,8 @@ import Matrix from '@open-pencil/scene-graph/matrix'import { nodeOrientationMatrix } from '#core/geometry'-import { figmaBlendModeToSkia } from './blend'+import { figmaBlendModeToSkia, needsIsolatedBlendLayer } from './blend'+import { makeBooleanOperationPath } from './boolean'import { blurSigma, renderNoiseEffects } from './effects'import type { SkiaRenderer } from './renderer'import {@@ -359,7 +360,8 @@ function renderInnerShadow(return}if (!includeChildren && castsFromOwnShape(node)) {- drawShapeInnerShadow(r, canvas, node, effect, innerShadowSpread(node, effect))+ const spread = innerShadowSpread(node, effect)+ drawShapeInnerShadow(r, canvas, node, effect, spread, isolatesInnerShadows(node))return}const bounds = shadowLayerBounds(r, graph, node, effect, 0, includeChildren)@@ -368,6 +370,24 @@ function renderInnerShadow()}+/**+ * Whether a shape draws its fills and inner shadows in a layer of their own. There each shadow+ * replaces the fill under it before taking the shape's outline, so the antialiased edge applies+ * once, as in Figma, rather than letting the fill show through. Blended fills and shadows mix with+ * what lies under the shape, so they keep drawing in place.+ */+export function isolatesInnerShadows(node: SceneNode): boolean {+ if (isLayerContainer(node) || !castsFromOwnShape(node)) return false+ const shadows = node.effects.filter((effect) => effect.visible && effect.type === 'INNER_SHADOW')+ return (+ shadows.length > 0 &&+ shadows.every((effect) => !needsIsolatedBlendLayer(effect.blendMode)) &&+ [...node.fills, ...node.fillGeometry.flatMap((geometry) => geometry.fills ?? [])].every(+ (fill) => !fill.visible || !needsIsolatedBlendLayer(fill.blendMode)+ )+ )+}+/*** Draws a shape's own effects. Frames, groups, and other containers take their shadows from* `renderLayerShadows` instead, because Figma casts them from the children as well.@@ -390,7 +410,10 @@ export function renderEffects(}if (pass === 'behind' && effect.type === 'BACKGROUND_BLUR') {- r.applyClippedBlur(canvas, node, blurSigma(effect.radius))+ const shape =+ node.type === 'BOOLEAN_OPERATION' ? makeBooleanOperationPath(r, node, graph) : null+ r.applyClippedBlur(canvas, node, blurSigma(effect.radius), shape)+ shape?.delete()}if (pass === 'inner' && effect.type === 'INNER_SHADOW' && ownShadows) {diff --git a/packages/core/src/canvas/shadows/shape.ts b/packages/core/src/canvas/shadows/shape.tsindex 2f2113639..966eb7eb3 100644--- a/packages/core/src/canvas/shadows/shape.ts+++ b/packages/core/src/canvas/shadows/shape.ts@@ -229,23 +229,23 @@ export function clipOutShapeKnockout(/*** Draws an inner shadow: everything outside the shape, moved by the shadow's offset and grown- * into the shape by its spread, blurred and clipped to the shape.+ * into the shape by its spread, blurred and clipped to the shape. `isolated` says the shape's fills+ * sit in a layer of their own, as `isolatesInnerShadows` has them.*/export function drawShapeInnerShadow(r: SkiaRenderer,canvas: Canvas,node: SceneNode,effect: Effect,- spread: number+ spread: number,+ isolated = false): void {const sp = spreadr.auxFill.setColor(r.ck.Color4f(effect.color.r, effect.color.g, effect.color.b, effect.color.a))r.auxFill.setImageFilter(r.getCachedDecalBlur(blurSigma(effect.radius)))- r.auxFill.setBlendMode(figmaBlendModeToSkia(r.ck, effect.blendMode))canvas.save()try {- r.clipNodeShape(canvas, node)const expand = effect.radius * 2const { x: offsetX, y: offsetY } = effect.offsetconst spreadPadding = sp < 0 ? -sp : 0@@ -267,10 +267,19 @@ export function drawShapeInnerShadow(const shadowPath = r.ck.Path.MakeFromOp(areaPath, shapePath, r.ck.PathOp.Difference)areaPath.delete()shapePath.delete()- if (shadowPath) {+ if (!shadowPath) return+ if (isolated) {+ // Alone over the fills, the shadow takes the fill out from under it before it is clipped,+ // so the outline's antialiased edge applies once and no fill shows through it.+ r.auxFill.setBlendMode(r.ck.BlendMode.DstOut)canvas.drawPath(shadowPath, r.auxFill)- shadowPath.delete()+ r.auxFill.setBlendMode(r.ck.BlendMode.Plus)+ } else {+ r.auxFill.setBlendMode(figmaBlendModeToSkia(r.ck, effect.blendMode))}+ r.clipNodeShape(canvas, node)+ canvas.drawPath(shadowPath, r.auxFill)+ shadowPath.delete()} finally {canvas.restore()r.auxFill.setImageFilter(null)diff --git a/packages/core/tests/canvas/blur.test.ts b/packages/core/tests/canvas/blur.test.tsindex db6541b9e..0a477c61c 100644--- a/packages/core/tests/canvas/blur.test.ts+++ b/packages/core/tests/canvas/blur.test.ts@@ -45,6 +45,12 @@ const FIGMA: Record<string, number[]> = {31, 39, 48, 58, 69, 80, 94, 107, 122, 137, 152, 166, 179, 190, 202, 210, 219, 227, 234, 241,245, 249, 252, 254, 254, 255, 255, 254, 255, 255, 255, 254, 255, 254, 254, 254, 255, 255, 255,254, 255, 255, 255, 255, 255, 255, 255, 254, 254, 255+ ],+ 'BACKGROUND_BLUR 16 union': [+ 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, 0, 0, 0, 0, 0, 0,+ 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 198, 190, 202, 210, 219, 227, 234, 241, 245, 249, 252,+ 254, 254, 255, 255, 254, 255, 255, 255, 254, 255, 254, 254, 254, 255, 255, 255, 254, 255, 255,+ 255, 255, 255, 255, 255, 254, 254, 255]}@@ -172,6 +178,31 @@ describe('blur effects fall off as in Figma', () => {}, 0)expectFigmaEdge(row, FIGMA['BACKGROUND_BLUR 16'])})++ test('background blur on a boolean, inside its result alone', () => {+ // The row crosses the lower circle from x 103; before it the backdrop stays sharp.+ const row = edgeRow((graph, frameId) => {+ graph.createNode('RECTANGLE', frameId, { width: 100, height: 400, fills: [solid(0, 0, 0)] })+ graph.createNode('RECTANGLE', frameId, {+ x: 100,+ width: 300,+ height: 400,+ fills: [solid(1, 1, 1)]+ })+ const union = graph.createNode('BOOLEAN_OPERATION', frameId, {+ x: 40,+ y: 40,+ width: 180,+ height: 240,+ booleanOperation: 'UNION',+ fills: [solid(1, 1, 1, 0.01)],+ effects: [effect('BACKGROUND_BLUR', 16)]+ })+ graph.createNode('ELLIPSE', union.id, { width: 120, height: 120 })+ graph.createNode('ELLIPSE', union.id, { x: 60, y: 120, width: 120, height: 120 })+ }, 0)+ expectFigmaEdge(row, FIGMA['BACKGROUND_BLUR 16 union'])+ })})describe('shadows of a transparent fill', () => {diff --git a/packages/core/tests/canvas/shadows/shape.test.ts b/packages/core/tests/canvas/shadows/shape.test.tsnew file mode 100644index 000000000..6a96b328f--- /dev/null+++ b/packages/core/tests/canvas/shadows/shape.test.ts@@ -0,0 +1,80 @@+import { afterAll, describe, expect, test } from 'bun:test'++import { SkiaRenderer } from '@open-pencil/core'+import { initCanvasKit } from '@open-pencil/core/io'+import { SceneGraph } from '@open-pencil/scene-graph'++import { isolatesInnerShadows } from '#core/canvas/shadows'++import { expectDefined } from '#core-tests/helpers/assert'+import { expectFigmaRow, renderRow, type FigmaRowScene } from '#core-tests/helpers/figma-rows'++const ck = await initCanvasKit()+const renderer = new SkiaRenderer(ck, expectDefined(ck.MakeSurface(1, 1)))+afterAll(() => renderer.destroy())++const RED = { type: 'SOLID' as const, color: { r: 1, g: 0, b: 0, a: 1 }, visible: true }++const SHARP_INNER_SHADOW = {+ type: 'INNER_SHADOW' as const,+ radius: 0,+ spread: 6,+ offset: { x: 8, y: 8 },+ color: { r: 0, g: 0, b: 0, a: 1 },+ visible: true,+ blendMode: 'NORMAL' as const,+ showShadowBehindNode: false+}++function roundedSquare(opacity: number): FigmaRowScene {+ return (graph, hostId) =>+ graph.createNode('RECTANGLE', hostId, {+ x: 120,+ y: 70,+ width: 160,+ height: 160,+ cornerRadius: 40,+ fills: [{ ...RED, opacity }],+ effects: [SHARP_INNER_SHADOW]+ })+}++// Figma 126 paints the shadowed edge of a rounded rectangle in the shadow alone, at the edge's+// coverage and at full strength over a translucent fill: row 90 from x 119 to 139 of its export.+const FIGMA_RED = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]+const FIGMA_ALPHA = [0, 0, 0, 223, 255, 255, 255, 255, 255, 255, 255]++describe('an inner shadow over a rounded edge', () => {+ for (const opacity of [1, 0.5]) {+ test(`shows none of a fill at ${opacity * 100}% through the edge`, () => {+ const scene = roundedSquare(opacity)+ expectFigmaRow(renderRow(ck, renderer, scene, 90, 119, 139, 0), FIGMA_RED)+ expectFigmaRow(renderRow(ck, renderer, scene, 90, 119, 139), FIGMA_ALPHA)+ })+ }+})++// A layer of their own would blend a fill with nothing under it, so blended fills stay in place.+describe('fills and inner shadows take a layer of their own', () => {+ function vector(blendMode: 'NORMAL' | 'MULTIPLY') {+ const graph = new SceneGraph()+ return graph.createNode('VECTOR', graph.getPages()[0].id, {+ width: 100,+ height: 100,+ fills: [{ ...RED, opacity: 1 }],+ fillGeometry: [+ {+ windingRule: 'NONZERO',+ commandsBlob: new Uint8Array(),+ fills: [{ ...RED, opacity: 1, blendMode }]+ }+ ],+ effects: [SHARP_INNER_SHADOW]+ })+ }++ test('unless a path of a vector fills with a blend', () => {+ expect(isolatesInnerShadows(vector('NORMAL'))).toBe(true)+ expect(isolatesInnerShadows(vector('MULTIPLY'))).toBe(false)+ })+})diff --git a/tests/e2e/canvas/blur-effects-visual.spec.ts-snapshots/blur-effects-openpencil-darwin.png b/tests/e2e/canvas/blur-effects-visual.spec.ts-snapshots/blur-effects-openpencil-darwin.pngindex 4a89ee5cf..237b26270 100644Binary files a/tests/e2e/canvas/blur-effects-visual.spec.ts-snapshots/blur-effects-openpencil-darwin.png and b/tests/e2e/canvas/blur-effects-visual.spec.ts-snapshots/blur-effects-openpencil-darwin.png differdiff --git a/tests/helpers/canvas/effects/scene.ts b/tests/helpers/canvas/effects/scene.tsindex 62b6424d5..b7af6b45d 100644--- a/tests/helpers/canvas/effects/scene.ts+++ b/tests/helpers/canvas/effects/scene.ts@@ -22,7 +22,9 @@ function effect(type: Effect['type'], radius: number, y = 0): Effect {/*** Layer blur, drop and inner shadow, and background blur, each at a 16px radius, plus a drop- * shadow, shown behind the node, under a fill at 0% opacity, which casts nothing.+ * shadow, shown behind the node, under a fill at 0% opacity, which casts nothing; a boolean's+ * background blur, inside its result alone; and sharp inner shadows over the rounded corners of+ * an opaque and a translucent fill, where no fill shows through the edge.*/export function createBlurEffectsScene(graph: SceneGraph, pageId: string): void {const card = { y: 100, width: 120, height: 120, cornerRadius: 20 }@@ -85,6 +87,50 @@ export function createBlurEffectsScene(graph: SceneGraph, pageId: string): void}]})+ for (const [index, color] of [+ [0.96, 0.35, 0.35],+ [0.08, 0.73, 0.73],+ [0.23, 0.51, 0.96]+ ].entries()) {+ graph.createNode('RECTANGLE', pageId, {+ name: `Union stripe ${index + 1}`,+ x: 260 + index * 40,+ y: 280,+ width: 40,+ height: 120,+ fills: [solid(color[0], color[1], color[2])]+ })+ }+ const union = graph.createNode('BOOLEAN_OPERATION', pageId, {+ name: 'Union background blur',+ x: 260,+ y: 280,+ width: 120,+ height: 120,+ booleanOperation: 'UNION',+ fills: [solid(1, 1, 1, 0.2)],+ effects: [effect('BACKGROUND_BLUR', 16)]+ })+ graph.createNode('ELLIPSE', union.id, { width: 70, height: 70 })+ graph.createNode('ELLIPSE', union.id, { x: 50, y: 50, width: 70, height: 70 })+ for (const [index, opacity] of [1, 0.5].entries()) {+ graph.createNode('RECTANGLE', pageId, {+ name: `Rounded inner shadow ${opacity * 100}%`,+ x: 440 + index * 180,+ ...card,+ y: 280,+ cornerRadius: 40,+ fills: [solid(0.96, 0.35, 0.35, opacity)],+ effects: [+ {+ ...effect('INNER_SHADOW', 0),+ spread: 6,+ offset: { x: 8, y: 8 },+ color: { r: 0, g: 0, b: 0, a: 1 }+ }+ ]+ })+ }}function shadow(type: 'DROP_SHADOW' | 'INNER_SHADOW', showShadowBehindNode = false): Effect {