Skip to content

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

fix(canvas): cast shadows from what each layer draws, as in Figma (#1290)

Danila Poyarkova7452a4127c6
diff --git a/changes/1290/fixed.md b/changes/1290/fixed.md
new file mode 100644
index 000000000..1b34989bf
--- /dev/null
+++ b/changes/1290/fixed.md
@@ -0,0 +1,2 @@
+- Drop and inner shadows are cast from everything a layer draws, as in Figma: its strokes, every child of a frame or group, and boolean operations, cut out under translucent fills and strokes unless shown behind the node, with a shape's inner shadow under its strokes.
+- Strokes with sides of their own weights are drawn as one ring, as in Figma: corners are filled and rounded by their sides, dashes are spaced side by side, and translucent strokes no longer darken where the sides meet.
diff --git a/packages/core/AGENTS.md b/packages/core/AGENTS.md
index 043a79ab7..36b4aec45 100644
--- a/packages/core/AGENTS.md
+++ b/packages/core/AGENTS.md
@@ -74,6 +74,7 @@ Canvas is CanvasKit (Skia WASM) on a WebGL surface, not DOM.
- A gradient or image paint builds a Skia shader through `applyGradientFill` and `applyImageFill` (`packages/core/src/canvas/fills.ts`), which take the target `Paint`, so a stroke reuses them instead of a second shader path.
- `forVisibleStrokes` (`packages/core/src/canvas/scene.ts`) is where a stroke's shader is set and cleared; stroke draw helpers take an already-configured `strokePaint` and must not reset its shader.
+- Shadows are cast from what a layer draws, children included, through `drawSilhouette` (`packages/core/src/canvas/shadows/silhouette.ts`); a container's shadows are drawn by `renderLayerShadows` around its children, not by `renderShape`. A faster path for a shape must give the same pixels as its silhouette (`packages/core/tests/canvas/shadows.test.ts`).
### Caches
diff --git a/packages/core/src/canvas/boolean.ts b/packages/core/src/canvas/boolean.ts
index 45389bc27..817f331e9 100644
--- a/packages/core/src/canvas/boolean.ts
+++ b/packages/core/src/canvas/boolean.ts
@@ -319,11 +319,13 @@ export function groupFitOptions(r: SkiaRenderer | null, graph: SceneGraph): Grou
return r ? { booleanBounds: booleanResultBounds(r, graph) } : {}
}
-export function renderBooleanOperation(
+/** Draws the operation's fills and strokes, without its effects. */
+export function paintBooleanOperation(
r: SkiaRenderer,
canvas: Canvas,
node: SceneNode,
- graph: SceneGraph
+ graph: SceneGraph,
+ between?: () => void
): void {
const path = makeBooleanOperationPath(r, node, graph)
if (!path) return
@@ -339,6 +341,7 @@ export function renderBooleanOperation(
r.fillPaint.setShader(null)
}
}
+ between?.()
for (const stroke of node.strokes) {
if (!stroke.visible) continue
@@ -352,3 +355,18 @@ export function renderBooleanOperation(
path.delete()
}
}
+
+/** Draws a boolean operation with its shadows: inner shadows sit over its fills, under strokes. */
+export function renderBooleanOperation(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ node: SceneNode,
+ graph: SceneGraph
+): void {
+ const rect = r.ck.LTRBRect(0, 0, node.width, node.height)
+ r.renderEffects(canvas, node, graph, rect, false, 'behind')
+ paintBooleanOperation(r, canvas, node, graph, () =>
+ r.renderEffects(canvas, node, graph, rect, false, 'inner')
+ )
+ r.renderEffects(canvas, node, graph, rect, false, 'front')
+}
diff --git a/packages/core/src/canvas/effects.ts b/packages/core/src/canvas/effects.ts
index 26428f0bb..cac044482 100644
--- a/packages/core/src/canvas/effects.ts
+++ b/packages/core/src/canvas/effects.ts
@@ -1,6 +1,10 @@
import type { Canvas, ImageFilter, MaskFilter } from 'canvaskit-wasm'
+import { readEffectiveFigmaRawField } from '@open-pencil/fig'
import type { SceneNode } from '@open-pencil/scene-graph'
+import type { Color, Vector } from '@open-pencil/scene-graph/primitives'
+
+import { BLACK } from '#core/constants'
import type { SkiaRenderer } from './renderer'
@@ -81,3 +85,85 @@ export function applyClippedBlur(
r.effectLayerPaint.setBlendMode(r.ck.BlendMode.SrcOver)
canvas.restore()
}
+
+const MAX_RAW_NOISE_CELLS = 12_000
+
+interface RawNoiseEffect {
+ type: 'NOISE'
+ visible?: boolean
+ color?: Color
+ secondaryColor?: Color
+ opacity?: number
+ density?: number
+ noiseSize?: Vector
+ noiseType?: 'MONOTONE' | 'DUOTONE' | 'MULTITONE'
+}
+
+function rawNoiseEffects(node: SceneNode): RawNoiseEffect[] {
+ const source = (node as Partial<SceneNode>).source
+ const effects = source ? readEffectiveFigmaRawField(node, 'effects') : undefined
+ if (!Array.isArray(effects)) return []
+ return effects.filter(
+ (effect): effect is RawNoiseEffect =>
+ effect !== null &&
+ typeof effect === 'object' &&
+ 'type' in effect &&
+ effect.type === 'NOISE' &&
+ ('visible' in effect ? effect.visible !== false : true)
+ )
+}
+
+function seededNoise(seed: number): number {
+ const x = Math.sin(seed * 12.9898) * 43758.5453
+ return x - Math.floor(x)
+}
+
+function renderNoiseEffect(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ node: SceneNode,
+ rect: Float32Array,
+ hasRadius: boolean,
+ effect: RawNoiseEffect
+): void {
+ const density = Math.max(0, Math.min(1, effect.density ?? 0.3))
+ const requestedStep = Math.max(2, Math.round((effect.noiseSize?.x ?? 0.5) * 8))
+ const boundedStep = Math.ceil(Math.sqrt((node.width * node.height) / MAX_RAW_NOISE_CELLS))
+ const step = Math.max(requestedStep, boundedStep)
+ const color = effect.color ?? BLACK
+ const opacity = effect.opacity ?? color.a
+ const paint = new r.ck.Paint()
+ try {
+ paint.setAntiAlias(false)
+ canvas.save()
+ r.clipNodeShape(canvas, node, rect, hasRadius)
+ for (let y = 0; y < node.height; y += step) {
+ for (let x = 0; x < node.width; x += step) {
+ const value = seededNoise((x + 1) * 73856093 + (y + 1) * 19349663)
+ if (value > density) continue
+ const alpha = Math.max(0, Math.min(1, opacity * (0.35 + value * 0.65)))
+ paint.setColor(r.ck.Color4f(color.r, color.g, color.b, alpha))
+ canvas.drawRect(
+ r.ck.LTRBRect(x, y, Math.min(node.width, x + 1), Math.min(node.height, y + 1)),
+ paint
+ )
+ }
+ }
+ canvas.restore()
+ } finally {
+ paint.delete()
+ }
+}
+
+/** Draws the raw Figma noise effects a node carries, which the scene graph does not model. */
+export function renderNoiseEffects(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ node: SceneNode,
+ rect: Float32Array,
+ hasRadius: boolean
+): void {
+ for (const effect of rawNoiseEffects(node)) {
+ renderNoiseEffect(r, canvas, node, rect, hasRadius, effect)
+ }
+}
diff --git a/packages/core/src/canvas/renderer.ts b/packages/core/src/canvas/renderer.ts
index 491166e40..7f497a4c6 100644
--- a/packages/core/src/canvas/renderer.ts
+++ b/packages/core/src/canvas/renderer.ts
@@ -39,6 +39,7 @@ import { initializeRendererPaints, initializeSelectionPaintColors } from './rend
import * as RenderPipeline from './renderer/pipeline'
import type { SceneBacking, SceneBackingBuild } from './renderer/retained-backing/types'
import * as RendererState from './renderer/state'
+import type { EffectPass } from './shadows'
import * as RenderText from './text'
import type { SavedDecorationCache } from './text/decorations'
import { createDerivedGlyphPathCache, createGlyphSilhouetteCache } from './text/derived'
@@ -184,7 +185,6 @@ export class SkiaRenderer {
lastSceneViewport: { panX: number; panY: number; zoom: number } | null = null
nodePictureCache = new Map<string, SkPicture | null>()
nodePictureCacheGenerations = new Map<string, number>()
- nodePictureCacheDependencies = new Map<string, readonly string[]>()
effectRasterCache = new EffectRasterCache()
subtreePictureCache = new Map<string, SubtreePictureCacheEntry>()
subtreePictureCachePageId: string | null = null
@@ -367,13 +367,14 @@ export class SkiaRenderer {
declare renderComponentSet: (canvas: Canvas, node: SceneNode, graph: SceneGraph) => void
declare renderShape: (canvas: Canvas, node: SceneNode, graph: SceneGraph) => void
declare renderShapeUncached: (canvas: Canvas, node: SceneNode, graph: SceneGraph) => void
+ declare paintShapeContent: (canvas: Canvas, node: SceneNode, graph: SceneGraph) => void
declare renderEffects: (
canvas: Canvas,
node: SceneNode,
+ graph: SceneGraph,
rect: Float32Array,
hasRadius: boolean,
- pass: 'behind' | 'front',
- shadowShapeChild?: SceneNode | null
+ pass: EffectPass
) => void
declare renderText: (canvas: Canvas, node: SceneNode, fill?: Fill) => void
declare drawNodeFill: (
@@ -406,11 +407,7 @@ export class SkiaRenderer {
node: SceneNode,
stroke: Stroke
) => void
- declare drawIndividualSideStrokes: (
- canvas: Canvas,
- node: SceneNode,
- align: 'INSIDE' | 'CENTER' | 'OUTSIDE'
- ) => void
+ declare drawIndividualSideStrokes: (canvas: Canvas, node: SceneNode, stroke: Stroke) => void
declare strokeNodeShape: (canvas: Canvas, node: SceneNode, paint: Paint) => void
declare makeNodeShapePath: (node: SceneNode, rect: Float32Array, hasRadius: boolean) => Path
declare makePolygonPath: (node: SceneNode) => Path
diff --git a/packages/core/src/canvas/renderer/effect-raster-cache.ts b/packages/core/src/canvas/renderer/effect-raster-cache.ts
index 435e06fc3..f6c75f34d 100644
--- a/packages/core/src/canvas/renderer/effect-raster-cache.ts
+++ b/packages/core/src/canvas/renderer/effect-raster-cache.ts
@@ -11,7 +11,6 @@ export interface EffectRasterCacheEntry {
scale: number
pixels: number
fontGeneration: number
- dependencyIds: readonly string[]
}
const MAX_EFFECT_RASTER_CACHE_PIXELS = 24_000_000
@@ -30,10 +29,6 @@ export class EffectRasterCache extends ResourceCache<string, EffectRasterCacheEn
dispose: (entry) => entry.image.delete()
})
}
-
- deleteDependencies(nodeId: string): void {
- this.deleteWhere((entry) => entry.dependencyIds.includes(nodeId))
- }
}
export function effectRasterScale(targetScale: number): number {
diff --git a/packages/core/src/canvas/renderer/methods.ts b/packages/core/src/canvas/renderer/methods.ts
index 7e9c5d303..be61c51be 100644
--- a/packages/core/src/canvas/renderer/methods.ts
+++ b/packages/core/src/canvas/renderer/methods.ts
@@ -16,9 +16,10 @@ import type { SkiaRenderer } from '#core/canvas/renderer'
import type { PresenceCursor, RenderOverlays } from '#core/canvas/renderer/types'
import * as Rulers from '#core/canvas/rulers'
import * as SceneRender from '#core/canvas/scene'
-import { renderEffects as renderShadowEffects } from '#core/canvas/shadows'
+import { type EffectPass, renderEffects as renderShadowEffects } from '#core/canvas/shadows'
import * as Shapes from '#core/canvas/shapes'
import * as Strokes from '#core/canvas/strokes'
+import { drawIndividualSideStrokes } from '#core/canvas/strokes/sides'
import type { TextEditor } from '#core/text/editor'
const rendererMethods: ThisType<SkiaRenderer> = {
@@ -246,15 +247,19 @@ const rendererMethods: ThisType<SkiaRenderer> = {
SceneRender.renderShapeUncached(this, canvas, node, graph)
},
+ paintShapeContent(canvas: Canvas, node: SceneNode, graph: SceneGraph): void {
+ SceneRender.paintShapeContent(this, canvas, node, graph)
+ },
+
renderEffects(
canvas: Canvas,
node: SceneNode,
+ graph: SceneGraph,
rect: Float32Array,
hasRadius: boolean,
- pass: 'behind' | 'front',
- shadowShapeChild?: SceneNode | null
+ pass: EffectPass
): void {
- renderShadowEffects(this, canvas, node, rect, hasRadius, pass, shadowShapeChild)
+ renderShadowEffects(this, canvas, node, graph, rect, hasRadius, pass)
},
renderText(canvas: Canvas, node: SceneNode, fill?: Fill): void {
@@ -310,12 +315,8 @@ const rendererMethods: ThisType<SkiaRenderer> = {
Strokes.drawRRectStrokeWithAlign(this, canvas, rrect, node, stroke)
},
- drawIndividualSideStrokes(
- canvas: Canvas,
- node: SceneNode,
- align: 'INSIDE' | 'CENTER' | 'OUTSIDE'
- ): void {
- Strokes.drawIndividualSideStrokes(this, canvas, node, align)
+ drawIndividualSideStrokes(canvas: Canvas, node: SceneNode, stroke: Stroke): void {
+ drawIndividualSideStrokes(this, canvas, node, stroke)
},
strokeNodeShape(canvas: Canvas, node: SceneNode, paint: Paint): void {
diff --git a/packages/core/src/canvas/renderer/state.ts b/packages/core/src/canvas/renderer/state.ts
index 8f4bc2851..58413f067 100644
--- a/packages/core/src/canvas/renderer/state.ts
+++ b/packages/core/src/canvas/renderer/state.ts
@@ -30,7 +30,6 @@ export function invalidateAllPictures(r: SkiaRenderer): void {
for (const pic of r.nodePictureCache.values()) pic?.delete()
r.nodePictureCache.clear()
r.nodePictureCacheGenerations.clear()
- r.nodePictureCacheDependencies.clear()
r.effectRasterCache.clear()
clearSubtreePictureCache(r)
}
@@ -44,20 +43,11 @@ export function invalidateNodePicture(
keepShaping: changedKeys !== undefined && !changesShaping(changedKeys)
})
r.effectRasterCache.delete(nodeId)
- r.effectRasterCache.deleteDependencies(nodeId)
- for (const [ownerId, dependencyIds] of r.nodePictureCacheDependencies) {
- if (!dependencyIds.includes(nodeId)) continue
- r.nodePictureCache.get(ownerId)?.delete()
- r.nodePictureCache.delete(ownerId)
- r.nodePictureCacheGenerations.delete(ownerId)
- r.nodePictureCacheDependencies.delete(ownerId)
- }
const pic = r.nodePictureCache.get(nodeId)
if (pic) {
pic.delete()
r.nodePictureCache.delete(nodeId)
r.nodePictureCacheGenerations.delete(nodeId)
- r.nodePictureCacheDependencies.delete(nodeId)
}
const subtree = r.subtreePictureCache.get(nodeId)
if (subtree) {
diff --git a/packages/core/src/canvas/scene.ts b/packages/core/src/canvas/scene.ts
index e57e96df6..dbcf19445 100644
--- a/packages/core/src/canvas/scene.ts
+++ b/packages/core/src/canvas/scene.ts
@@ -37,7 +37,8 @@ import {
effectRasterScale,
effectRasterScaleMatches
} from './renderer/effect-raster-cache'
-import { paintCastsShadow } from './shadows'
+import { renderLayerShadows } from './shadows'
+import { isLayerContainer } from './shadows/silhouette'
import { makeSmoothRRectPath, nodeHasRadius, nodeHasSmoothCorners } from './shapes'
import {
configureStrokePaint,
@@ -406,6 +407,7 @@ export function renderNode(
}
applyNodeTransforms(canvas, node, overlays)
+ renderLayerShadows(r, canvas, graph, node, 'behind')
renderNodeContent(r, canvas, graph, node, overlays)
drawLayoutGrids(r, canvas, node)
renderChildren(
@@ -418,6 +420,7 @@ export function renderNode(
absY,
hasTransformedAncestor || hasNodeTransform(projectedNode(node, overlays.rotationPreview))
)
+ renderLayerShadows(r, canvas, graph, node, 'front')
if (layerBlur) {
canvas.restore()
@@ -484,7 +487,7 @@ export function renderSection(
forVisibleStrokes(r, node, graph, (stroke, color) => {
configureStrokePaint(r, node, stroke, color)
- if (node.independentStrokeWeights) r.drawIndividualSideStrokes(canvas, node, stroke.align)
+ if (node.independentStrokeWeights) r.drawIndividualSideStrokes(canvas, node, stroke)
else r.drawRRectStrokeWithAlign(canvas, rrect, node, stroke)
})
}
@@ -516,8 +519,18 @@ export function renderComponentSet(
})
}
+/** The effects `renderShape` draws: a container's shadows are drawn around its children instead. */
+function shapeEffects(node: SceneNode): SceneNode['effects'] {
+ const ownShadows = !isLayerContainer(node)
+ return node.effects.filter(
+ (effect) =>
+ effect.visible &&
+ (ownShadows || (effect.type !== 'DROP_SHADOW' && effect.type !== 'INNER_SHADOW'))
+ )
+}
+
function canRasterCacheEffects(node: SceneNode): boolean {
- const visibleEffects = node.effects.filter((effect) => effect.visible)
+ const visibleEffects = shapeEffects(node)
return (
visibleEffects.length > 0 &&
visibleEffects.every(
@@ -532,7 +545,7 @@ export function renderShape(
node: SceneNode,
graph: SceneGraph
): void {
- const hasEffects = node.effects.some((effect) => effect.visible)
+ const hasEffects = shapeEffects(node).length > 0
if (r.viewportImageRendering || !hasEffects) {
r.renderShapeUncached(canvas, node, graph)
return
@@ -595,8 +608,7 @@ export function renderShape(
height,
scale,
pixels: image.width() * image.height(),
- fontGeneration: r.fontGeneration,
- dependencyIds: node.childIds.slice(0, 1)
+ fontGeneration: r.fontGeneration
})
try {
canvas.drawImageRectOptions(
@@ -625,7 +637,6 @@ export function renderShape(
if (cached) cached.delete()
r.nodePictureCache.delete(node.id)
r.nodePictureCacheGenerations.delete(node.id)
- r.nodePictureCacheDependencies.delete(node.id)
const bounds = r.ck.LTRBRect(-margin, -margin, node.width + margin, node.height + margin)
const recorder = new r.ck.PictureRecorder()
@@ -635,23 +646,12 @@ export function renderShape(
const picture = recorder.finishRecordingAsPicture()
r.nodePictureCache.set(node.id, picture)
r.nodePictureCacheGenerations.set(node.id, r.fontGeneration)
- const shadowChild = getShadowShapeChild(node, graph)
- r.nodePictureCacheDependencies.set(node.id, shadowChild ? [shadowChild.id] : [])
canvas.drawPicture(picture)
} finally {
recorder.delete()
}
}
-function getShadowShapeChild(node: SceneNode, graph: SceneGraph): SceneNode | null {
- if (node.fills.some(paintCastsShadow)) return null
- if (node.strokes.some(paintCastsShadow)) return null
- if (node.childIds.length === 0) return null
- const child = graph.getNode(node.childIds[0])
- if (!child?.visible) return null
- return child
-}
-
function drawVectorStrokeGeometry(
r: SkiaRenderer,
canvas: Canvas,
@@ -750,14 +750,11 @@ function drawRegularStroke(
sc: Color
): void {
configureStrokePaint(r, node, stroke, sc)
- if (stroke.dashPattern && stroke.dashPattern.length > 0) {
- r.strokePaint.setPathEffect(r.ck.PathEffect.MakeDash(stroke.dashPattern, 0))
- } else {
- r.strokePaint.setPathEffect(null)
- }
+ const dash = normalizeDashPattern(stroke.dashPattern)
+ r.strokePaint.setPathEffect(dash.length > 0 ? r.ck.PathEffect.MakeDash(dash, 0) : null)
if (node.independentStrokeWeights && r.isRectangularType(node.type)) {
- r.drawIndividualSideStrokes(canvas, node, stroke.align)
+ r.drawIndividualSideStrokes(canvas, node, stroke)
} else {
r.drawStrokeWithAlign(canvas, node, rect, hasRadius, stroke.align)
}
@@ -895,6 +892,7 @@ function paintNodeStrokes(
})
}
+/** Draws a shape with its own effects: Figma puts inner shadows over fills and under strokes. */
export function renderShapeUncached(
r: SkiaRenderer,
canvas: Canvas,
@@ -903,10 +901,23 @@ export function renderShapeUncached(
): void {
const rect = r.ck.LTRBRect(0, 0, node.width, node.height)
const hasRadius = nodeHasRadius(node)
+ r.renderEffects(canvas, node, graph, rect, hasRadius, 'behind')
+ paintShapeContent(r, canvas, node, graph, () =>
+ r.renderEffects(canvas, node, graph, rect, hasRadius, 'inner')
+ )
+ r.renderEffects(canvas, node, graph, rect, hasRadius, 'front')
+}
- const shadowChild = getShadowShapeChild(node, graph)
- r.renderEffects(canvas, node, rect, hasRadius, 'behind', shadowChild)
-
+/** Draws a shape's fills and strokes without its effects; `afterFills` runs between the two. */
+export function paintShapeContent(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ node: SceneNode,
+ graph: SceneGraph,
+ afterFills?: () => void
+): void {
+ const rect = r.ck.LTRBRect(0, 0, node.width, node.height)
+ const hasRadius = nodeHasRadius(node)
const sg = node.strokeGeometry.length > 0 ? r.getStrokeGeometry(node) : null
const vectorPaths = node.type === 'VECTOR' ? r.getVectorPaths(node) : null
const vectorStroke = node.type === 'VECTOR' ? vectorStrokePaths(r, node) : null
@@ -926,11 +937,11 @@ export function renderShapeUncached(
drawVisibleFills(r, node, graph, (fill) => r.drawNodeFill(canvas, node, rect, hasRadius, fill))
}
if (node.type === 'TEXT') drawTextEmoji(r, canvas, node)
+ afterFills?.()
if (!pathTextStrokeFirst && !reflowedPathText) {
paintNodeStrokes(r, canvas, node, graph, rect, hasRadius, sg, vectorPaths, vectorStroke)
}
- r.renderEffects(canvas, node, rect, hasRadius, 'front', shadowChild)
}
function hasComplexTextFill(fill?: Fill): boolean {
diff --git a/packages/core/src/canvas/shadows.ts b/packages/core/src/canvas/shadows.ts
index 1a337fa39..b9ff96a17 100644
--- a/packages/core/src/canvas/shadows.ts
+++ b/packages/core/src/canvas/shadows.ts
@@ -1,356 +1,234 @@
-import type { Canvas, Path } from 'canvaskit-wasm'
+import type { BlendMode, Canvas, ImageFilter } from 'canvaskit-wasm'
-import { readEffectiveFigmaRawField } from '@open-pencil/fig'
-import type { Fill, SceneNode } from '@open-pencil/scene-graph'
-import type { Color, Vector } from '@open-pencil/scene-graph/primitives'
-
-import { BLACK } from '#core/constants'
+import type { Effect, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { figmaBlendModeToSkia } from './blend'
-import { blurSigma } from './effects'
+import { blurSigma, renderNoiseEffects } from './effects'
import type { SkiaRenderer } from './renderer'
import {
- makeNodeShapePath,
- makeSmoothRRectPath,
- nodeHasRadius,
- nodeHasSmoothCorners
-} from './shapes'
-
-const MAX_RAW_NOISE_CELLS = 12_000
-
-interface RawNoiseEffect {
- type: 'NOISE'
- visible?: boolean
- color?: Color
- secondaryColor?: Color
- opacity?: number
- density?: number
- noiseSize?: Vector
- noiseType?: 'MONOTONE' | 'DUOTONE' | 'MULTITONE'
-}
-
+ castsFromOwnShape,
+ clipOutShapeKnockout,
+ drawOutlineDropShadow,
+ drawRingDropShadow,
+ drawShapeDropShadow,
+ drawShapeInnerShadow,
+ regularStrokeOutline,
+ strokeGrowsOutline
+} from './shadows/shape'
+import {
+ drawSilhouette,
+ fillsCastShadow,
+ isLayerContainer,
+ paintsCastShadow,
+ paintsOverKnockout,
+ shadowIncludesChildren,
+ silhouetteBounds,
+ soleShadowChild
+} from './shadows/silhouette'
+import { nodeHasRadius } from './shapes'
function resetEffectLayerPaint(r: SkiaRenderer): void {
r.effectLayerPaint.setImageFilter(null)
r.effectLayerPaint.setColorFilter(null)
r.effectLayerPaint.setBlendMode(r.ck.BlendMode.SrcOver)
}
-function rawNoiseEffects(node: SceneNode): RawNoiseEffect[] {
- const source = (node as Partial<SceneNode>).source
- const effects = source ? readEffectiveFigmaRawField(node, 'effects') : undefined
- if (!Array.isArray(effects)) return []
- return effects.filter(
- (effect): effect is RawNoiseEffect =>
- effect !== null &&
- typeof effect === 'object' &&
- 'type' in effect &&
- effect.type === 'NOISE' &&
- ('visible' in effect ? effect.visible !== false : true)
- )
-}
+/** `behind` draws drop shadows and background blur, `inner` inner shadows over fills, `front` noise. */
+export type EffectPass = 'behind' | 'inner' | 'front'
-function seededNoise(seed: number): number {
- const x = Math.sin(seed * 12.9898) * 43758.5453
- return x - Math.floor(x)
+/** Figma spreads a shadow only where it follows the layer's own outline: shapes and filled frames that clip. */
+function shadowSpread(node: SceneNode, effect: Effect): number {
+ if (node.type === 'TEXT' || node.type === 'BOOLEAN_OPERATION') return 0
+ if (!isLayerContainer(node)) return effect.spread
+ return node.clipsContent && fillsCastShadow(node) ? effect.spread : 0
}
-function renderNoiseEffect(
+function shadowLayerBounds(
r: SkiaRenderer,
- canvas: Canvas,
+ graph: SceneGraph,
node: SceneNode,
- rect: Float32Array,
- hasRadius: boolean,
- effect: RawNoiseEffect
-): void {
- const density = Math.max(0, Math.min(1, effect.density ?? 0.3))
- const requestedStep = Math.max(2, Math.round((effect.noiseSize?.x ?? 0.5) * 8))
- const boundedStep = Math.ceil(Math.sqrt((node.width * node.height) / MAX_RAW_NOISE_CELLS))
- const step = Math.max(requestedStep, boundedStep)
- const color = effect.color ?? BLACK
- const opacity = effect.opacity ?? color.a
- const paint = new r.ck.Paint()
- try {
- paint.setAntiAlias(false)
- canvas.save()
- r.clipNodeShape(canvas, node, rect, hasRadius)
- for (let y = 0; y < node.height; y += step) {
- for (let x = 0; x < node.width; x += step) {
- const value = seededNoise((x + 1) * 73856093 + (y + 1) * 19349663)
- if (value > density) continue
- const alpha = Math.max(0, Math.min(1, opacity * (0.35 + value * 0.65)))
- paint.setColor(r.ck.Color4f(color.r, color.g, color.b, alpha))
- canvas.drawRect(
- r.ck.LTRBRect(x, y, Math.min(node.width, x + 1), Math.min(node.height, y + 1)),
- paint
- )
- }
- }
- canvas.restore()
- } finally {
- paint.delete()
- }
-}
-
-function drawChildTransform(canvas: Canvas, child: SceneNode, offset = { x: 0, y: 0 }): void {
- canvas.translate(child.x + offset.x, child.y + offset.y)
- if (child.rotation !== 0) {
- canvas.rotate(child.rotation, child.width / 2, child.height / 2)
- }
- if (child.flipX || child.flipY) {
- canvas.translate(child.flipX ? child.width : 0, child.flipY ? child.height : 0)
- canvas.scale(child.flipX ? -1 : 1, child.flipY ? -1 : 1)
- }
-}
-
-function localEffectOffset(effect: SceneNode['effects'][number], child?: SceneNode | null) {
- let x = effect.offset.x
- let y = effect.offset.y
- if (!child) return { x, y }
-
- const rotation = child.rotation
- if (rotation !== 0) {
- const rad = (-rotation * Math.PI) / 180
- const cos = Math.cos(rad)
- const sin = Math.sin(rad)
- const nx = x * cos - y * sin
- const ny = x * sin + y * cos
- x = nx
- y = ny
- }
- if (child.flipX) x = -x
- if (child.flipY) y = -y
- return { x, y }
-}
-
-function isPathShape(node: SceneNode): boolean {
- return node.type === 'POLYGON' || node.type === 'STAR' || node.type === 'VECTOR'
-}
-
-function effectLayerBounds(
- r: SkiaRenderer,
- node: SceneNode,
- effect: SceneNode['effects'][number],
- extraPadding = 0
+ effect: Effect,
+ spread: number,
+ includeChildren: boolean
): Float32Array {
+ const box = silhouetteBounds(graph, node, includeChildren) ?? {
+ x: 0,
+ y: 0,
+ width: node.width,
+ height: node.height
+ }
const offset = effect.offset
- const padding = Math.max(effect.radius * 2, Math.abs(effect.spread)) + extraPadding
+ const padding = effect.radius * 2 + Math.abs(spread)
return r.ck.LTRBRect(
- Math.min(0, offset.x) - padding,
- Math.min(0, offset.y) - padding,
- Math.max(node.width, node.width + offset.x) + padding,
- Math.max(node.height, node.height + offset.y) + padding
+ box.x + Math.min(0, offset.x) - padding,
+ box.y + Math.min(0, offset.y) - padding,
+ box.x + box.width + Math.max(0, offset.x) + padding,
+ box.y + box.height + Math.max(0, offset.y) + padding
)
}
-function pathWithSpread(r: SkiaRenderer, path: Path, spread: number): Path | null {
- if (spread === 0) return path.copy()
- const ring = path.makeStroked({ width: Math.abs(spread) * 2, join: r.ck.StrokeJoin.Round })
- if (!ring) return null
- const result = r.ck.Path.MakeFromOp(
- path,
- ring,
- spread > 0 ? r.ck.PathOp.Union : r.ck.PathOp.Difference
- )
- ring.delete()
- return result
+/** Grows or shrinks a silhouette by the spread, square as Figma spreads a rectangle. */
+function spreadFilter(r: SkiaRenderer, spread: number): ImageFilter | null {
+ if (spread > 0) return r.ck.ImageFilter.MakeDilate(spread, spread, null)
+ if (spread < 0) return r.ck.ImageFilter.MakeErode(-spread, -spread, null)
+ return null
}
-function drawPathShape(
+/** Draws a shadow cast by whatever `draw` paints: its alpha is the outline, offset and blurred. */
+function drawSilhouetteDropShadow(
r: SkiaRenderer,
canvas: Canvas,
- node: SceneNode,
- hasRadius: boolean,
- spread = 0
+ effect: Effect,
+ spread: number,
+ bounds: Float32Array,
+ blendMode: BlendMode,
+ draw: () => void
): void {
- const path = makeNodeShapePath(r, node, r.ltrb(0, 0, node.width, node.height), hasRadius)
- const spreadPath = pathWithSpread(r, path, spread)
- path.delete()
- if (!spreadPath) return
+ const ck = r.ck
+ const color = ck.Color4f(effect.color.r, effect.color.g, effect.color.b, effect.color.a)
+ const sigma = blurSigma(effect.radius)
+ const morphology = spreadFilter(r, spread)
+ const filter = morphology
+ ? ck.ImageFilter.MakeDropShadowOnly(
+ effect.offset.x,
+ effect.offset.y,
+ sigma,
+ sigma,
+ color,
+ morphology
+ )
+ : r.getCachedDropShadow(effect.offset.x, effect.offset.y, sigma, color)
+ const paint = new ck.Paint()
+ paint.setImageFilter(filter)
+ paint.setBlendMode(blendMode)
+ canvas.saveLayer(paint, bounds)
try {
- canvas.drawPath(spreadPath, r.auxFill)
+ draw()
} finally {
- spreadPath.delete()
+ canvas.restore()
+ paint.delete()
+ if (morphology) {
+ filter.delete()
+ morphology.delete()
+ }
}
}
-function drawShadowGeometryPath(r: SkiaRenderer, canvas: Canvas, path: Path, spread: number): void {
- if (spread === 0) {
- canvas.drawPath(path, r.auxFill)
- return
- }
- const spreadPath = pathWithSpread(r, path, spread)
- if (!spreadPath) return
+function drawKnockout(r: SkiaRenderer, canvas: Canvas, bounds: Float32Array, draw: () => void) {
+ const paint = new r.ck.Paint()
+ paint.setBlendMode(r.ck.BlendMode.DstOut)
+ canvas.saveLayer(paint, bounds)
try {
- canvas.drawPath(spreadPath, r.auxFill)
+ draw()
} finally {
- spreadPath.delete()
+ canvas.restore()
+ paint.delete()
}
}
-function drawShadowCutout(
+/**
+ * Draws a shadow cast by the node's own outline without a layer, when that outline is a shape
+ * grown by its stroke; false when the node needs its silhouette drawn instead.
+ */
+function drawOwnShapeDropShadow(
r: SkiaRenderer,
canvas: Canvas,
node: SceneNode,
- effect: SceneNode['effects'][number],
- shapeNode: SceneNode,
- shapeHasRadius: boolean,
- geometryShadow: Path[] | null
-): void {
- r.auxFill.setMaskFilter(null)
- r.auxFill.setColor(r.ck.BLACK)
- r.auxFill.setBlendMode(r.ck.BlendMode.DstOut)
+ effect: Effect,
+ spread: number,
+ blendMode: BlendMode,
+ knockout: boolean
+): boolean {
+ const outline = regularStrokeOutline(node, spread)
+ if (!outline && !castsFromOwnShape(node)) return false
+ const hasRadius = nodeHasRadius(node)
+ const castsFill = fillsCastShadow(node)
canvas.save()
try {
- canvas.translate(-effect.offset.x, -effect.offset.y)
- if (geometryShadow) {
- const fillGeometry = r.getFillGeometry(node)
- if (fillGeometry) for (const path of fillGeometry) canvas.drawPath(path, r.auxFill)
- } else if (shapeNode.type === 'ELLIPSE') {
- canvas.drawOval(r.ltrb(0, 0, shapeNode.width, shapeNode.height), r.auxFill)
- } else if (isPathShape(shapeNode)) {
- drawPathShape(r, canvas, shapeNode, shapeHasRadius)
- } else if (nodeHasSmoothCorners(shapeNode)) {
- const path = makeSmoothRRectPath(r, shapeNode)
- canvas.drawPath(path, r.auxFill)
- path.delete()
- } else if (shapeHasRadius) {
- canvas.drawRRect(r.makeRRect(shapeNode), r.auxFill)
- } else {
- canvas.drawRect(r.ltrb(0, 0, shapeNode.width, shapeNode.height), r.auxFill)
+ if (knockout) clipOutShapeKnockout(r, canvas, node, hasRadius, outline)
+ if (castsFill && outline && strokeGrowsOutline(outline)) {
+ drawOutlineDropShadow(r, canvas, node, effect, outline, spread, blendMode)
+ } else if (castsFill) {
+ drawShapeDropShadow(r, canvas, node, effect, hasRadius, spread, blendMode)
+ } else if (outline) {
+ drawRingDropShadow(r, canvas, node, effect, outline, spread, blendMode)
}
} finally {
canvas.restore()
- r.auxFill.setBlendMode(r.ck.BlendMode.SrcOver)
}
+ return true
}
-/**
- * Figma casts a full-strength shadow from any paint above 0% opacity and none from a paint at
- * 0% or a gradient whose stops are all transparent, so such a paint counts as no paint at all.
- */
-export function paintCastsShadow(paint: Fill): boolean {
- if (!paint.visible || paint.opacity === 0) return false
- return paint.gradientStops?.some((stop) => stop.color.a > 0) ?? true
-}
-
-function castsShadow(node: SceneNode, shadowShapeChild?: SceneNode | null): boolean {
- if (shadowShapeChild) return true
- return node.fills.some(paintCastsShadow) || node.strokes.some(paintCastsShadow)
-}
-
-function drawShapeDropShadow(
- r: SkiaRenderer,
- canvas: Canvas,
- node: SceneNode,
- effect: SceneNode['effects'][number],
- hasRadius: boolean,
- shadowShapeChild?: SceneNode | null
-): void {
- const sp = effect.spread
- const shapeNode = shadowShapeChild ?? node
- const shapeHasRadius = shadowShapeChild ? nodeHasRadius(shadowShapeChild) : hasRadius
- const hasCastingFill = node.fills.some(paintCastsShadow)
- let geometryShadow: Path[] | null = null
- if (!shadowShapeChild) {
- if (hasCastingFill) {
- geometryShadow = r.getFillGeometry(node)
- } else if (node.childIds.length === 0 && node.strokeGeometry.length > 0) {
- geometryShadow = r.getStrokeGeometry(node)
- }
- }
-
- r.auxFill.setColor(r.color4f(effect.color.r, effect.color.g, effect.color.b, effect.color.a))
- r.auxFill.setMaskFilter(r.getCachedMaskBlur(blurSigma(effect.radius)))
- r.auxFill.setImageFilter(null)
- r.auxFill.setBlendMode(figmaBlendModeToSkia(r.ck, effect.blendMode))
+/** Draws a shadow cast by `child`, in its parent's coordinates. */
+function withChildCoordinates<T>(canvas: Canvas, child: SceneNode, draw: () => T): T {
canvas.save()
- let savedLayer = false
try {
- if (shadowShapeChild) drawChildTransform(canvas, shadowShapeChild, effect.offset)
- else canvas.translate(effect.offset.x, effect.offset.y)
-
- const shouldHideShadowBehindUnfilledNode =
- effect.showShadowBehindNode === false && !hasCastingFill && !shadowShapeChild
- if (shouldHideShadowBehindUnfilledNode) {
- resetEffectLayerPaint(r)
- canvas.saveLayer(r.effectLayerPaint, effectLayerBounds(r, shapeNode, effect))
- savedLayer = true
- }
-
- if (geometryShadow) {
- for (const path of geometryShadow) drawShadowGeometryPath(r, canvas, path, sp)
- } else if (shapeNode.type === 'ELLIPSE') {
- canvas.drawOval(r.ltrb(-sp, -sp, shapeNode.width + sp, shapeNode.height + sp), r.auxFill)
- } else if (isPathShape(shapeNode)) {
- drawPathShape(r, canvas, shapeNode, shapeHasRadius, sp)
- } else if (nodeHasSmoothCorners(shapeNode)) {
- const path = makeSmoothRRectPath(r, shapeNode, sp)
- canvas.drawPath(path, r.auxFill)
- path.delete()
- } else if (shapeHasRadius) {
- canvas.drawRRect(r.makeRRectWithSpread(shapeNode, sp), r.auxFill)
- } else {
- canvas.drawRect(r.ltrb(-sp, -sp, shapeNode.width + sp, shapeNode.height + sp), r.auxFill)
- }
- if (shouldHideShadowBehindUnfilledNode) {
- drawShadowCutout(r, canvas, node, effect, shapeNode, shapeHasRadius, geometryShadow)
- }
+ canvas.translate(child.x, child.y)
+ return draw()
} finally {
- if (savedLayer) canvas.restore()
canvas.restore()
- r.auxFill.setMaskFilter(null)
- r.auxFill.setBlendMode(r.ck.BlendMode.SrcOver)
- resetEffectLayerPaint(r)
}
}
function renderDropShadow(
r: SkiaRenderer,
canvas: Canvas,
+ graph: SceneGraph,
node: SceneNode,
- effect: SceneNode['effects'][number],
- hasRadius: boolean,
- shadowShapeChild?: SceneNode | null
+ effect: Effect,
+ includeChildren: boolean
): void {
- resetEffectLayerPaint(r)
-
- const shapeNode = shadowShapeChild ?? node
- if (shapeNode.type !== 'TEXT') {
- if (!castsShadow(node, shadowShapeChild)) return
- drawShapeDropShadow(r, canvas, node, effect, hasRadius, shadowShapeChild)
- resetEffectLayerPaint(r)
- return
+ if (!includeChildren && !paintsCastShadow(node)) return
+ const spread = shadowSpread(node, effect)
+ 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, () =>
+ drawOwnShapeDropShadow(r, canvas, sole, effect, spread, blendMode, knockout)
+ )
+ : !includeChildren &&
+ drawOwnShapeDropShadow(r, canvas, node, effect, spread, blendMode, knockout)
+ if (drawnAlone) return
+
+ const bounds = shadowLayerBounds(r, graph, node, effect, spread, includeChildren)
+ const isolation = knockout ? new r.ck.Paint() : null
+ if (isolation) {
+ isolation.setBlendMode(blendMode)
+ canvas.saveLayer(isolation, bounds)
}
-
- const shadowColor = r.ck.Color4f(effect.color.r, effect.color.g, effect.color.b, effect.color.a)
- const dropFilter = r.getCachedDropShadow(0, 0, blurSigma(effect.radius), shadowColor)
-
- canvas.save()
- let savedLayer = false
try {
- if (shadowShapeChild) drawChildTransform(canvas, shadowShapeChild, effect.offset)
- else canvas.translate(effect.offset.x, effect.offset.y)
-
- r.effectLayerPaint.setBlendMode(figmaBlendModeToSkia(r.ck, effect.blendMode))
- r.effectLayerPaint.setImageFilter(dropFilter)
- canvas.saveLayer(r.effectLayerPaint, effectLayerBounds(r, shapeNode, effect))
- savedLayer = true
- r.renderText(canvas, shapeNode)
+ drawSilhouetteDropShadow(
+ r,
+ canvas,
+ effect,
+ spread,
+ bounds,
+ isolation ? r.ck.BlendMode.SrcOver : blendMode,
+ () => drawSilhouette(r, canvas, graph, node, 'cast', includeChildren)
+ )
+ if (knockout) {
+ drawKnockout(r, canvas, bounds, () =>
+ drawSilhouette(r, canvas, graph, node, 'knockout', includeChildren)
+ )
+ }
} finally {
- if (savedLayer) canvas.restore()
- canvas.restore()
+ if (isolation) {
+ canvas.restore()
+ isolation.delete()
+ }
resetEffectLayerPaint(r)
}
}
-function drawTextInnerShadow(
+/** Draws an inner shadow inside whatever `draw` paints, cut from an offset, blurred inverse of it. */
+function drawSilhouetteInnerShadow(
r: SkiaRenderer,
canvas: Canvas,
- _node: SceneNode,
- effect: SceneNode['effects'][number],
- shadowShapeChild?: SceneNode | null
+ effect: Effect,
+ bounds: Float32Array,
+ draw: () => void
): void {
- const shapeNode = shadowShapeChild ?? _node
const ck = r.ck
resetEffectLayerPaint(r)
@@ -359,14 +237,11 @@ function drawTextInnerShadow(
let solidBlackFilter: ReturnType<typeof ck.ColorFilter.MakeBlend> | null = null
try {
- canvas.save()
- restoreCount++
- if (shadowShapeChild) drawChildTransform(canvas, shadowShapeChild)
-
- const bounds = effectLayerBounds(r, shapeNode, effect)
+ r.effectLayerPaint.setBlendMode(figmaBlendModeToSkia(ck, effect.blendMode))
canvas.saveLayer(r.effectLayerPaint, bounds)
restoreCount++
- r.renderText(canvas, shapeNode)
+ r.effectLayerPaint.setBlendMode(ck.BlendMode.SrcOver)
+ draw()
r.effectLayerPaint.setBlendMode(ck.BlendMode.SrcIn)
tintFilter = ck.ColorFilter.MakeBlend(
@@ -377,26 +252,21 @@ function drawTextInnerShadow(
canvas.saveLayer(r.effectLayerPaint, bounds)
restoreCount++
- const { x: localOffsetX, y: localOffsetY } = localEffectOffset(effect, shadowShapeChild)
canvas.save()
restoreCount++
- canvas.translate(localOffsetX, localOffsetY)
+ canvas.translate(effect.offset.x, effect.offset.y)
+ // The inverse is drawn in offset coordinates, so it covers `bounds` once shifted back.
+ const { x: dx, y: dy } = effect.offset
+ const inverse = ck.LTRBRect(bounds[0] - dx, bounds[1] - dy, bounds[2] - dx, bounds[3] - dy)
r.effectLayerPaint.setBlendMode(ck.BlendMode.SrcOver)
r.effectLayerPaint.setColorFilter(null)
r.effectLayerPaint.setImageFilter(r.getCachedDecalBlur(blurSigma(effect.radius)))
- canvas.saveLayer(r.effectLayerPaint, bounds)
+ canvas.saveLayer(r.effectLayerPaint, inverse)
restoreCount++
- const expand = effect.radius * 2 + Math.max(Math.abs(localOffsetX), Math.abs(localOffsetY))
- const giantRect = ck.LTRBRect(
- -expand,
- -expand,
- shapeNode.width + expand,
- shapeNode.height + expand
- )
r.auxFill.setColor(ck.Color4f(0, 0, 0, 1))
- canvas.drawRect(giantRect, r.auxFill)
+ canvas.drawRect(inverse, r.auxFill)
r.effectLayerPaint.setImageFilter(null)
r.effectLayerPaint.setBlendMode(ck.BlendMode.DstOut)
@@ -404,7 +274,7 @@ function drawTextInnerShadow(
r.effectLayerPaint.setColorFilter(solidBlackFilter)
canvas.saveLayer(r.effectLayerPaint, bounds)
restoreCount++
- r.renderText(canvas, shapeNode)
+ draw()
} finally {
while (restoreCount > 0) {
canvas.restore()
@@ -417,155 +287,94 @@ function drawTextInnerShadow(
}
}
-function drawShapeInnerShadow(
+function renderInnerShadow(
r: SkiaRenderer,
canvas: Canvas,
+ graph: SceneGraph,
node: SceneNode,
rect: Float32Array,
- effect: SceneNode['effects'][number],
+ effect: Effect,
hasRadius: boolean,
- shadowShapeChild?: SceneNode | null
+ includeChildren: boolean
): void {
- const sp = effect.spread
- const shapeNode = shadowShapeChild ?? node
- r.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))
-
- const shapeRect = shadowShapeChild ? r.ck.LTRBRect(0, 0, shapeNode.width, shapeNode.height) : rect
- const shapeHasRadius = shadowShapeChild ? nodeHasRadius(shadowShapeChild) : hasRadius
-
- canvas.save()
- try {
- if (shadowShapeChild) drawChildTransform(canvas, shadowShapeChild)
-
- if (shapeNode.type === 'ELLIPSE') {
- const builder = new r.ck.PathBuilder()
- builder.addOval(shapeRect)
- const path = builder.detachAndDelete()
- try {
- canvas.clipPath(path, r.ck.ClipOp.Intersect, true)
- } finally {
- path.delete()
- }
- } else if (isPathShape(shapeNode)) {
- const path = makeNodeShapePath(r, shapeNode, shapeRect, shapeHasRadius)
- try {
- canvas.clipPath(path, r.ck.ClipOp.Intersect, true)
- } finally {
- path.delete()
- }
- } else if (nodeHasSmoothCorners(shapeNode)) {
- const path = makeSmoothRRectPath(r, shapeNode)
- canvas.clipPath(path, r.ck.ClipOp.Intersect, true)
- path.delete()
- } else if (shapeHasRadius) {
- canvas.clipRRect(r.makeRRect(shapeNode), r.ck.ClipOp.Intersect, true)
- } else {
- canvas.clipRect(shapeRect, r.ck.ClipOp.Intersect, true)
- }
-
- const expand = effect.radius * 2
- const { x: localOffsetX, y: localOffsetY } = localEffectOffset(effect, shadowShapeChild)
-
- const spreadPadding = sp < 0 ? -sp : 0
- const big = r.ck.LTRBRect(
- Math.min(-expand, -expand + localOffsetX - spreadPadding),
- Math.min(-expand, -expand + localOffsetY - spreadPadding),
- Math.max(shapeNode.width + expand, shapeNode.width + expand + localOffsetX + spreadPadding),
- Math.max(shapeNode.height + expand, shapeNode.height + expand + localOffsetY + spreadPadding)
- )
- const bigPathBuilder = new r.ck.PathBuilder()
- bigPathBuilder.addRect(big)
- const bigPath = bigPathBuilder.detachAndDelete()
- let innerPath: Path | null = null
- if (shapeNode.type === 'ELLIPSE') {
- const builder = new r.ck.PathBuilder()
- const offsetRect = r.ck.LTRBRect(
- localOffsetX + sp,
- localOffsetY + sp,
- shapeNode.width + localOffsetX - sp,
- shapeNode.height + localOffsetY - sp
- )
- builder.addOval(offsetRect)
- innerPath = builder.detachAndDelete()
- } else if (isPathShape(shapeNode)) {
- const sourcePath = makeNodeShapePath(r, shapeNode, shapeRect, shapeHasRadius)
- const transformedBuilder = new r.ck.PathBuilder()
- transformedBuilder.addPath(sourcePath, r.ck.Matrix.translated(localOffsetX, localOffsetY))
- sourcePath.delete()
- const transformed = transformedBuilder.detachAndDelete()
- innerPath = pathWithSpread(r, transformed, -sp)
- transformed.delete()
- } else if (nodeHasSmoothCorners(shapeNode)) {
- innerPath = makeSmoothRRectPath(r, shapeNode, -sp, localOffsetX, localOffsetY)
- } else if (shapeHasRadius) {
- const builder = new r.ck.PathBuilder()
- builder.addRRect(r.makeRRectWithOffset(shapeNode, localOffsetX, localOffsetY, sp))
- innerPath = builder.detachAndDelete()
- } else {
- const builder = new r.ck.PathBuilder()
- builder.addRect(
- r.ck.LTRBRect(
- localOffsetX + sp,
- localOffsetY + sp,
- shapeNode.width + localOffsetX - sp,
- shapeNode.height + localOffsetY - sp
- )
+ if (!includeChildren && !paintsCastShadow(node)) return
+ const sole = includeChildren ? soleShadowChild(graph, node) : null
+ if (sole && castsFromOwnShape(sole)) {
+ withChildCoordinates(canvas, sole, () =>
+ drawShapeInnerShadow(
+ r,
+ canvas,
+ sole,
+ r.ck.LTRBRect(0, 0, sole.width, sole.height),
+ effect,
+ nodeHasRadius(sole)
)
- innerPath = builder.detachAndDelete()
- }
-
- const shadowPath = innerPath
- ? r.ck.Path.MakeFromOp(bigPath, innerPath, r.ck.PathOp.Difference)
- : null
- innerPath?.delete()
- bigPath.delete()
- if (shadowPath) {
- canvas.drawPath(shadowPath, r.auxFill)
- shadowPath.delete()
- }
- } finally {
- canvas.restore()
- r.auxFill.setImageFilter(null)
- r.auxFill.setBlendMode(r.ck.BlendMode.SrcOver)
+ )
+ return
}
+ if (!includeChildren && castsFromOwnShape(node)) {
+ drawShapeInnerShadow(r, canvas, node, rect, effect, hasRadius)
+ return
+ }
+ const bounds = shadowLayerBounds(r, graph, node, effect, 0, includeChildren)
+ drawSilhouetteInnerShadow(r, canvas, effect, bounds, () =>
+ drawSilhouette(r, canvas, graph, node, 'cast', includeChildren)
+ )
}
+/**
+ * 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.
+ */
export function renderEffects(
r: SkiaRenderer,
canvas: Canvas,
node: SceneNode,
+ graph: SceneGraph,
rect: Float32Array,
hasRadius: boolean,
- pass: 'behind' | 'front',
- shadowShapeChild?: SceneNode | null
+ pass: EffectPass
): void {
- if (pass === 'front') {
- for (const effect of rawNoiseEffects(node)) {
- renderNoiseEffect(r, canvas, node, rect, hasRadius, effect)
- }
- }
+ if (pass === 'front') renderNoiseEffects(r, canvas, node, rect, hasRadius)
+ const ownShadows = !isLayerContainer(node)
for (const effect of node.effects) {
if (!effect.visible) continue
- if (pass === 'behind' && effect.type === 'DROP_SHADOW') {
- renderDropShadow(r, canvas, node, effect, hasRadius, shadowShapeChild)
+ if (pass === 'behind' && effect.type === 'DROP_SHADOW' && ownShadows) {
+ renderDropShadow(r, canvas, graph, node, effect, false)
}
if (pass === 'behind' && effect.type === 'BACKGROUND_BLUR') {
r.applyClippedBlur(canvas, node, rect, hasRadius, blurSigma(effect.radius))
}
- if (pass === 'front' && effect.type === 'INNER_SHADOW') {
- const shapeNode = shadowShapeChild ?? node
- if (shapeNode.type !== 'TEXT' && !castsShadow(node, shadowShapeChild)) continue
- if (shapeNode.type === 'TEXT') {
- drawTextInnerShadow(r, canvas, node, effect, shadowShapeChild)
- } else {
- drawShapeInnerShadow(r, canvas, node, rect, effect, hasRadius, shadowShapeChild)
- }
+ if (pass === 'inner' && effect.type === 'INNER_SHADOW' && ownShadows) {
+ renderInnerShadow(r, canvas, graph, node, rect, effect, hasRadius, false)
}
}
}
+
+/**
+ * Draws a container's drop shadows before it (`behind`) and its inner shadows over its fills,
+ * strokes, and children (`front`), cast from the children too unless its own fill covers them.
+ */
+export function renderLayerShadows(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ graph: SceneGraph,
+ node: SceneNode,
+ pass: 'behind' | 'front'
+): void {
+ if (!isLayerContainer(node)) return
+ const type = pass === 'behind' ? 'DROP_SHADOW' : 'INNER_SHADOW'
+ const effects = node.effects.filter((effect) => effect.visible && effect.type === type)
+ if (effects.length === 0) return
+ const includeChildren = shadowIncludesChildren(graph, node)
+ const hasRadius = nodeHasRadius(node)
+ const rect = r.ck.LTRBRect(0, 0, node.width, node.height)
+ for (const effect of effects) {
+ if (pass === 'behind') renderDropShadow(r, canvas, graph, node, effect, includeChildren)
+ else renderInnerShadow(r, canvas, graph, node, rect, effect, hasRadius, includeChildren)
+ }
+}
diff --git a/packages/core/src/canvas/shadows/shape.ts b/packages/core/src/canvas/shadows/shape.ts
new file mode 100644
index 000000000..231b41928
--- /dev/null
+++ b/packages/core/src/canvas/shadows/shape.ts
@@ -0,0 +1,434 @@
+import type { BlendMode, Canvas, Path } from 'canvaskit-wasm'
+
+import type { Effect, SceneNode, Stroke } from '@open-pencil/scene-graph'
+
+import { figmaBlendModeToSkia } from '#core/canvas/blend'
+import { blurSigma } from '#core/canvas/effects'
+import type { SkiaRenderer } from '#core/canvas/renderer'
+import {
+ makeNodeShapePath,
+ makeSmoothRRectPath,
+ nodeHasRadius,
+ nodeHasSmoothCorners
+} from '#core/canvas/shapes'
+import { sideStrokeRRects, strokeAlignShare } from '#core/canvas/strokes/sides'
+
+import { fillsCastShadow, paintCastsShadow } from './silhouette'
+
+function isPathShape(node: SceneNode): boolean {
+ return node.type === 'POLYGON' || node.type === 'STAR' || node.type === 'VECTOR'
+}
+
+/** Whether the node's fill outline is its whole shadow: it casts from a fill and no stroke reaches past it. */
+export function castsFromOwnShape(node: SceneNode): boolean {
+ return (
+ node.type !== 'TEXT' &&
+ node.type !== 'BOOLEAN_OPERATION' &&
+ !isPartialArc(node) &&
+ fillsCastShadow(node) &&
+ node.strokes.every((stroke) => !paintCastsShadow(stroke) || stroke.align === 'INSIDE')
+ )
+}
+
+const OUTLINE_SHAPE_TYPES: ReadonlySet<SceneNode['type']> = new Set<SceneNode['type']>([
+ 'RECTANGLE',
+ 'ROUNDED_RECTANGLE',
+ 'ELLIPSE',
+ 'FRAME',
+ 'COMPONENT',
+ 'COMPONENT_SET',
+ 'INSTANCE',
+ 'SECTION'
+])
+
+/**
+ * A pie, donut, or open arc. The shadow paths below draw ellipses as ovals, so these take the
+ * silhouette, which draws the arc itself.
+ */
+function isPartialArc(node: SceneNode): boolean {
+ const arc = node.type === 'ELLIPSE' ? node.arcData : null
+ if (!arc) return false
+ return arc.innerRadius > 0 || Math.abs(arc.endingAngle - arc.startingAngle) < 2 * Math.PI - 1e-6
+}
+
+/** Distances from each side of a rectangle: top, right, bottom, left. */
+type Sides = readonly [number, number, number, number]
+
+const evenSides = (distance: number): Sides => [distance, distance, distance, distance]
+
+/** How far a shape's stroke reaches past each side of it (`outset`) and into it (`inset`). */
+export interface StrokeOutline {
+ outset: Sides
+ inset: Sides
+ /** Every side reaches as far, so the outline is the shape itself grown. */
+ even: boolean
+ align: Stroke['align']
+}
+
+function sideOutline([top, right, bottom, left]: Sides, align: Stroke['align']): StrokeOutline {
+ const share = strokeAlignShare(align)
+ return {
+ outset: [top * share, right * share, bottom * share, left * share],
+ inset: [top * (1 - share), right * (1 - share), bottom * (1 - share), left * (1 - share)],
+ even: false,
+ align
+ }
+}
+
+/**
+ * For a rectangle, ellipse, or frame with at most one plain stroke, the outline that stroke
+ * gives it; null when the outline is not the shape grown, as with dashes or a sharp corner the
+ * stroke does not miter. Sides of their own weights give the ring of `sideStrokeRRects`, but
+ * measured on Figma 126, a shadow with a spread grows every side by the layer's single weight.
+ */
+export function regularStrokeOutline(node: SceneNode, spread: number): StrokeOutline | null {
+ if (!OUTLINE_SHAPE_TYPES.has(node.type) || isPartialArc(node)) return null
+ const strokes = node.strokes.filter(paintCastsShadow)
+ if (strokes.length === 0) return evenOutline(0, 'INSIDE')
+ const [stroke] = strokes
+ if (strokes.length > 1 || stroke.dashPattern?.length) return null
+ const sharp = node.type !== 'ELLIPSE' && !nodeHasRadius(node)
+ if (node.independentStrokeWeights && node.type !== 'ELLIPSE') {
+ const sides: Sides = [
+ node.borderTopWeight,
+ node.borderRightWeight,
+ node.borderBottomWeight,
+ node.borderLeftWeight
+ ]
+ if (sides.every((weight) => weight === sides[0])) return evenOutline(sides[0], stroke.align)
+ if (spread !== 0) return evenOutline(node.strokeWeight, stroke.align)
+ return sideOutline(sides, stroke.align)
+ }
+ if (sharp && (stroke.join ?? node.strokeJoin) !== 'MITER') return null
+ return evenOutline(stroke.weight, stroke.align)
+}
+
+function evenOutline(weight: number, align: Stroke['align']): StrokeOutline {
+ const outset = weight * strokeAlignShare(align)
+ return { outset: evenSides(outset), inset: evenSides(weight - outset), even: true, align }
+}
+
+/** The node's rectangle, rounded rectangle, or ellipse grown by `offset`, or shrunk when negative. */
+function grownShapePath(r: SkiaRenderer, node: SceneNode, offset: number): Path {
+ if (node.type !== 'ELLIPSE' && nodeHasSmoothCorners(node)) {
+ return makeSmoothRRectPath(r, node, offset)
+ }
+ const builder = new r.ck.PathBuilder()
+ const rect = r.ltrb(-offset, -offset, node.width + offset, node.height + offset)
+ if (node.type === 'ELLIPSE') builder.addOval(rect)
+ else if (nodeHasRadius(node)) builder.addRRect(r.makeRRectWithSpread(node, offset))
+ else builder.addRect(rect)
+ return builder.detachAndDelete()
+}
+
+/** The outline the node's stroke gives it, grown further by `spread`. */
+function strokeOutlinePath(
+ r: SkiaRenderer,
+ node: SceneNode,
+ outline: StrokeOutline,
+ spread: number
+): Path {
+ if (outline.even) return grownShapePath(r, node, outline.outset[0] + spread)
+ const builder = new r.ck.PathBuilder()
+ builder.addRRect(sideStrokeRRects(node, outline.align, spread).outer)
+ return builder.detachAndDelete()
+}
+
+function pathWithSpread(r: SkiaRenderer, path: Path, spread: number): Path | null {
+ if (spread === 0) return path.copy()
+ const ring = path.makeStroked({ width: Math.abs(spread) * 2, join: r.ck.StrokeJoin.Round })
+ if (!ring) return null
+ const result = r.ck.Path.MakeFromOp(
+ path,
+ ring,
+ spread > 0 ? r.ck.PathOp.Union : r.ck.PathOp.Difference
+ )
+ ring.delete()
+ return result
+}
+
+function drawPathShape(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ node: SceneNode,
+ hasRadius: boolean,
+ spread = 0
+): void {
+ const path = makeNodeShapePath(r, node, r.ltrb(0, 0, node.width, node.height), hasRadius)
+ const spreadPath = pathWithSpread(r, path, spread)
+ path.delete()
+ if (!spreadPath) return
+ try {
+ canvas.drawPath(spreadPath, r.auxFill)
+ } finally {
+ spreadPath.delete()
+ }
+}
+
+function drawShadowGeometryPath(r: SkiaRenderer, canvas: Canvas, path: Path, spread: number): void {
+ if (spread === 0) {
+ canvas.drawPath(path, r.auxFill)
+ return
+ }
+ const spreadPath = pathWithSpread(r, path, spread)
+ if (!spreadPath) return
+ try {
+ canvas.drawPath(spreadPath, r.auxFill)
+ } finally {
+ spreadPath.delete()
+ }
+}
+
+/**
+ * Draws what `draw` paints with `r.auxFill` as a shadow, offset and blurred as a mask, which lets
+ * Skia blur rectangles and rounded rectangles analytically.
+ */
+function drawMaskShadow(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ effect: Effect,
+ blendMode: BlendMode,
+ draw: () => void
+): void {
+ r.auxFill.setColor(r.color4f(effect.color.r, effect.color.g, effect.color.b, effect.color.a))
+ r.auxFill.setMaskFilter(r.getCachedMaskBlur(blurSigma(effect.radius)))
+ r.auxFill.setImageFilter(null)
+ r.auxFill.setBlendMode(blendMode)
+ canvas.save()
+ try {
+ canvas.translate(effect.offset.x, effect.offset.y)
+ draw()
+ } finally {
+ canvas.restore()
+ r.auxFill.setMaskFilter(null)
+ r.auxFill.setBlendMode(r.ck.BlendMode.SrcOver)
+ }
+}
+
+/** Draws a shadow cast by the node's fill outline grown by `spread`. */
+export function drawShapeDropShadow(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ node: SceneNode,
+ effect: Effect,
+ hasRadius: boolean,
+ spread: number,
+ blendMode: BlendMode
+): void {
+ const sp = spread
+ const geometryShadow = r.getFillGeometry(node)
+ drawMaskShadow(r, canvas, effect, blendMode, () => {
+ if (geometryShadow) {
+ for (const path of geometryShadow) drawShadowGeometryPath(r, canvas, path, sp)
+ } else if (node.type === 'ELLIPSE') {
+ canvas.drawOval(r.ltrb(-sp, -sp, node.width + sp, node.height + sp), r.auxFill)
+ } else if (isPathShape(node)) {
+ drawPathShape(r, canvas, node, hasRadius, sp)
+ } else if (nodeHasSmoothCorners(node)) {
+ const path = makeSmoothRRectPath(r, node, sp)
+ canvas.drawPath(path, r.auxFill)
+ path.delete()
+ } else if (hasRadius) {
+ canvas.drawRRect(r.makeRRectWithSpread(node, sp), r.auxFill)
+ } else {
+ canvas.drawRect(r.ltrb(-sp, -sp, node.width + sp, node.height + sp), r.auxFill)
+ }
+ })
+}
+
+/** Whether the stroke reaches past the shape on any side, so it grows the shadow. */
+export function strokeGrowsOutline(outline: StrokeOutline): boolean {
+ return outline.outset.some((distance) => distance > 0)
+}
+
+/** Draws a shadow cast by the shape grown by its stroke and the spread. */
+export function drawOutlineDropShadow(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ node: SceneNode,
+ effect: Effect,
+ outline: StrokeOutline,
+ spread: number,
+ blendMode: BlendMode
+): void {
+ drawMaskShadow(r, canvas, effect, blendMode, () => {
+ const offset = outline.outset[0] + spread
+ const rect = r.ltrb(-offset, -offset, node.width + offset, node.height + offset)
+ if (!outline.even) {
+ canvas.drawRRect(sideStrokeRRects(node, outline.align, spread).outer, r.auxFill)
+ } else if (node.type !== 'ELLIPSE' && nodeHasSmoothCorners(node)) {
+ const path = strokeOutlinePath(r, node, outline, spread)
+ canvas.drawPath(path, r.auxFill)
+ path.delete()
+ } else if (node.type === 'ELLIPSE') canvas.drawOval(rect, r.auxFill)
+ else if (nodeHasRadius(node)) canvas.drawRRect(r.makeRRectWithSpread(node, offset), r.auxFill)
+ else canvas.drawRect(rect, r.auxFill)
+ })
+}
+
+/** Draws the shadow of a stroke without a fill: the ring between its outline and its inner edge. */
+export function drawRingDropShadow(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ node: SceneNode,
+ effect: Effect,
+ outline: StrokeOutline,
+ spread: number,
+ blendMode: BlendMode
+): void {
+ const builder = new r.ck.PathBuilder()
+ if (outline.even) {
+ const outer = strokeOutlinePath(r, node, outline, spread)
+ builder.addPath(outer)
+ outer.delete()
+ const inset = outline.inset[0] + spread
+ if (inset * 2 < Math.min(node.width, node.height)) {
+ const inner = grownShapePath(r, node, -inset)
+ builder.addPath(inner)
+ inner.delete()
+ }
+ } else {
+ const { outer, inner } = sideStrokeRRects(node, outline.align, spread)
+ builder.addRRect(outer)
+ if (inner) builder.addRRect(inner)
+ }
+ const ring = builder.detachAndDelete()
+ ring.setFillType(r.ck.FillType.EvenOdd)
+ try {
+ drawMaskShadow(r, canvas, effect, blendMode, () => canvas.drawPath(ring, r.auxFill))
+ } finally {
+ ring.delete()
+ }
+}
+
+/** Clips out the area a shape hides its shadow under: the shape grown by its stroke. */
+export function clipOutShapeKnockout(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ node: SceneNode,
+ hasRadius: boolean,
+ outline: StrokeOutline | null
+): void {
+ const geometry = outline ? null : r.getFillGeometry(node)
+ if (geometry) {
+ for (const path of geometry) canvas.clipPath(path, r.ck.ClipOp.Difference, true)
+ return
+ }
+ const path = outline
+ ? strokeOutlinePath(r, node, outline, 0)
+ : makeNodeShapePath(r, node, r.ltrb(0, 0, node.width, node.height), hasRadius)
+ canvas.clipPath(path, r.ck.ClipOp.Difference, true)
+ path.delete()
+}
+
+export function drawShapeInnerShadow(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ node: SceneNode,
+ rect: Float32Array,
+ effect: Effect,
+ hasRadius: boolean
+): void {
+ const sp = effect.spread
+ const shapeNode = node
+ r.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))
+
+ const shapeRect = rect
+ const shapeHasRadius = hasRadius
+
+ canvas.save()
+ try {
+ if (shapeNode.type === 'ELLIPSE') {
+ const builder = new r.ck.PathBuilder()
+ builder.addOval(shapeRect)
+ const path = builder.detachAndDelete()
+ try {
+ canvas.clipPath(path, r.ck.ClipOp.Intersect, true)
+ } finally {
+ path.delete()
+ }
+ } else if (isPathShape(shapeNode)) {
+ const path = makeNodeShapePath(r, shapeNode, shapeRect, shapeHasRadius)
+ try {
+ canvas.clipPath(path, r.ck.ClipOp.Intersect, true)
+ } finally {
+ path.delete()
+ }
+ } else if (nodeHasSmoothCorners(shapeNode)) {
+ const path = makeSmoothRRectPath(r, shapeNode)
+ canvas.clipPath(path, r.ck.ClipOp.Intersect, true)
+ path.delete()
+ } else if (shapeHasRadius) {
+ canvas.clipRRect(r.makeRRect(shapeNode), r.ck.ClipOp.Intersect, true)
+ } else {
+ canvas.clipRect(shapeRect, r.ck.ClipOp.Intersect, true)
+ }
+
+ const expand = effect.radius * 2
+ const { x: localOffsetX, y: localOffsetY } = effect.offset
+
+ const spreadPadding = sp < 0 ? -sp : 0
+ const big = r.ck.LTRBRect(
+ Math.min(-expand, -expand + localOffsetX - spreadPadding),
+ Math.min(-expand, -expand + localOffsetY - spreadPadding),
+ Math.max(shapeNode.width + expand, shapeNode.width + expand + localOffsetX + spreadPadding),
+ Math.max(shapeNode.height + expand, shapeNode.height + expand + localOffsetY + spreadPadding)
+ )
+ const bigPathBuilder = new r.ck.PathBuilder()
+ bigPathBuilder.addRect(big)
+ const bigPath = bigPathBuilder.detachAndDelete()
+ let innerPath: Path | null = null
+ if (shapeNode.type === 'ELLIPSE') {
+ const builder = new r.ck.PathBuilder()
+ const offsetRect = r.ck.LTRBRect(
+ localOffsetX + sp,
+ localOffsetY + sp,
+ shapeNode.width + localOffsetX - sp,
+ shapeNode.height + localOffsetY - sp
+ )
+ builder.addOval(offsetRect)
+ innerPath = builder.detachAndDelete()
+ } else if (isPathShape(shapeNode)) {
+ const sourcePath = makeNodeShapePath(r, shapeNode, shapeRect, shapeHasRadius)
+ const transformedBuilder = new r.ck.PathBuilder()
+ transformedBuilder.addPath(sourcePath, r.ck.Matrix.translated(localOffsetX, localOffsetY))
+ sourcePath.delete()
+ const transformed = transformedBuilder.detachAndDelete()
+ innerPath = pathWithSpread(r, transformed, -sp)
+ transformed.delete()
+ } else if (nodeHasSmoothCorners(shapeNode)) {
+ innerPath = makeSmoothRRectPath(r, shapeNode, -sp, localOffsetX, localOffsetY)
+ } else if (shapeHasRadius) {
+ const builder = new r.ck.PathBuilder()
+ builder.addRRect(r.makeRRectWithOffset(shapeNode, localOffsetX, localOffsetY, sp))
+ innerPath = builder.detachAndDelete()
+ } else {
+ const builder = new r.ck.PathBuilder()
+ builder.addRect(
+ r.ck.LTRBRect(
+ localOffsetX + sp,
+ localOffsetY + sp,
+ shapeNode.width + localOffsetX - sp,
+ shapeNode.height + localOffsetY - sp
+ )
+ )
+ innerPath = builder.detachAndDelete()
+ }
+
+ const shadowPath = innerPath
+ ? r.ck.Path.MakeFromOp(bigPath, innerPath, r.ck.PathOp.Difference)
+ : null
+ innerPath?.delete()
+ bigPath.delete()
+ if (shadowPath) {
+ canvas.drawPath(shadowPath, r.auxFill)
+ shadowPath.delete()
+ }
+ } finally {
+ canvas.restore()
+ r.auxFill.setImageFilter(null)
+ r.auxFill.setBlendMode(r.ck.BlendMode.SrcOver)
+ }
+}
diff --git a/packages/core/src/canvas/shadows/silhouette.ts b/packages/core/src/canvas/shadows/silhouette.ts
new file mode 100644
index 000000000..158793440
--- /dev/null
+++ b/packages/core/src/canvas/shadows/silhouette.ts
@@ -0,0 +1,367 @@
+import type { Canvas } from 'canvaskit-wasm'
+
+import type { Fill, NodeType, SceneGraph, SceneNode, Stroke } from '@open-pencil/scene-graph'
+import Matrix from '@open-pencil/scene-graph/matrix'
+import type { Rect } from '@open-pencil/scene-graph/primitives'
+
+import { paintBooleanOperation } from '#core/canvas/boolean'
+import { renderMaskedChildIds } from '#core/canvas/masks'
+import type { SkiaRenderer } from '#core/canvas/renderer'
+import { nodeHasRadius, nodeHasSmoothCorners } from '#core/canvas/shapes'
+import { strokeAlignShare } from '#core/canvas/strokes/sides'
+import { nodeOrientationMatrix } from '#core/geometry'
+
+/**
+ * What a shadow is cast from (`cast`) or hidden under when it does not show behind the node
+ * (`knockout`). Measured on Figma 126: a layer casts from the outline of every paint above 0%
+ * opacity, its children included, at full strength; it hides the shadow under every shape it
+ * draws, a shape's area included even at 0% fill, but a container's area only when the container
+ * paints something itself or clips its content.
+ */
+export type SilhouetteMode = 'cast' | 'knockout'
+
+const SILHOUETTE_PAINT: Fill = {
+ type: 'SOLID',
+ color: { r: 1, g: 1, b: 1, a: 1 },
+ opacity: 1,
+ visible: true
+}
+
+const LAYER_CONTAINER_TYPES: ReadonlySet<NodeType> = new Set<NodeType>([
+ 'FRAME',
+ 'GROUP',
+ 'SECTION',
+ 'COMPONENT',
+ 'COMPONENT_SET',
+ 'INSTANCE'
+])
+
+/**
+ * Figma casts a full-strength shadow from any paint above 0% opacity and none from a paint at
+ * 0% or a gradient whose stops are all transparent, so such a paint counts as no paint at all.
+ */
+export function paintCastsShadow(paint: Fill): boolean {
+ if (!paint.visible || paint.opacity === 0) return false
+ return paint.gradientStops?.some((stop) => stop.color.a > 0) ?? true
+}
+
+/** Frames, groups, and the like, whose shadows Figma casts from their children as well. */
+export function isLayerContainer(node: SceneNode): boolean {
+ return LAYER_CONTAINER_TYPES.has(node.type)
+}
+
+export function fillsCastShadow(node: SceneNode): boolean {
+ return (
+ node.fills.some(paintCastsShadow) ||
+ node.fillGeometry.some((geometry) => geometry.fills?.some(paintCastsShadow) ?? false)
+ )
+}
+
+export function paintsCastShadow(node: SceneNode): boolean {
+ return fillsCastShadow(node) || node.strokes.some(paintCastsShadow)
+}
+
+function clipsChildren(node: SceneNode): boolean {
+ return node.clipsContent && node.type !== 'GROUP'
+}
+
+function drawsSilhouette(node: SceneNode): boolean {
+ return node.visible && !node.internalOnly && node.opacity > 0
+}
+
+/** Whether a container has a child that draws, which its shadows then include. */
+export function hasDrawnChildren(graph: SceneGraph, node: SceneNode): boolean {
+ if (!isLayerContainer(node)) return false
+ return node.childIds.some((id) => {
+ const child = graph.getNode(id)
+ return child !== undefined && drawsSilhouette(child) && !child.isMask
+ })
+}
+
+function silhouetteStroke(stroke: Stroke): Stroke {
+ return { ...stroke, ...SILHOUETTE_PAINT, blendMode: undefined }
+}
+
+/** The node with its shadow-casting paints made opaque and no effects, or null when it draws none. */
+function silhouetteProxy(node: SceneNode, mode: SilhouetteMode): SceneNode | null {
+ const strokes = node.strokes.filter(paintCastsShadow).map(silhouetteStroke)
+ const castsFill = fillsCastShadow(node)
+ const coversArea =
+ mode === 'knockout' &&
+ (!isLayerContainer(node) || castsFill || strokes.length > 0 || clipsChildren(node))
+ const fills = castsFill || coversArea ? [SILHOUETTE_PAINT] : []
+ if (fills.length === 0 && strokes.length === 0) return null
+ return {
+ ...node,
+ fills,
+ strokes,
+ fillGeometry: node.fillGeometry.map((geometry) =>
+ geometry.fills
+ ? {
+ ...geometry,
+ fills: coversArea || geometry.fills.some(paintCastsShadow) ? [SILHOUETTE_PAINT] : []
+ }
+ : geometry
+ ),
+ effects: [],
+ boundVariables: {}
+ }
+}
+
+/** Draws what the node casts or hides a shadow under, opaque, in its own coordinates. */
+export function drawSilhouette(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ graph: SceneGraph,
+ node: SceneNode,
+ mode: SilhouetteMode,
+ includeChildren: boolean
+): void {
+ const proxy = silhouetteProxy(node, mode)
+ if (proxy?.type === 'BOOLEAN_OPERATION') paintBooleanOperation(r, canvas, proxy, graph)
+ else if (proxy) r.paintShapeContent(canvas, proxy, graph)
+ if (includeChildren && isLayerContainer(node)) drawChildSilhouettes(r, canvas, graph, node, mode)
+}
+
+function drawChildSilhouettes(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ graph: SceneGraph,
+ node: SceneNode,
+ mode: SilhouetteMode
+): void {
+ const drawChild = (childId: string) => {
+ const child = graph.getNode(childId)
+ if (!child || !drawsSilhouette(child)) return
+ canvas.save()
+ canvas.translate(child.x, child.y)
+ canvas.concat(nodeOrientationMatrix(child))
+ drawSilhouette(r, canvas, graph, child, mode, true)
+ canvas.restore()
+ }
+ canvas.save()
+ try {
+ if (clipsChildren(node)) {
+ r.clipNodeShape(
+ canvas,
+ node,
+ r.ck.LTRBRect(0, 0, node.width, node.height),
+ nodeHasRadius(node)
+ )
+ }
+ renderMaskedChildIds(
+ r,
+ canvas,
+ node.childIds,
+ (childId) => {
+ const child = graph.getNode(childId)
+ return child && drawsSilhouette(child) && child.isMask ? child.maskType : null
+ },
+ drawChild,
+ drawChild,
+ (childId) => childBox(graph, childId)
+ )
+ } finally {
+ canvas.restore()
+ }
+}
+
+/** How far a stroke reaches past the shape it outlines. */
+export function strokeOutset(stroke: Stroke): number {
+ return stroke.weight * strokeAlignShare(stroke.align)
+}
+
+function strokeOverflow(node: SceneNode): number {
+ let overflow = 0
+ for (const stroke of node.strokes) {
+ if (paintCastsShadow(stroke)) overflow = Math.max(overflow, strokeOutset(stroke))
+ }
+ return overflow
+}
+
+function isOpaquePaint(paint: Fill): boolean {
+ return (
+ paint.visible &&
+ paint.type === 'SOLID' &&
+ paint.opacity === 1 &&
+ paint.color.a === 1 &&
+ (paint.blendMode === undefined || paint.blendMode === 'NORMAL')
+ )
+}
+
+function paintsOverOwnKnockout(node: SceneNode): boolean {
+ const strokes = node.strokes.filter(paintCastsShadow)
+ const coversArea =
+ !isLayerContainer(node) || fillsCastShadow(node) || strokes.length > 0 || clipsChildren(node)
+ if (coversArea && !node.fills.some(isOpaquePaint)) return false
+ return strokes.every((stroke) => stroke.align === 'INSIDE' || isOpaquePaint(stroke))
+}
+
+/**
+ * Whether the layer paints opaquely over everything its knockout would clear, so the shadow
+ * hidden under it is hidden anyway and the knockout can be skipped.
+ */
+export function paintsOverKnockout(
+ graph: SceneGraph,
+ node: SceneNode,
+ includeChildren: boolean
+): boolean {
+ if (!paintsOverOwnKnockout(node)) return false
+ if (!includeChildren || !isLayerContainer(node)) return true
+ return node.childIds.every((id) => {
+ const child = graph.getNode(id)
+ if (!child || !drawsSilhouette(child)) return true
+ const blends = child.blendMode !== 'NORMAL' && child.blendMode !== 'PASS_THROUGH'
+ if (child.isMask || child.opacity < 1 || blends) return false
+ return paintsOverKnockout(graph, child, true)
+ })
+}
+
+function unionRect(a: Rect | null, b: Rect | null): Rect | null {
+ if (!a) return b
+ if (!b) return a
+ const x = Math.min(a.x, b.x)
+ const y = Math.min(a.y, b.y)
+ return {
+ x,
+ y,
+ width: Math.max(a.x + a.width, b.x + b.width) - x,
+ height: Math.max(a.y + a.height, b.y + b.height) - y
+ }
+}
+
+/** The box a child's silhouette can cover, in its parent's coordinates. */
+function childBox(graph: SceneGraph, childId: string): Rect | null {
+ const child = graph.getNode(childId)
+ if (!child || !drawsSilhouette(child)) return null
+ const local = silhouetteBounds(graph, child, true)
+ if (!local) return null
+ const matrix = Matrix.multiply(Matrix.translated(child.x, child.y), nodeOrientationMatrix(child))
+ const points = Matrix.mapPoints(matrix, [
+ local.x,
+ local.y,
+ local.x + local.width,
+ local.y,
+ local.x + local.width,
+ local.y + local.height,
+ local.x,
+ local.y + local.height
+ ])
+ const xs = [points[0], points[2], points[4], points[6]]
+ const ys = [points[1], points[3], points[5], points[7]]
+ const x = Math.min(...xs)
+ const y = Math.min(...ys)
+ return { x, y, width: Math.max(...xs) - x, height: Math.max(...ys) - y }
+}
+
+function childrenBounds(graph: SceneGraph, node: SceneNode): Rect | null {
+ let bounds: Rect | null = null
+ for (const childId of node.childIds) bounds = unionRect(bounds, childBox(graph, childId))
+ if (!bounds || !clipsChildren(node)) return bounds
+ const x = Math.max(bounds.x, 0)
+ const y = Math.max(bounds.y, 0)
+ const right = Math.min(bounds.x + bounds.width, node.width)
+ const bottom = Math.min(bounds.y + bounds.height, node.height)
+ return right > x && bottom > y ? { x, y, width: right - x, height: bottom - y } : null
+}
+
+/** The box the node's silhouette can cover, in its own coordinates, strokes included. */
+export function silhouetteBounds(
+ graph: SceneGraph,
+ node: SceneNode,
+ includeChildren: boolean
+): Rect | null {
+ const overflow = strokeOverflow(node)
+ const own: Rect = {
+ x: -overflow,
+ y: -overflow,
+ width: node.width + overflow * 2,
+ height: node.height + overflow * 2
+ }
+ if (!includeChildren || !isLayerContainer(node)) return own
+ return unionRect(own, childrenBounds(graph, node))
+}
+
+/**
+ * Whether a point lies inside the node's rectangle and rounded corners. Corner smoothing pulls a
+ * corner further in, so a smoothed corner is checked as a circle of the longer smoothed radius.
+ */
+function pointInShape(node: SceneNode, x: number, y: number): boolean {
+ const epsilon = 0.01
+ if (x < -epsilon || y < -epsilon || x > node.width + epsilon || y > node.height + epsilon) {
+ return false
+ }
+ if (!nodeHasRadius(node)) return true
+ const smoothing = nodeHasSmoothCorners(node) ? 1 + node.cornerSmoothing : 1
+ const radius = (value: number) => Math.min(value * smoothing, node.width / 2, node.height / 2)
+ const corners = node.independentCorners
+ ? [node.topLeftRadius, node.topRightRadius, node.bottomRightRadius, node.bottomLeftRadius]
+ : [node.cornerRadius, node.cornerRadius, node.cornerRadius, node.cornerRadius]
+ const [topLeft, topRight, bottomRight, bottomLeft] = corners.map(radius)
+ const outsideCorner = (cx: number, cy: number, r: number, inCorner: boolean) =>
+ inCorner && Math.hypot(x - cx, y - cy) > r + epsilon
+ return !(
+ outsideCorner(topLeft, topLeft, topLeft, x < topLeft && y < topLeft) ||
+ outsideCorner(
+ node.width - topRight,
+ topRight,
+ topRight,
+ x > node.width - topRight && y < topRight
+ ) ||
+ outsideCorner(
+ node.width - bottomRight,
+ node.height - bottomRight,
+ bottomRight,
+ x > node.width - bottomRight && y > node.height - bottomRight
+ ) ||
+ outsideCorner(
+ bottomLeft,
+ node.height - bottomLeft,
+ bottomLeft,
+ x < bottomLeft && y > node.height - bottomLeft
+ )
+ )
+}
+
+/** The node's shape is convex, so a box lies inside it when its four corners do. */
+function shapeContainsBox(node: SceneNode, box: Rect): boolean {
+ const right = box.x + box.width
+ const bottom = box.y + box.height
+ return (
+ pointInShape(node, box.x, box.y) &&
+ pointInShape(node, right, box.y) &&
+ pointInShape(node, right, bottom) &&
+ pointInShape(node, box.x, bottom)
+ )
+}
+
+/**
+ * Whether a container's shadows have to include its children: they do unless the container's
+ * own fill already covers everything they draw.
+ */
+export function shadowIncludesChildren(graph: SceneGraph, node: SceneNode): boolean {
+ if (!hasDrawnChildren(graph, node)) return false
+ if (!fillsCastShadow(node)) return true
+ if (clipsChildren(node)) return false
+ const bounds = childrenBounds(graph, node)
+ return bounds !== null && !shapeContainsBox(node, bounds)
+}
+
+/**
+ * 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.
+ */
+export function soleShadowChild(graph: SceneGraph, node: SceneNode): SceneNode | null {
+ if (!isLayerContainer(node) || paintsCastShadow(node) || clipsChildren(node)) return null
+ let sole: SceneNode | null = null
+ 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 (!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.ts b/packages/core/src/canvas/strokes.ts
index 04af99c0c..3247e5003 100644
--- a/packages/core/src/canvas/strokes.ts
+++ b/packages/core/src/canvas/strokes.ts
@@ -408,54 +408,6 @@ export function drawRRectStrokeWithAlign(
}
}
-export function drawIndividualSideStrokes(
- r: SkiaRenderer,
- canvas: Canvas,
- node: SceneNode,
- align: 'INSIDE' | 'CENTER' | 'OUTSIDE'
-): void {
- const w = node.width
- const h = node.height
- const inside = align === 'INSIDE'
- const outside = align === 'OUTSIDE'
-
- const tw = node.borderTopWeight
- if (tw > 0) {
- let y = 0
- if (inside) y = tw / 2
- else if (outside) y = -tw / 2
- r.strokePaint.setStrokeWidth(tw)
- canvas.drawLine(0, y, w, y, r.strokePaint)
- }
-
- const rw = node.borderRightWeight
- if (rw > 0) {
- let x = w
- if (inside) x = w - rw / 2
- else if (outside) x = w + rw / 2
- r.strokePaint.setStrokeWidth(rw)
- canvas.drawLine(x, 0, x, h, r.strokePaint)
- }
-
- const bw = node.borderBottomWeight
- if (bw > 0) {
- let y = h
- if (inside) y = h - bw / 2
- else if (outside) y = h + bw / 2
- r.strokePaint.setStrokeWidth(bw)
- canvas.drawLine(0, y, w, y, r.strokePaint)
- }
-
- const lw = node.borderLeftWeight
- if (lw > 0) {
- let x = 0
- if (inside) x = lw / 2
- else if (outside) x = -lw / 2
- r.strokePaint.setStrokeWidth(lw)
- canvas.drawLine(x, 0, x, h, r.strokePaint)
- }
-}
-
export function strokeNodeShape(
r: SkiaRenderer,
canvas: Canvas,
diff --git a/packages/core/src/canvas/strokes/sides.ts b/packages/core/src/canvas/strokes/sides.ts
new file mode 100644
index 000000000..8cbb738e0
--- /dev/null
+++ b/packages/core/src/canvas/strokes/sides.ts
@@ -0,0 +1,228 @@
+import type { Canvas, Path } from 'canvaskit-wasm'
+
+import type { SceneNode, Stroke } from '@open-pencil/scene-graph'
+
+import type { SkiaRenderer } from '#core/canvas/renderer'
+import { normalizeDashPattern } from '#core/canvas/strokes'
+
+/** 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
+ if (align === 'CENTER') return 0.5
+ return 0
+}
+
+function cornerRadii(node: SceneNode): [number, number, number, number] {
+ if (!node.independentCorners) {
+ return [node.cornerRadius, node.cornerRadius, node.cornerRadius, node.cornerRadius]
+ }
+ return [node.topLeftRadius, node.topRightRadius, node.bottomRightRadius, node.bottomLeftRadius]
+}
+
+/**
+ * The outer and inner edges of a frame's stroke with sides of their own weights, as rounded
+ * 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.
+ */
+export function sideStrokeRRects(
+ node: SceneNode,
+ align: Stroke['align'],
+ grow = 0
+): { outer: Float32Array; inner: Float32Array | null } {
+ const share = strokeAlignShare(align)
+ const weights = [
+ node.borderTopWeight,
+ node.borderRightWeight,
+ node.borderBottomWeight,
+ node.borderLeftWeight
+ ]
+ 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
+ const [tl, tr, br, bl] = cornerRadii(node)
+ const out = (radius: number, a: number, aWeight: number, b: number, bWeight: number) => {
+ if (radius <= 0) return 0
+ const stroked = [aWeight > 0 ? a : null, bWeight > 0 ? b : null].filter((side) => side !== null)
+ return Math.max(0, radius + (stroked.length > 0 ? Math.min(...stroked) : grow))
+ }
+ const into = (radius: number, side: number) => Math.max(0, radius - side)
+ const tlOut = out(tl, top, tWeight, left, lWeight)
+ const trOut = out(tr, top, tWeight, right, rWeight)
+ const brOut = out(br, bottom, bWeight, right, rWeight)
+ const blOut = out(bl, bottom, bWeight, left, lWeight)
+ const outer = new Float32Array([
+ -left,
+ -top,
+ node.width + right,
+ node.height + bottom,
+ tlOut,
+ tlOut,
+ trOut,
+ trOut,
+ brOut,
+ brOut,
+ blOut,
+ blOut
+ ])
+ if (leftIn + rightIn >= node.width || topIn + bottomIn >= node.height) {
+ return { outer, inner: null }
+ }
+ const inner = new Float32Array([
+ leftIn,
+ topIn,
+ node.width - rightIn,
+ node.height - bottomIn,
+ into(tl, leftIn),
+ into(tl, topIn),
+ into(tr, rightIn),
+ into(tr, topIn),
+ into(br, rightIn),
+ into(br, bottomIn),
+ into(bl, leftIn),
+ into(bl, bottomIn)
+ ])
+ return { outer, inner }
+}
+
+/** Strokes a frame whose sides have their own weights, as one ring like Figma, or side by side when dashed. */
+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)) {
+ 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)
+ } finally {
+ r.strokePaint.setStyle(r.ck.PaintStyle.Stroke)
+ }
+}
+
+/**
+ * Where one side's dashes fall along its length: Figma 126 stretches the pattern so the side
+ * holds a whole number of periods, rounded to the nearest, with half a dash at each end.
+ */
+export function sideDashSpans(length: number, pattern: readonly number[]): Array<[number, number]> {
+ const period = pattern.reduce((sum, size) => sum + size, 0)
+ if (period <= 0 || length <= 0) return [[0, Math.max(0, length)]]
+ const scale = length / (Math.max(1, Math.round(length / period)) * period)
+ const spans: Array<[number, number]> = []
+ let position = (-pattern[0] * scale) / 2
+ for (let index = 0; position < length; index++) {
+ const size = pattern[index % pattern.length] * scale
+ const start = Math.max(0, position)
+ const end = Math.min(length, position + size)
+ if (index % 2 === 0 && end > start) spans.push([start, end])
+ position += size
+ }
+ return spans
+}
+
+/**
+ * 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.
+ */
+function dashedSidesPath(
+ r: SkiaRenderer,
+ node: SceneNode,
+ align: Stroke['align'],
+ pattern: readonly number[]
+): Path {
+ 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 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)
+ }
+ }
+ 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)
+ }
+ }
+ 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()
+}
+
+/** Dashed sides on rounded corners, drawn as straight dashed lines along each side. */
+function drawDashedSideLines(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ node: SceneNode,
+ align: 'INSIDE' | 'CENTER' | 'OUTSIDE'
+): void {
+ const w = node.width
+ const h = node.height
+ const inside = align === 'INSIDE'
+ const outside = align === 'OUTSIDE'
+
+ const tw = node.borderTopWeight
+ if (tw > 0) {
+ let y = 0
+ if (inside) y = tw / 2
+ else if (outside) y = -tw / 2
+ r.strokePaint.setStrokeWidth(tw)
+ canvas.drawLine(0, y, w, y, r.strokePaint)
+ }
+
+ const rw = node.borderRightWeight
+ if (rw > 0) {
+ let x = w
+ if (inside) x = w - rw / 2
+ else if (outside) x = w + rw / 2
+ r.strokePaint.setStrokeWidth(rw)
+ canvas.drawLine(x, 0, x, h, r.strokePaint)
+ }
+
+ const bw = node.borderBottomWeight
+ if (bw > 0) {
+ let y = h
+ if (inside) y = h - bw / 2
+ else if (outside) y = h + bw / 2
+ r.strokePaint.setStrokeWidth(bw)
+ canvas.drawLine(0, y, w, y, r.strokePaint)
+ }
+
+ const lw = node.borderLeftWeight
+ if (lw > 0) {
+ let x = 0
+ if (inside) x = lw / 2
+ else if (outside) x = -lw / 2
+ r.strokePaint.setStrokeWidth(lw)
+ canvas.drawLine(x, 0, x, h, r.strokePaint)
+ }
+}
diff --git a/packages/core/tests/canvas/shadows.test.ts b/packages/core/tests/canvas/shadows.test.ts
new file mode 100644
index 000000000..ed5106f66
--- /dev/null
+++ b/packages/core/tests/canvas/shadows.test.ts
@@ -0,0 +1,404 @@
+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 { expectDefined } from '../helpers/assert'
+import { expectFigmaRow, renderRow, type FigmaRowScene } from '../helpers/figma-rows'
+
+const ck = await initCanvasKit()
+const renderer = new SkiaRenderer(ck, expectDefined(ck.MakeSurface(1, 1)))
+afterAll(() => renderer.destroy())
+
+/**
+ * Rows of pixels from Figma 126 exports of the scenes below, read as `renderRow` reads ours.
+ */
+const FIGMA: Record<string, number[]> = {
+ "rect-nofill-stroke-CENTER-F": [
+ 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 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, 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, 255,
+ 42, 84, 141, 180, 188, 164, 112, 60, 24, 6, 0, 0
+ ],
+ "rect-nofill-stroke-CENTER-T": [
+ 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 41, 84, 141, 180, 189, 164, 112, 60, 25, 5, 1, 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, 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, 255, 42, 84, 141, 180, 188, 164, 112, 60, 24, 6, 0, 0
+ ],
+ "rect-fill50-F": [
+ 0, 0, 0, 0, 0, 0, 0, 0, 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, 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, 255, 255, 255, 242, 214, 169, 113, 61, 25, 4, 0,
+ 0, 0, 0
+ ],
+ "rect-fill50-T": [
+ 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 133, 147, 169, 199, 225, 242, 252, 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, 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, 242, 214, 169, 113, 61, 25, 4, 0,
+ 0, 0, 0
+ ],
+ "frame-nofill-two-F": [
+ 0, 0, 0, 0, 0, 0, 0, 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, 242,
+ 215, 171, 114, 61, 25, 5, 0, 0, 0, 0, 0, 0
+ ],
+ "frame-fill1-overflow-noclip": [
+ 0, 0, 0, 0, 0, 0, 0, 1, 14, 41, 84, 142, 191, 226, 245, 250, 250, 250, 250, 250, 250, 250, 250,
+ 250, 250, 250, 250, 250, 250, 251, 250, 250, 250, 250, 250, 255, 255, 255, 255, 255, 255
+ ],
+ "frame-fill1-overflow-clip": [
+ 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, 255, 255, 255
+ ],
+ "group-fill0rect-child-F": [
+ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+ ],
+ "group-fill0rect-child-T": [
+ 0, 0, 0, 0, 0, 0, 0, 1, 8, 27, 57, 96, 130, 154, 167, 171, 171, 171, 171, 171, 171, 171, 171,
+ 171, 171, 171, 171, 171, 171, 171, 171, 170, 171, 171, 171, 170, 171, 170, 171, 171, 171, 171,
+ 171, 171, 171, 171, 171, 170, 162, 143, 114, 76, 40, 17, 4, 0
+ ],
+ "s0-frame-nofill-two-clip": [
+ 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 171, 114,
+ 61, 25, 5, 0, 0, 0, 0, 0, 0
+ ],
+ "frame-clip-nofill-two-T": [
+ 0, 0, 0, 0, 0, 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, 242, 215,
+ 171, 114, 61, 25, 5, 0, 0, 0, 0, 0, 0
+ ],
+ "s10-frame-fill1-noclip": [
+ 255, 255, 255, 255, 255, 255, 255, 255, 242, 214, 169, 113, 61, 25, 4, 0, 0, 0, 0, 0, 0
+ ],
+ "s10-frame-fill1-clip": [
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 242, 214, 170, 113, 61, 25, 5,
+ 0
+ ],
+ "n-union": [
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 242, 214, 171, 113, 62, 26, 5, 0, 0, 0, 0, 0,
+ 0
+ ],
+ "inner-rect-stroke-INSIDE": [0, 0, 0, 128, 128, 128, 128, 128, 128, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
+ "inner-frame-clip-child-at-edge": [
+ 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
+ ],
+}
+
+const solid = (r: number, g: number, b: number, opacity = 1) => ({
+ type: 'SOLID' as const,
+ color: { r, g, b, a: 1 },
+ opacity,
+ visible: true
+})
+const RED = solid(1, 0, 0)
+const BLUE = solid(0, 0, 1)
+const GREEN = solid(0, 0.6, 0)
+
+function shadow(type: Effect['type'], props: Partial<Effect> = {}): Effect {
+ const offset = type === 'INNER_SHADOW' ? 8 : 12
+ return {
+ type,
+ radius: 8,
+ spread: 0,
+ offset: { x: offset, y: offset },
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ visible: true,
+ blendMode: 'NORMAL',
+ showShadowBehindNode: false,
+ ...props
+ }
+}
+
+/** A 160px square at (120, 70), where every scene puts its shadowed layer. */
+const square = { x: 120, y: 70, width: 160, height: 160 }
+
+function centerStroke(opacity = 1): Pick<SceneNode, 'strokes' | 'strokeWeight' | 'strokeAlign'> {
+ return {
+ strokes: [{ ...solid(0, 0, 1, opacity), weight: 8, align: 'CENTER' }],
+ strokeWeight: 8,
+ strokeAlign: 'CENTER'
+ }
+}
+
+function twoChildren(graph: SceneGraph, parentId: string): void {
+ graph.createNode('RECTANGLE', parentId, { x: 10, y: 10, width: 60, height: 60, fills: [BLUE] })
+ graph.createNode('RECTANGLE', parentId, { x: 90, y: 90, width: 60, height: 60, fills: [GREEN] })
+}
+
+function overflowingChild(graph: SceneGraph, parentId: string): void {
+ graph.createNode('RECTANGLE', parentId, { x: -60, y: 50, width: 120, height: 50, fills: [BLUE] })
+}
+
+const row = (build: FigmaRowScene, y: number, x0: number, x1: number, channel = 3) =>
+ renderRow(ck, renderer, build, y, x0, x1, channel)
+
+describe('drop shadows are cast from what the layer draws, as in Figma', () => {
+ test('a shape without a fill casts from its stroke and hides the shadow inside', () => {
+ for (const showShadowBehindNode of [false, true]) {
+ const values = row(
+ (graph, hostId) =>
+ graph.createNode('RECTANGLE', hostId, {
+ ...square,
+ fills: [],
+ ...centerStroke(),
+ effects: [shadow('DROP_SHADOW', { showShadowBehindNode })]
+ }),
+ 150,
+ 104,
+ 306
+ )
+ expectFigmaRow(
+ values,
+ FIGMA[`rect-nofill-stroke-CENTER-${showShadowBehindNode ? 'T' : 'F'}`]
+ )
+ }
+ })
+
+ test('a translucent fill hides the shadow under it unless it shows behind the node', () => {
+ for (const showShadowBehindNode of [false, true]) {
+ const values = row(
+ (graph, hostId) =>
+ graph.createNode('RECTANGLE', hostId, {
+ ...square,
+ fills: [solid(1, 0, 0, 0.5)],
+ effects: [shadow('DROP_SHADOW', { showShadowBehindNode })]
+ }),
+ 150,
+ 104,
+ 306
+ )
+ expectFigmaRow(values, FIGMA[`rect-fill50-${showShadowBehindNode ? 'T' : 'F'}`])
+ }
+ })
+
+ test('a frame without a fill casts from every child', () => {
+ const values = row(
+ (graph, hostId) => {
+ const frame = graph.createNode('FRAME', hostId, {
+ ...square,
+ fills: [],
+ clipsContent: false,
+ effects: [shadow('DROP_SHADOW')]
+ })
+ twoChildren(graph, frame.id)
+ },
+ 200,
+ 196,
+ 300
+ )
+ expectFigmaRow(values, FIGMA['frame-nofill-two-F'])
+ })
+
+ test('children outside a frame cast unless the frame clips them', () => {
+ for (const clipsContent of [false, true]) {
+ const values = row(
+ (graph, hostId) => {
+ const frame = graph.createNode('FRAME', hostId, {
+ ...square,
+ fills: [RED],
+ clipsContent,
+ effects: [shadow('DROP_SHADOW')]
+ })
+ overflowingChild(graph, frame.id)
+ },
+ 175,
+ 50,
+ 130
+ )
+ expectFigmaRow(values, FIGMA[`frame-fill1-overflow-${clipsContent ? 'clip' : 'noclip'}`])
+ }
+ })
+
+ test('a shape at 0% fill in a group hides the shadow of what it covers', () => {
+ for (const showShadowBehindNode of [false, true]) {
+ const values = row(
+ (graph, hostId) => {
+ const group = graph.createNode('GROUP', hostId, {
+ ...square,
+ effects: [shadow('DROP_SHADOW', { showShadowBehindNode })]
+ })
+ graph.createNode('RECTANGLE', group.id, {
+ x: 0,
+ y: 0,
+ width: 160,
+ height: 160,
+ fills: [solid(1, 0, 0, 0)]
+ })
+ graph.createNode('RECTANGLE', group.id, {
+ x: 40,
+ y: 40,
+ width: 80,
+ height: 80,
+ fills: [BLUE]
+ })
+ },
+ 200,
+ 150,
+ 260
+ )
+ expectFigmaRow(values, FIGMA[`group-fill0rect-child-${showShadowBehindNode ? 'T' : 'F'}`])
+ }
+ })
+
+ test('a clipping frame hides its children shadows inside it unless they show behind', () => {
+ for (const showShadowBehindNode of [false, true]) {
+ const values = row(
+ (graph, hostId) => {
+ const frame = graph.createNode('FRAME', hostId, {
+ ...square,
+ fills: [],
+ clipsContent: true,
+ effects: [shadow('DROP_SHADOW', { showShadowBehindNode })]
+ })
+ twoChildren(graph, frame.id)
+ },
+ 200,
+ 200,
+ 300
+ )
+ expectFigmaRow(
+ values,
+ FIGMA[showShadowBehindNode ? 'frame-clip-nofill-two-T' : 's0-frame-nofill-two-clip']
+ )
+ }
+ })
+
+ test('spread applies to a frame only when it clips its content', () => {
+ for (const clipsContent of [false, true]) {
+ const values = row(
+ (graph, hostId) =>
+ graph.createNode('FRAME', hostId, {
+ ...square,
+ fills: [RED],
+ clipsContent,
+ effects: [shadow('DROP_SHADOW', { spread: 10 })]
+ }),
+ 150,
+ 270,
+ 310
+ )
+ expectFigmaRow(values, FIGMA[`s10-frame-fill1-${clipsContent ? 'clip' : 'noclip'}`])
+ }
+ })
+
+ test('a boolean operation casts from its result', () => {
+ const values = row(
+ (graph, hostId) => {
+ const union = graph.createNode('BOOLEAN_OPERATION', hostId, {
+ x: 130,
+ y: 80,
+ width: 110,
+ height: 130,
+ booleanOperation: 'UNION',
+ fills: [RED],
+ effects: [shadow('DROP_SHADOW')]
+ })
+ graph.createNode('RECTANGLE', union.id, { x: 0, y: 0, width: 100, height: 60, fills: [BLUE] })
+ graph.createNode('RECTANGLE', union.id, { x: 50, y: 30, width: 60, height: 100, fills: [BLUE] })
+ },
+ 180,
+ 226,
+ 270
+ )
+ expectFigmaRow(values, FIGMA['n-union'])
+ })
+})
+
+describe('arcs cast from the arc, not the whole ellipse', () => {
+ test('a half pie casts only below its flat edge', () => {
+ const pie: FigmaRowScene = (graph, hostId) =>
+ graph.createNode('ELLIPSE', hostId, {
+ ...square,
+ fills: [RED],
+ arcData: { startingAngle: 0, endingAngle: Math.PI, innerRadius: 0 },
+ effects: [shadow('DROP_SHADOW')]
+ })
+ // Outside the ellipse, right of it: under the missing top half, then beside the pie.
+ const above = row(pie, square.y + 60, square.x + 162, square.x + 168)
+ const beside = row(pie, square.y + 100, square.x + 162, square.x + 168)
+ expect(Math.max(...above)).toBeLessThanOrEqual(2)
+ expect(Math.min(...beside)).toBeGreaterThan(200)
+ })
+})
+
+describe('inner shadows sit where Figma draws them', () => {
+ test('a shape takes its inner shadow under its strokes (blue channel)', () => {
+ const values = row(
+ (graph, hostId) =>
+ graph.createNode('RECTANGLE', hostId, {
+ ...square,
+ fills: [RED],
+ strokes: [{ ...solid(0, 0, 1, 0.5), weight: 12, align: 'INSIDE' }],
+ strokeWeight: 12,
+ strokeAlign: 'INSIDE',
+ effects: [shadow('INNER_SHADOW')]
+ }),
+ 150,
+ 114,
+ 150,
+ 2
+ )
+ expectFigmaRow(values, FIGMA['inner-rect-stroke-INSIDE'])
+ })
+
+ test('a frame takes its inner shadow over its children (blue channel)', () => {
+ const values = row(
+ (graph, hostId) => {
+ const frame = graph.createNode('FRAME', hostId, {
+ ...square,
+ fills: [RED],
+ clipsContent: true,
+ effects: [shadow('INNER_SHADOW')]
+ })
+ graph.createNode('RECTANGLE', frame.id, {
+ x: 0,
+ y: 0,
+ width: 160,
+ height: 50,
+ fills: [BLUE]
+ })
+ },
+ 95,
+ 116,
+ 170,
+ 2
+ )
+ expectFigmaRow(values, FIGMA['inner-frame-clip-child-at-edge'])
+ })
+
+ test('an offset larger than the blur shades the whole strip it uncovers (red channel)', () => {
+ const values = row(
+ (graph, hostId) => {
+ const union = graph.createNode('BOOLEAN_OPERATION', hostId, {
+ ...square,
+ booleanOperation: 'UNION',
+ fills: [RED],
+ effects: [shadow('INNER_SHADOW', { radius: 4, offset: { x: 50, y: 0 } })]
+ })
+ graph.createNode('RECTANGLE', union.id, {
+ x: 0,
+ y: 0,
+ width: 160,
+ height: 160,
+ fills: [BLUE]
+ })
+ },
+ 40 + square.y,
+ square.x,
+ square.x + 60,
+ 0
+ )
+ // Opaque black covers the first 50px; past the blur the fill shows again.
+ expect(Math.max(...values.slice(0, 22))).toBeLessThanOrEqual(2)
+ expect(values.at(-1)).toBe(255)
+ })
+})
diff --git a/packages/core/tests/canvas/strokes/sides.test.ts b/packages/core/tests/canvas/strokes/sides.test.ts
new file mode 100644
index 000000000..431d88f48
--- /dev/null
+++ b/packages/core/tests/canvas/strokes/sides.test.ts
@@ -0,0 +1,143 @@
+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 { createDefaultNode } from '@open-pencil/scene-graph/node-defaults'
+
+import { sideDashSpans, sideStrokeRRects } from '#core/canvas/strokes/sides'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+import { expectFigmaRow, renderRow } from '#core-tests/helpers/figma-rows'
+
+const ck = await initCanvasKit()
+const renderer = new SkiaRenderer(ck, expectDefined(ck.MakeSurface(1, 1)))
+afterAll(() => renderer.destroy())
+
+/** Rows of alpha from Figma 126 exports, read as `renderRow` reads ours. */
+const FIGMA = {
+ sharpHalf: [0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128],
+ roundHalf: [0, 0, 0, 0, 0, 8, 128, 128, 128, 128, 120, 8, 0, 0, 0, 0, 0, 0, 0, 0],
+ 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
+ ]
+}
+
+function sidesFrame(props: Partial<SceneNode> = {}, opacity = 0.5) {
+ return (graph: SceneGraph, hostId: string) => {
+ graph.createNode('FRAME', hostId, {
+ x: 120,
+ y: 70,
+ width: 160,
+ height: 160,
+ fills: [],
+ clipsContent: false,
+ strokes: [
+ {
+ type: 'SOLID',
+ color: { r: 0, g: 0, b: 1, a: 1 },
+ opacity,
+ visible: true,
+ weight: 8,
+ align: 'CENTER'
+ }
+ ],
+ strokeWeight: 8,
+ strokeAlign: 'CENTER',
+ independentStrokeWeights: true,
+ borderTopWeight: 8,
+ borderRightWeight: 0,
+ borderBottomWeight: 16,
+ borderLeftWeight: 4,
+ ...props
+ })
+ }
+}
+
+describe('strokes with sides of their own weights, as in Figma', () => {
+ test('are one ring with a filled corner, so a translucent stroke does not overlap', () => {
+ expectFigmaRow(renderRow(ck, renderer, sidesFrame(), 68, 112, 140), FIGMA.sharpHalf)
+ })
+
+ test('round each corner by its sides', () => {
+ expectFigmaRow(
+ renderRow(ck, renderer, sidesFrame({ cornerRadius: 24 }), 76, 112, 150),
+ FIGMA.roundHalf
+ )
+ })
+
+ test('dash each side on its own, with the corner between two dashed sides filled', () => {
+ const dashed = sidesFrame({ width: 150, height: 150 }, 1)
+ const values = renderRow(
+ ck,
+ renderer,
+ (graph, hostId) => {
+ dashed(graph, hostId)
+ const frame = graph.getNode(expectDefined(graph.getNode(hostId)).childIds[0])
+ if (frame) frame.strokes = frame.strokes.map((stroke) => ({ ...stroke, dashPattern: [20, 10] }))
+ },
+ 68,
+ 112,
+ 200
+ )
+ expectFigmaRow(values, FIGMA.dashed)
+ })
+
+ test('dash rounded sides with a one-value pattern, as dash and gap alike', () => {
+ const rounded = sidesFrame({ cornerRadius: 24 }, 1)
+ const values = renderRow(
+ ck,
+ renderer,
+ (graph, hostId) => {
+ rounded(graph, hostId)
+ const frame = graph.getNode(expectDefined(graph.getNode(hostId)).childIds[0])
+ if (frame) frame.strokes = frame.strokes.map((stroke) => ({ ...stroke, dashPattern: [10] }))
+ },
+ 70,
+ 160,
+ 240
+ )
+ expect(values.filter((alpha) => alpha === 0).length).toBeGreaterThan(10)
+ expect(values.filter((alpha) => alpha === 255).length).toBeGreaterThan(10)
+ })
+
+ test('take Figma’s corner radii: inner by each side, outer by the narrower side', () => {
+ const node = createDefaultNode(() => 'frame', 'FRAME', {
+ width: 160,
+ height: 160,
+ cornerRadius: 24,
+ independentStrokeWeights: true,
+ borderTopWeight: 4,
+ borderRightWeight: 12,
+ borderBottomWeight: 20,
+ borderLeftWeight: 16
+ })
+ const { outer, inner } = sideStrokeRRects(node, 'CENTER')
+ // Figma's strokeGeometry for this frame: outer corners of radius 26, 26, 30, and 32.
+ expect([...outer]).toEqual([-8, -2, 166, 170, 26, 26, 26, 26, 30, 30, 32, 32])
+ expect([...expectDefined(inner)]).toEqual([8, 2, 154, 150, 16, 22, 18, 22, 18, 14, 16, 14])
+ })
+
+ test('stretch the dash pattern to whole periods on each side', () => {
+ const rounded = (spans: Array<[number, number]>) =>
+ spans.map(([start, end]) => [Math.round(start * 100) / 100, Math.round(end * 100) / 100])
+ expect(rounded(sideDashSpans(80, [20, 10]))).toEqual([
+ [0, 8.89],
+ [17.78, 35.56],
+ [44.44, 62.22],
+ [71.11, 80]
+ ])
+ expect(rounded(sideDashSpans(100, [30, 10]))).toEqual([
+ [0, 12.5],
+ [20.83, 45.83],
+ [54.17, 79.17],
+ [87.5, 100]
+ ])
+ expect(rounded(sideDashSpans(70, [10, 20]))).toEqual([
+ [0, 5.83],
+ [29.17, 40.83],
+ [64.17, 70]
+ ])
+ })
+})
diff --git a/packages/core/tests/helpers/figma-rows.ts b/packages/core/tests/helpers/figma-rows.ts
new file mode 100644
index 000000000..ee661a29e
--- /dev/null
+++ b/packages/core/tests/helpers/figma-rows.ts
@@ -0,0 +1,72 @@
+import { expect } from 'bun:test'
+
+import type { CanvasKit } from 'canvaskit-wasm'
+
+import type { SkiaRenderer } from '@open-pencil/core'
+import { renderNodesToImage } from '@open-pencil/core/io'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { expectDefined } from './assert'
+
+/** Builds a scene into the frame `hostId`. */
+export type FigmaRowScene = (graph: SceneGraph, hostId: string) => void
+
+/**
+ * Renders `build` into a 400 × 300 frame without a fill, the size of the Figma 126 exports the
+ * rows are read from, and reads every 2px from `x0` to `x1` at `y`: alpha unless `channel` says.
+ */
+export function renderRow(
+ ck: CanvasKit,
+ renderer: SkiaRenderer,
+ build: FigmaRowScene,
+ y: number,
+ x0: number,
+ x1: number,
+ channel = 3
+): number[] {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const host = graph.createNode('FRAME', page, {
+ width: 400,
+ height: 300,
+ fills: [],
+ clipsContent: true
+ })
+ build(graph, host.id)
+ const png = expectDefined(
+ renderNodesToImage(ck, renderer, graph, page, [host.id], {
+ scale: 1,
+ format: 'PNG',
+ trimTransparent: false
+ })
+ )
+ const image = expectDefined(ck.MakeImageFromEncoded(png))
+ try {
+ const offset = (image.width() - 400) / 2
+ const pixels = expectDefined(
+ image.readPixels(0, 0, {
+ width: image.width(),
+ height: image.height(),
+ alphaType: ck.AlphaType.Unpremul,
+ colorType: ck.ColorType.RGBA_8888,
+ colorSpace: ck.ColorSpace.SRGB
+ })
+ )
+ const values: number[] = []
+ for (let x = x0; x <= x1; x += 2) {
+ values.push(pixels[((y + offset) * image.width() + x + offset) * 4 + channel])
+ }
+ return values
+ } finally {
+ image.delete()
+ }
+}
+
+/** Our blur kernel is fitted to Figma's within a few levels; outlines must match exactly. */
+export function expectFigmaRow(values: number[], figma: number[]): void {
+ expect(values).toHaveLength(figma.length)
+ const differences = values.map((value, index) => Math.abs(value - figma[index]))
+ const rms = Math.sqrt(differences.reduce((sum, d) => sum + d * d, 0) / differences.length)
+ expect(Math.max(...differences)).toBeLessThanOrEqual(10)
+ expect(rms).toBeLessThanOrEqual(3)
+}
diff --git a/tests/e2e/canvas/shadow-silhouette-visual.spec.ts b/tests/e2e/canvas/shadow-silhouette-visual.spec.ts
new file mode 100644
index 000000000..9c79e63db
--- /dev/null
+++ b/tests/e2e/canvas/shadow-silhouette-visual.spec.ts
@@ -0,0 +1,13 @@
+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'
+import { shadowSilhouetteDriver } from '#tests/helpers/canvas/effects/driver'
+
+const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')
+const scene = shadowSilhouetteDriver(() => editor.page)
+
+// The silhouettes are checked against Figma's pixels in packages/core/tests/canvas/shadows.test.ts.
+test('shadows are cast from what each layer draws, as in Figma', async () => {
+ await scene.show()
+ await editor.canvas.waitForRender()
+ editor.canvas.assertNoErrors()
+ expect(await editor.canvas.screenshotCanvasRegion()).toMatchSnapshot('shadow-silhouettes.png')
+})
diff --git a/tests/e2e/canvas/shadow-silhouette-visual.spec.ts-snapshots/shadow-silhouettes-openpencil-darwin.png b/tests/e2e/canvas/shadow-silhouette-visual.spec.ts-snapshots/shadow-silhouettes-openpencil-darwin.png
new file mode 100644
index 000000000..96de6161b
Binary files /dev/null and b/tests/e2e/canvas/shadow-silhouette-visual.spec.ts-snapshots/shadow-silhouettes-openpencil-darwin.png differ
diff --git a/tests/e2e/canvas/side-strokes-visual.spec.ts b/tests/e2e/canvas/side-strokes-visual.spec.ts
new file mode 100644
index 000000000..3fd4d1ddf
--- /dev/null
+++ b/tests/e2e/canvas/side-strokes-visual.spec.ts
@@ -0,0 +1,16 @@
+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'
+import { sideStrokesDriver } from '#tests/helpers/canvas/strokes/driver'
+
+const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')
+const scene = sideStrokesDriver(() => editor.page)
+
+// The ring, corner radii, and dashes are checked against Figma in packages/core/tests/canvas/strokes/sides.test.ts.
+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.
+ expect(await editor.canvas.screenshotCanvasRegion()).toMatchSnapshot('side-strokes.png', {
+ maxDiffPixels: 24
+ })
+})
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
new file mode 100644
index 000000000..6303e1f4f
Binary files /dev/null and b/tests/e2e/canvas/side-strokes-visual.spec.ts-snapshots/side-strokes-openpencil-darwin.png differ
diff --git a/tests/engine/render/canvas/effect-raster-cache.test.ts b/tests/engine/render/canvas/effect-raster-cache.test.ts
index 5b770dbd5..f5e151c56 100644
--- a/tests/engine/render/canvas/effect-raster-cache.test.ts
+++ b/tests/engine/render/canvas/effect-raster-cache.test.ts
@@ -17,8 +17,7 @@ function entry(pixels: number): EffectRasterCacheEntry {
height: 10,
scale: 2,
pixels,
- fontGeneration: 0,
- dependencyIds: []
+ fontGeneration: 0
}
}
@@ -53,17 +52,6 @@ describe('effect raster cache', () => {
expect(cache.size).toBe(0)
})
- test('invalidates an owning raster when a geometry dependency changes', () => {
- const cache = new EffectRasterCache()
- const parent = { ...entry(100), dependencyIds: ['child'] }
- cache.set('parent', parent)
-
- cache.deleteDependencies('child')
-
- expect(parent.image.delete).toHaveBeenCalledTimes(1)
- expect(cache.has('parent')).toBe(false)
- })
-
test('evicts least-recently-used entries within the pixel budget', () => {
const cache = new EffectRasterCache()
const first = entry(12_000_000)
diff --git a/tests/engine/render/canvas/effects/edge-cases.test.ts b/tests/engine/render/canvas/effects/edge-cases.test.ts
index c673962af..7e569e5ed 100644
--- a/tests/engine/render/canvas/effects/edge-cases.test.ts
+++ b/tests/engine/render/canvas/effects/edge-cases.test.ts
@@ -1,19 +1,24 @@
import { describe, expect, mock, test } from 'bun:test'
-import type { Path } from 'canvaskit-wasm'
-
-import { createDefaultNode, type SceneNode } from '@open-pencil/scene-graph'
+import { createDefaultNode } from '@open-pencil/scene-graph'
import { renderEffects } from '#core/canvas/shadows'
import { asCanvas } from '../helpers'
-import { createMockCanvas, createMockRenderer, mockCalls, OPAQUE_FILL } from './helpers'
+import {
+ createMockCanvas,
+ createMockRenderer,
+ effectNode,
+ mockCalls,
+ OPAQUE_FILL,
+ TEST_GRAPH
+} from './helpers'
describe('Edge cases and bug fixes', () => {
- test('drop shadow cast from stroke when node has no fill', () => {
+ test('a dashed stroke without a fill casts from an opaque copy of its dashes', () => {
const r = createMockRenderer()
const canvas = createMockCanvas()
- const node: Partial<SceneNode> = {
+ const node = effectNode({
type: 'RECTANGLE',
width: 100,
height: 100,
@@ -35,18 +40,26 @@ describe('Edge cases and bug fixes', () => {
weight: 2,
opacity: 1,
color: { r: 0, g: 0, b: 0, a: 1 },
- align: 'CENTER'
+ align: 'CENTER',
+ dashPattern: [4, 2]
}
],
strokeGeometry: [{ windingRule: 'NONZERO', commandsBlob: new Uint8Array() }],
childIds: []
- }
- r.getStrokeGeometry = mock(() => [{} as Path])
+ })
- renderEffects(r, asCanvas(canvas), node as SceneNode, new Float32Array(4), false, 'behind')
+ renderEffects(r, asCanvas(canvas), node, TEST_GRAPH, new Float32Array(4), false, 'behind')
- expect(r.getStrokeGeometry).toHaveBeenCalledWith(node)
- expect(canvas.drawPath).toHaveBeenCalled()
+ expect(r.getCachedDropShadow).toHaveBeenCalled()
+ expect(r.paintShapeContent).toHaveBeenCalledWith(
+ canvas,
+ expect.objectContaining({
+ fills: [],
+ strokes: [expect.objectContaining({ dashPattern: [4, 2], opacity: 1 })],
+ effects: []
+ }),
+ TEST_GRAPH
+ )
})
test('drop shadow is not drawn under a fill at 0% opacity', () => {
@@ -72,256 +85,16 @@ describe('Edge cases and bug fixes', () => {
childIds: []
})
- renderEffects(r, asCanvas(canvas), node, new Float32Array(4), false, 'behind')
+ renderEffects(r, asCanvas(canvas), node, TEST_GRAPH, new Float32Array(4), false, 'behind')
expect(canvas.drawRect).not.toHaveBeenCalled()
expect(canvas.drawPath).not.toHaveBeenCalled()
})
- test('drop shadow on stroked containers uses the container bounds', () => {
- const r = createMockRenderer()
- const canvas = createMockCanvas()
- const node: Partial<SceneNode> = {
- type: 'FRAME',
- width: 224,
- height: 424,
- fills: [],
- effects: [
- {
- type: 'DROP_SHADOW',
- visible: true,
- color: { r: 0, g: 0, b: 0, a: 1 },
- offset: { x: 0, y: 2 },
- radius: 4,
- spread: 0,
- showShadowBehindNode: false
- }
- ],
- strokes: [
- {
- type: 'SOLID',
- visible: true,
- weight: 1,
- opacity: 1,
- color: { r: 0, g: 0, b: 0, a: 1 },
- align: 'CENTER'
- }
- ],
- strokeGeometry: [{ windingRule: 'NONZERO', commandsBlob: new Uint8Array() }],
- childIds: ['header']
- }
- r.getStrokeGeometry = mock(() => [{} as Path])
-
- renderEffects(r, asCanvas(canvas), node as SceneNode, new Float32Array(4), true, 'behind')
-
- expect(r.getStrokeGeometry).not.toHaveBeenCalled()
- expect(canvas.drawRRect).toHaveBeenCalled()
- })
-
- test('drop shadow from child applies child transforms (geometric parity)', () => {
- const r = createMockRenderer()
- const canvas = createMockCanvas()
- const child: Partial<SceneNode> = {
- type: 'RECTANGLE',
- x: 10,
- y: 20,
- width: 50,
- height: 60,
- rotation: 45,
- flipY: true,
- effects: []
- }
- const node: Partial<SceneNode> = {
- type: 'FRAME',
- width: 100,
- height: 100,
- fills: [],
- effects: [
- {
- type: 'DROP_SHADOW',
- visible: true,
- color: { r: 0, g: 0, b: 0, a: 1 },
- offset: { x: 5, y: 5 },
- radius: 0,
- spread: 0
- }
- ],
- childIds: ['child1']
- }
-
- renderEffects(
- r,
- asCanvas(canvas),
- node as SceneNode,
- new Float32Array(4),
- false,
- 'behind',
- child as SceneNode
- )
-
- // Verify order: translate (offset) -> rotate -> translate (flip) -> scale
- const translateCalls = mockCalls(canvas.translate)
- const rotateCalls = mockCalls(canvas.rotate)
- const scaleCalls = mockCalls(canvas.scale)
-
- expect(translateCalls[0]).toEqual([5 + 10, 5 + 20])
- expect(rotateCalls[0]).toEqual([45, 25, 30])
- expect(translateCalls[1]).toEqual([0, 60])
- expect(scaleCalls[0]).toEqual([1, -1])
- expect(canvas.drawRect).toHaveBeenCalled()
- })
-
- test('drop shadow from TEXT child renders glyphs (fidelity parity)', () => {
- const r = createMockRenderer()
- const canvas = createMockCanvas()
- const child: Partial<SceneNode> = {
- type: 'TEXT',
- x: 10,
- y: 20,
- width: 50,
- height: 60,
- text: 'Hello',
- effects: []
- }
- const node: Partial<SceneNode> = {
- type: 'FRAME',
- width: 100,
- height: 100,
- fills: [],
- effects: [
- {
- type: 'DROP_SHADOW',
- visible: true,
- color: { r: 0, g: 0, b: 0, a: 1 },
- offset: { x: 5, y: 5 },
- radius: 10,
- spread: 0
- }
- ],
- childIds: ['child1']
- }
-
- renderEffects(
- r,
- asCanvas(canvas),
- node as SceneNode,
- new Float32Array(4),
- false,
- 'behind',
- child as SceneNode
- )
-
- expect(r.getCachedDropShadow).toHaveBeenCalled()
- expect(canvas.saveLayer).toHaveBeenCalled()
- expect(canvas.translate).toHaveBeenCalledWith(15, 25)
- expect(r.renderText).toHaveBeenCalledWith(expect.anything(), child)
- })
-
- test('inner shadow from shape child applies child transforms and rects (geometric parity)', () => {
- const r = createMockRenderer()
- const canvas = createMockCanvas()
- const child: Partial<SceneNode> = {
- type: 'RECTANGLE',
- x: 10,
- y: 20,
- width: 50,
- height: 60,
- rotation: 45,
- flipY: true,
- effects: []
- }
- const node: Partial<SceneNode> = {
- type: 'FRAME',
- width: 100,
- height: 100,
- fills: [],
- effects: [
- {
- type: 'INNER_SHADOW',
- visible: true,
- color: { r: 0, g: 0, b: 0, a: 1 },
- offset: { x: 5, y: 5 },
- radius: 0,
- spread: 0
- }
- ],
- childIds: ['child1']
- }
-
- renderEffects(
- r,
- asCanvas(canvas),
- node as SceneNode,
- new Float32Array(4),
- false,
- 'front',
- child as SceneNode
- )
-
- const translateCalls = mockCalls(canvas.translate)
- const rotateCalls = mockCalls(canvas.rotate)
- const scaleCalls = mockCalls(canvas.scale)
-
- expect(translateCalls[0]).toEqual([10, 20])
- expect(rotateCalls[0]).toEqual([45, 25, 30])
- expect(translateCalls[1]).toEqual([0, 60])
- expect(scaleCalls[0]).toEqual([1, -1])
- expect(r.ck.LTRBRect).toHaveBeenCalledWith(0, 0, 50, 60)
- expect(canvas.clipRect).toHaveBeenCalled()
- })
-
- test('drop shadow from TEXT child applies offset in parent space', () => {
- const r = createMockRenderer()
- const canvas = createMockCanvas()
- const child: Partial<SceneNode> = {
- type: 'TEXT',
- x: 10,
- y: 20,
- width: 50,
- height: 60,
- text: 'Hello',
- rotation: 45,
- effects: []
- }
- const node: Partial<SceneNode> = {
- type: 'FRAME',
- width: 100,
- height: 100,
- fills: [],
- effects: [
- {
- type: 'DROP_SHADOW',
- visible: true,
- color: { r: 0, g: 0, b: 0, a: 1 },
- offset: { x: 5, y: 5 },
- radius: 10,
- spread: 0
- }
- ],
- childIds: ['child1']
- }
-
- renderEffects(
- r,
- asCanvas(canvas),
- node as SceneNode,
- new Float32Array(4),
- false,
- 'behind',
- child as SceneNode
- )
-
- const translateCalls = mockCalls(canvas.translate)
- expect(translateCalls[0]).toEqual([15, 25]) // offset + child position
-
- // The filter should NOT have the offset (neutralized to 0,0)
- expect(r.getCachedDropShadow).toHaveBeenCalledWith(0, 0, expect.closeTo(4.3), expect.anything())
- })
-
test('INNER_SHADOW with large offset does not vanish (bounding box union)', () => {
const r = createMockRenderer()
const canvas = createMockCanvas()
- const node: Partial<SceneNode> = {
+ const node = effectNode({
type: 'RECTANGLE',
width: 100,
height: 100,
@@ -336,15 +109,16 @@ describe('Edge cases and bug fixes', () => {
spread: 0
}
]
- }
+ })
renderEffects(
r,
asCanvas(canvas),
- node as SceneNode,
+ node,
+ TEST_GRAPH,
new Float32Array([0, 0, 100, 100]),
false,
- 'front'
+ 'inner'
)
// Expect LTRBRect for 'big' to encompass both the shape (0 to 100) and the offset hole (200 to 300)
@@ -361,7 +135,7 @@ describe('Edge cases and bug fixes', () => {
test('INNER_SHADOW with spread on rounded rect shrinks hole concentrically', () => {
const r = createMockRenderer()
const canvas = createMockCanvas()
- const node: Partial<SceneNode> = {
+ const node = effectNode({
type: 'RECTANGLE',
width: 100,
height: 100,
@@ -377,15 +151,16 @@ describe('Edge cases and bug fixes', () => {
spread: 4
}
]
- }
+ })
renderEffects(
r,
asCanvas(canvas),
- node as SceneNode,
+ node,
+ TEST_GRAPH,
new Float32Array([0, 0, 100, 100]),
true,
- 'front'
+ 'inner'
)
// makeRRectWithOffset should receive (node, localOffsetX, localOffsetY, spread)
@@ -399,7 +174,7 @@ describe('Edge cases and bug fixes', () => {
canvas.drawRect = mock(() => {
throw new Error('draw failed')
})
- const node: Partial<SceneNode> = {
+ const node = effectNode({
type: 'RECTANGLE',
width: 100,
height: 100,
@@ -416,29 +191,28 @@ describe('Edge cases and bug fixes', () => {
],
strokeGeometry: [],
childIds: []
- }
+ })
expect(() =>
- renderEffects(r, asCanvas(canvas), node as SceneNode, new Float32Array(4), false, 'behind')
+ renderEffects(r, asCanvas(canvas), node, TEST_GRAPH, new Float32Array(4), false, 'behind')
).toThrow('draw failed')
expect(canvas.restore).toHaveBeenCalled()
expect(r.auxFill.setMaskFilter).toHaveBeenCalledWith(null)
expect(r.auxFill.setBlendMode).toHaveBeenCalledWith(r.ck.BlendMode.SrcOver)
- expect(r.effectLayerPaint.setImageFilter).toHaveBeenCalledWith(null)
})
test('text inner shadow restores canvas when glyph rendering throws', () => {
const r = createMockRenderer()
const canvas = createMockCanvas()
- r.renderText = mock(() => {
+ r.paintShapeContent = mock(() => {
throw new Error('text failed')
})
- const node: Partial<SceneNode> = {
+ const node = effectNode({
type: 'TEXT',
width: 100,
height: 100,
- fills: [],
+ fills: [OPAQUE_FILL],
effects: [
{
type: 'INNER_SHADOW',
@@ -449,13 +223,13 @@ describe('Edge cases and bug fixes', () => {
spread: 0
}
]
- }
+ })
expect(() =>
- renderEffects(r, asCanvas(canvas), node as SceneNode, new Float32Array(4), false, 'front')
+ renderEffects(r, asCanvas(canvas), node, TEST_GRAPH, new Float32Array(4), false, 'inner')
).toThrow('text failed')
- expect(mockCalls(canvas.restore).length).toBe(2)
+ expect(mockCalls(canvas.restore).length).toBe(1)
expect(r.effectLayerPaint.setColorFilter).toHaveBeenCalledWith(null)
expect(r.effectLayerPaint.setImageFilter).toHaveBeenCalledWith(null)
})
diff --git a/tests/engine/render/canvas/effects/helpers.ts b/tests/engine/render/canvas/effects/helpers.ts
index 9fd1d5c9c..056e7ff56 100644
--- a/tests/engine/render/canvas/effects/helpers.ts
+++ b/tests/engine/render/canvas/effects/helpers.ts
@@ -2,7 +2,8 @@ import { mock } from 'bun:test'
import type { InputRect, Paint } from 'canvaskit-wasm'
-import type { Fill } from '@open-pencil/scene-graph'
+import { SceneGraph, type Fill, type SceneNode } from '@open-pencil/scene-graph'
+import { createDefaultNode } from '@open-pencil/scene-graph/node-defaults'
import type { SkiaRenderer } from '#core/canvas/renderer'
import { renderEffects } from '#core/canvas/shadows'
@@ -20,6 +21,14 @@ export function mockCalls(fn: unknown): unknown[][] {
return calls
}
+/** A graph for effect tests whose nodes have no children to look up. */
+export const TEST_GRAPH = new SceneGraph()
+
+/** A complete node of `props.type` for effect tests, with every field the renderer reads. */
+export function effectNode(props: Partial<SceneNode> & Pick<SceneNode, 'type'>): SceneNode {
+ return createDefaultNode(() => props.id ?? 'node', props.type, props)
+}
+
/** A fill to cast from: Figma casts no shadow from a shape with no fill, stroke, or child. */
export const OPAQUE_FILL: Fill = {
type: 'SOLID',
@@ -31,6 +40,7 @@ export const OPAQUE_FILL: Fill = {
export function createMockRenderer(overrides: Partial<SkiaRenderer> = {}): SkiaRenderer {
class MockPath {
delete = mock(() => undefined)
+ setFillType = mock(() => undefined)
copy = mock(() => new MockPath())
makeCombined = mock(() => new MockPath())
makeStroked = mock(() => new MockPath())
@@ -41,7 +51,7 @@ export function createMockRenderer(overrides: Partial<SkiaRenderer> = {}): SkiaR
Color4f: mock((r, g, b, a) => new Float32Array([r, g, b, a])),
LTRBRect: mock((l, t, r, b) => new Float32Array([l, t, r, b])),
RRectXY: mock(() => new Float32Array(12)),
- ClipOp: { Intersect: 0 },
+ ClipOp: { Intersect: 0, Difference: 1 },
Path: Object.assign(MockPath, {
MakeFromOp: mock(() => new MockPath())
}),
@@ -59,6 +69,7 @@ export function createMockRenderer(overrides: Partial<SkiaRenderer> = {}): SkiaR
detachAndDelete = mock(() => new MockPath())
},
PathOp: { Difference: 0, Union: 1 },
+ FillType: { Winding: 0, EvenOdd: 1 },
StrokeCap: { Butt: 0, Round: 1, Square: 2 },
StrokeJoin: { Miter: 0, Round: 1, Bevel: 2 },
Matrix: { translated: mock(() => new Float32Array(9)) },
@@ -74,6 +85,8 @@ export function createMockRenderer(overrides: Partial<SkiaRenderer> = {}): SkiaR
WHITE: new Float32Array([1, 1, 1, 1]),
TRANSPARENT: new Float32Array([0, 0, 0, 0]),
Paint: class {
+ setBlendMode = mock(() => undefined)
+ setImageFilter = mock(() => undefined)
setAntiAlias = mock(() => undefined)
setColor = mock(() => undefined)
setShader = mock(() => undefined)
@@ -151,6 +164,7 @@ export function createMockRenderer(overrides: Partial<SkiaRenderer> = {}): SkiaR
return new this.ck.Path()
}),
renderText: mock(() => undefined),
+ paintShapeContent: mock(() => undefined),
applyClippedBlur: mock(() => undefined),
clipNodeShape: mock(() => undefined),
applyFill: mock(() => true),
diff --git a/tests/engine/render/canvas/effects/inner-shadow.test.ts b/tests/engine/render/canvas/effects/inner-shadow.test.ts
index dd17fbb70..feb8facd7 100644
--- a/tests/engine/render/canvas/effects/inner-shadow.test.ts
+++ b/tests/engine/render/canvas/effects/inner-shadow.test.ts
@@ -1,21 +1,25 @@
import { describe, expect, test } from 'bun:test'
-import type { SceneNode } from '@open-pencil/scene-graph'
-
import { renderEffects } from '#core/canvas/shadows'
import { asCanvas } from '../helpers'
-import { createMockCanvas, createMockRenderer } from './helpers'
+import {
+ createMockCanvas,
+ createMockRenderer,
+ effectNode,
+ OPAQUE_FILL,
+ TEST_GRAPH
+} from './helpers'
describe('INNER_SHADOW bug proofs', () => {
test('INNER_SHADOW solid mask via ColorFilter on DstOut layer', () => {
const r = createMockRenderer()
const canvas = createMockCanvas()
- const node: Partial<SceneNode> = {
+ const node = effectNode({
type: 'TEXT',
width: 100,
height: 100,
- fills: [],
+ fills: [OPAQUE_FILL],
childIds: [],
effects: [
{
@@ -27,12 +31,12 @@ describe('INNER_SHADOW bug proofs', () => {
spread: 0
}
]
- }
+ })
- renderEffects(r, asCanvas(canvas), node as SceneNode, new Float32Array(4), false, 'front')
+ renderEffects(r, asCanvas(canvas), node, TEST_GRAPH, new Float32Array(4), false, 'inner')
// PROOF: ColorFilter.MakeBlend(black, SrcIn) on DstOut layer paint
- // forces renderText output to solid black without mutating fillPaint.
+ // forces the silhouette to solid black without mutating fillPaint.
// The DstOut saveLayer punches the solid mask from the blurred block.
expect(canvas.saveLayer).toHaveBeenCalled()
expect(canvas.drawRect).toHaveBeenCalled()
diff --git a/tests/engine/render/canvas/effects/ordering.test.ts b/tests/engine/render/canvas/effects/ordering.test.ts
index c55c8a69c..b1d3a84b5 100644
--- a/tests/engine/render/canvas/effects/ordering.test.ts
+++ b/tests/engine/render/canvas/effects/ordering.test.ts
@@ -33,7 +33,7 @@ describe('Renderer effect ordering (Behavioral)', () => {
}
const callOrder: string[] = []
- r.renderEffects = mock((_c, _n, _r, _h, pass) => {
+ r.renderEffects = mock((_c, _n, _g, _r, _h, pass) => {
callOrder.push(`renderEffects:${pass}`)
})
r.drawNodeFill = mock(() => {
@@ -42,10 +42,15 @@ describe('Renderer effect ordering (Behavioral)', () => {
renderShapeUncached(r, asCanvas(canvas), node, graph as SceneGraph)
- expect(callOrder).toEqual(['renderEffects:behind', 'drawNodeFill', 'renderEffects:front'])
+ expect(callOrder).toEqual([
+ 'renderEffects:behind',
+ 'drawNodeFill',
+ 'renderEffects:inner',
+ 'renderEffects:front'
+ ])
})
- test('inner shadow and blur render after strokes', () => {
+ test('inner shadows render under strokes and noise over them, as in Figma', () => {
const r = createMockRenderer()
const canvas = createMockCanvas()
const node = createDefaultNode(() => 'node1', 'RECTANGLE', {
@@ -79,7 +84,7 @@ describe('Renderer effect ordering (Behavioral)', () => {
}
const callOrder: string[] = []
- r.renderEffects = mock((_c, _n, _r, _h, pass) => {
+ r.renderEffects = mock((_c, _n, _g, _r, _h, pass) => {
callOrder.push(`renderEffects:${pass}`)
})
r.drawStrokeWithAlign = mock(() => {
@@ -88,10 +93,11 @@ describe('Renderer effect ordering (Behavioral)', () => {
renderShapeUncached(r, asCanvas(canvas), node, graph as SceneGraph)
- const strokeIdx = callOrder.indexOf('drawStrokeWithAlign')
- const frontIdx = callOrder.indexOf('renderEffects:front')
- expect(strokeIdx).toBeGreaterThan(-1)
- expect(frontIdx).toBeGreaterThan(-1)
- expect(strokeIdx).toBeLessThan(frontIdx)
+ expect(callOrder).toEqual([
+ 'renderEffects:behind',
+ 'renderEffects:inner',
+ 'drawStrokeWithAlign',
+ 'renderEffects:front'
+ ])
})
})
diff --git a/tests/engine/render/canvas/effects/path-shapes.test.ts b/tests/engine/render/canvas/effects/path-shapes.test.ts
index 2a5f3289e..15e040023 100644
--- a/tests/engine/render/canvas/effects/path-shapes.test.ts
+++ b/tests/engine/render/canvas/effects/path-shapes.test.ts
@@ -1,11 +1,16 @@
import { describe, expect, mock, test } from 'bun:test'
-import type { SceneNode } from '@open-pencil/scene-graph'
-
import { renderEffects } from '#core/canvas/shadows'
import { asCanvas } from '../helpers'
-import { createMockCanvas, createMockRenderer, mockCalls, OPAQUE_FILL } from './helpers'
+import {
+ createMockCanvas,
+ createMockRenderer,
+ effectNode,
+ mockCalls,
+ OPAQUE_FILL,
+ TEST_GRAPH
+} from './helpers'
const requiredNodeFields = { childIds: [] as string[], strokeGeometry: [] }
@@ -13,7 +18,7 @@ describe('path shape shadows', () => {
test('drop shadow for a star without imported geometry uses the star path', () => {
const r = createMockRenderer()
const canvas = createMockCanvas()
- const node: Partial<SceneNode> = {
+ const node = effectNode({
...requiredNodeFields,
type: 'STAR',
width: 100,
@@ -29,9 +34,9 @@ describe('path shape shadows', () => {
spread: 5
}
]
- }
+ })
- renderEffects(r, asCanvas(canvas), node as SceneNode, new Float32Array(4), false, 'behind')
+ renderEffects(r, asCanvas(canvas), node, TEST_GRAPH, new Float32Array(4), false, 'behind')
expect(r.makePolygonPath).toHaveBeenCalled()
expect(canvas.drawPath).toHaveBeenCalled()
@@ -48,7 +53,7 @@ describe('path shape shadows', () => {
r.ck.Path.MakeFromOp = mock(() => combinedPath)
r.getFillGeometry = mock(() => [cachedPath])
- const node: Partial<SceneNode> = {
+ const node = effectNode({
...requiredNodeFields,
type: 'STAR',
width: 100,
@@ -64,9 +69,9 @@ describe('path shape shadows', () => {
spread: 10
}
]
- }
+ })
- renderEffects(r, asCanvas(canvas), node as SceneNode, new Float32Array(4), false, 'behind')
+ renderEffects(r, asCanvas(canvas), node, TEST_GRAPH, new Float32Array(4), false, 'behind')
const makeFromOp = r.ck.Path.MakeFromOp as ReturnType<typeof mock>
expect(makeFromOp).toHaveBeenCalledWith(cachedPath, ringPath, r.ck.PathOp.Union)
@@ -78,7 +83,7 @@ describe('path shape shadows', () => {
test('inner shadow for a polygon clips and cuts out with polygon paths', () => {
const r = createMockRenderer()
const canvas = createMockCanvas()
- const node: Partial<SceneNode> = {
+ const node = effectNode({
...requiredNodeFields,
type: 'POLYGON',
width: 100,
@@ -94,15 +99,16 @@ describe('path shape shadows', () => {
spread: 3
}
]
- }
+ })
renderEffects(
r,
asCanvas(canvas),
- node as SceneNode,
+ node,
+ TEST_GRAPH,
new Float32Array([0, 0, 100, 100]),
false,
- 'front'
+ 'inner'
)
expect(mockCalls(r.makePolygonPath).length).toBeGreaterThanOrEqual(2)
diff --git a/tests/engine/render/canvas/effects/spread.test.ts b/tests/engine/render/canvas/effects/spread.test.ts
index 98c63cce5..85f668de7 100644
--- a/tests/engine/render/canvas/effects/spread.test.ts
+++ b/tests/engine/render/canvas/effects/spread.test.ts
@@ -1,17 +1,21 @@
import { describe, expect, test } from 'bun:test'
-import type { SceneNode } from '@open-pencil/scene-graph'
-
import { renderEffects } from '#core/canvas/shadows'
import { asCanvas } from '../helpers'
-import { createMockCanvas, createMockRenderer, OPAQUE_FILL } from './helpers'
+import {
+ createMockCanvas,
+ createMockRenderer,
+ effectNode,
+ OPAQUE_FILL,
+ TEST_GRAPH
+} from './helpers'
describe('Shadow spread support (Behavioral)', () => {
test('drop shadow uses spread for shape expansion', () => {
const r = createMockRenderer()
const canvas = createMockCanvas()
- const node: Partial<SceneNode> = {
+ const node = effectNode({
type: 'RECTANGLE',
width: 100,
height: 100,
@@ -27,10 +31,10 @@ describe('Shadow spread support (Behavioral)', () => {
}
],
strokeGeometry: []
- }
+ })
const rect = new Float32Array([0, 0, 100, 100])
- renderEffects(r, asCanvas(canvas), node as SceneNode, rect, false, 'behind')
+ renderEffects(r, asCanvas(canvas), node, TEST_GRAPH, rect, false, 'behind')
expect(canvas.drawRect).toHaveBeenCalled()
expect(r.ltrb).toHaveBeenCalledWith(-4, -4, 104, 104)
@@ -39,10 +43,11 @@ describe('Shadow spread support (Behavioral)', () => {
test('drop shadow uses makeRRectWithSpread when node has radius', () => {
const r = createMockRenderer()
const canvas = createMockCanvas()
- const node: Partial<SceneNode> = {
+ const node = effectNode({
type: 'RECTANGLE',
width: 100,
height: 100,
+ cornerRadius: 8,
fills: [{ visible: true, type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, opacity: 1 }],
effects: [
{
@@ -55,10 +60,10 @@ describe('Shadow spread support (Behavioral)', () => {
}
],
strokeGeometry: []
- }
+ })
const rect = new Float32Array([0, 0, 100, 100])
- renderEffects(r, asCanvas(canvas), node as SceneNode, rect, true, 'behind')
+ renderEffects(r, asCanvas(canvas), node, TEST_GRAPH, rect, true, 'behind')
expect(r.makeRRectWithSpread).toHaveBeenCalledWith(node, 4)
expect(canvas.drawRRect).toHaveBeenCalled()
@@ -67,7 +72,7 @@ describe('Shadow spread support (Behavioral)', () => {
test('inner shadow uses spread for cutout contraction', () => {
const r = createMockRenderer()
const canvas = createMockCanvas()
- const node: Partial<SceneNode> = {
+ const node = effectNode({
type: 'RECTANGLE',
width: 100,
height: 100,
@@ -83,10 +88,10 @@ describe('Shadow spread support (Behavioral)', () => {
spread: 4
}
]
- }
+ })
const rect = new Float32Array([0, 0, 100, 100])
- renderEffects(r, asCanvas(canvas), node as SceneNode, rect, false, 'front')
+ renderEffects(r, asCanvas(canvas), node, TEST_GRAPH, rect, false, 'inner')
expect(r.ck.LTRBRect).toHaveBeenCalledWith(9, 9, 101, 101)
expect(canvas.drawPath).toHaveBeenCalled()
diff --git a/tests/engine/render/canvas/effects/text-shadow.test.ts b/tests/engine/render/canvas/effects/text-shadow.test.ts
index 3b8717e74..d9e94fcd2 100644
--- a/tests/engine/render/canvas/effects/text-shadow.test.ts
+++ b/tests/engine/render/canvas/effects/text-shadow.test.ts
@@ -1,21 +1,26 @@
import { describe, expect, test } from 'bun:test'
-import type { SceneNode } from '@open-pencil/scene-graph'
-
import { renderEffects } from '#core/canvas/shadows'
import { asCanvas } from '../helpers'
-import { createMockCanvas, createMockRenderer, mockCalls } from './helpers'
+import {
+ createMockCanvas,
+ createMockRenderer,
+ effectNode,
+ mockCalls,
+ OPAQUE_FILL,
+ TEST_GRAPH
+} from './helpers'
-describe('Text shadow renders on glyphs, not bounding box (Behavioral)', () => {
- test('drop shadow has TEXT-specific branch', () => {
+describe('Text shadows follow the glyphs, not the bounding box (Behavioral)', () => {
+ test('drop shadow is cast from the glyph silhouette', () => {
const r = createMockRenderer()
const canvas = createMockCanvas()
- const node: Partial<SceneNode> = {
+ const node = effectNode({
type: 'TEXT',
width: 100,
height: 100,
- fills: [],
+ fills: [OPAQUE_FILL],
childIds: [],
effects: [
{
@@ -27,25 +32,25 @@ describe('Text shadow renders on glyphs, not bounding box (Behavioral)', () => {
spread: 0
}
]
- }
+ })
const rect = new Float32Array([0, 0, 100, 100])
- renderEffects(r, asCanvas(canvas), node as SceneNode, rect, false, 'behind')
+ renderEffects(r, asCanvas(canvas), node, TEST_GRAPH, rect, false, 'behind')
expect(r.getCachedDropShadow).toHaveBeenCalled()
- expect(canvas.saveLayer).toHaveBeenCalledWith(r.effectLayerPaint, expect.any(Float32Array))
+ expect(canvas.saveLayer).toHaveBeenCalledWith(expect.anything(), expect.any(Float32Array))
expect(r.ck.LTRBRect).toHaveBeenCalledWith(-20, -20, 125, 125)
- expect(r.renderText).toHaveBeenCalled()
+ expect(r.paintShapeContent).toHaveBeenCalledTimes(1)
})
- test('inner shadow has TEXT-specific branch', () => {
+ test('inner shadow is cut from the glyph silhouette', () => {
const r = createMockRenderer()
const canvas = createMockCanvas()
- const node: Partial<SceneNode> = {
+ const node = effectNode({
type: 'TEXT',
width: 100,
height: 100,
- fills: [],
+ fills: [OPAQUE_FILL],
childIds: [],
effects: [
{
@@ -57,18 +62,18 @@ describe('Text shadow renders on glyphs, not bounding box (Behavioral)', () => {
spread: 0
}
]
- }
+ })
const rect = new Float32Array([0, 0, 100, 100])
- renderEffects(r, asCanvas(canvas), node as SceneNode, rect, false, 'front')
+ renderEffects(r, asCanvas(canvas), node, TEST_GRAPH, rect, false, 'inner')
// 4-layer saveLayer stack: Master, SrcIn/Tint, Blur, DstOut/Punch
expect(canvas.saveLayer).toHaveBeenCalledTimes(4)
for (const call of canvas.saveLayer.mock.calls) {
expect(call[1]).toBeInstanceOf(Float32Array)
}
- // renderText called twice: once for mask (step 2), once for punch-out (step 8)
- expect(r.renderText).toHaveBeenCalledTimes(2)
+ // The glyph silhouette is drawn twice: once for the mask, once for the punch-out
+ expect(r.paintShapeContent).toHaveBeenCalledTimes(2)
// Blend modes for the SrcIn and DstOut layers
expect(r.effectLayerPaint.setBlendMode).toHaveBeenCalledWith(r.ck.BlendMode.SrcIn)
expect(r.effectLayerPaint.setBlendMode).toHaveBeenCalledWith(r.ck.BlendMode.DstOut)
@@ -81,11 +86,11 @@ describe('Text shadow renders on glyphs, not bounding box (Behavioral)', () => {
test('inner shadow detaches ColorFilter from effectLayerPaint before deletion', () => {
const r = createMockRenderer()
const canvas = createMockCanvas()
- const node: Partial<SceneNode> = {
+ const node = effectNode({
type: 'TEXT',
width: 100,
height: 100,
- fills: [],
+ fills: [OPAQUE_FILL],
childIds: [],
effects: [
{
@@ -97,10 +102,10 @@ describe('Text shadow renders on glyphs, not bounding box (Behavioral)', () => {
spread: 0
}
]
- }
+ })
const rect = new Float32Array([0, 0, 100, 100])
- renderEffects(r, asCanvas(canvas), node as SceneNode, rect, false, 'front')
+ renderEffects(r, asCanvas(canvas), node, TEST_GRAPH, rect, false, 'inner')
const calls = mockCalls(r.effectLayerPaint.setColorFilter)
// The final call must be null (exit guard cleans up)
diff --git a/tests/engine/render/canvas/effects/types.test.ts b/tests/engine/render/canvas/effects/types.test.ts
index e6bd35042..5ba96ab4e 100644
--- a/tests/engine/render/canvas/effects/types.test.ts
+++ b/tests/engine/render/canvas/effects/types.test.ts
@@ -1,8 +1,8 @@
import { describe, expect, mock, test } from 'bun:test'
-import type { ImageFilter, Path } from 'canvaskit-wasm'
+import type { ImageFilter } from 'canvaskit-wasm'
-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import type { SceneGraph } from '@open-pencil/scene-graph'
import { createDefaultSourceMetadata } from '@open-pencil/scene-graph/node-defaults'
import { applyClippedBlur } from '#core/canvas/effects'
@@ -10,13 +10,20 @@ import { renderNode } from '#core/canvas/scene'
import { renderEffects } from '#core/canvas/shadows'
import { asCanvas, asDouble } from '../helpers'
-import { createMockCanvas, createMockRenderer, mockCalls, OPAQUE_FILL } from './helpers'
+import {
+ createMockCanvas,
+ createMockRenderer,
+ effectNode,
+ mockCalls,
+ OPAQUE_FILL,
+ TEST_GRAPH
+} from './helpers'
describe('Renderer handles all effect types (Behavioral)', () => {
test('handles DROP_SHADOW', () => {
const r = createMockRenderer()
const canvas = createMockCanvas()
- const node: Partial<SceneNode> = {
+ const node = effectNode({
type: 'RECTANGLE',
width: 100,
height: 100,
@@ -33,27 +40,20 @@ describe('Renderer handles all effect types (Behavioral)', () => {
spread: 0
}
]
- }
- renderEffects(r, asCanvas(canvas), node as SceneNode, new Float32Array(4), false, 'behind')
+ })
+ renderEffects(r, asCanvas(canvas), node, TEST_GRAPH, new Float32Array(4), false, 'behind')
expect(canvas.drawRect).toHaveBeenCalled()
})
- test('drop shadow follows stroke geometry and hides shadow behind unfilled nodes', () => {
- const strokePath = asDouble<Path>({ kind: 'stroke' })
- const fillPath = asDouble<Path>({ kind: 'fill' })
- const r = createMockRenderer({
- getFillGeometry: mock(() => [fillPath]),
- getStrokeGeometry: mock(() => [strokePath])
- })
+ test('a stroke without a fill casts a ring and clips its shape out of the shadow', () => {
+ const r = createMockRenderer()
const canvas = createMockCanvas()
- const node: Partial<SceneNode> = {
+ const node = effectNode({
type: 'RECTANGLE',
width: 100,
height: 100,
fills: [],
- strokes: [{ ...OPAQUE_FILL, weight: 1, align: 'CENTER' }],
- childIds: [],
- strokeGeometry: [{ windingRule: 'NONZERO', commandsBlob: new Uint8Array([0]) }],
+ strokes: [{ ...OPAQUE_FILL, opacity: 0.5, weight: 4, align: 'CENTER' }],
effects: [
{
type: 'DROP_SHADOW',
@@ -65,21 +65,24 @@ describe('Renderer handles all effect types (Behavioral)', () => {
showShadowBehindNode: false
}
]
- }
+ })
- renderEffects(r, asCanvas(canvas), node as SceneNode, new Float32Array(4), false, 'behind')
+ renderEffects(r, asCanvas(canvas), node, TEST_GRAPH, new Float32Array(4), false, 'behind')
- expect(r.getStrokeGeometry).toHaveBeenCalledWith(node)
- expect(r.getFillGeometry).toHaveBeenCalledWith(node)
- expect(canvas.drawPath).toHaveBeenCalledWith(strokePath, r.auxFill)
- expect(canvas.drawPath).toHaveBeenCalledWith(fillPath, r.auxFill)
- expect(r.auxFill.setBlendMode).toHaveBeenCalledWith(r.ck.BlendMode.DstOut)
+ expect(r.ltrb).toHaveBeenCalledWith(-2, -2, 102, 102)
+ expect(r.ltrb).toHaveBeenCalledWith(2, 2, 98, 98)
+ const [ring] = mockCalls(canvas.drawPath).find(([, paint]) => paint === r.auxFill) ?? []
+ if (typeof ring !== 'object' || ring === null) throw new Error('expected the ring path')
+ expect(mockCalls(Reflect.get(ring, 'setFillType'))).toContainEqual([r.ck.FillType.EvenOdd])
+ expect(canvas.clipPath).toHaveBeenCalledWith(expect.anything(), r.ck.ClipOp.Difference, true)
+ expect(canvas.drawPath).toHaveBeenCalledWith(expect.anything(), r.auxFill)
+ expect(r.paintShapeContent).not.toHaveBeenCalled()
})
test('applies effect blend modes to rendered shadow paint', () => {
const r = createMockRenderer()
const canvas = createMockCanvas()
- const node: Partial<SceneNode> = {
+ const node = effectNode({
type: 'RECTANGLE',
width: 100,
height: 100,
@@ -97,9 +100,9 @@ describe('Renderer handles all effect types (Behavioral)', () => {
blendMode: 'SCREEN'
}
]
- }
+ })
- renderEffects(r, asCanvas(canvas), node as SceneNode, new Float32Array(4), false, 'behind')
+ renderEffects(r, asCanvas(canvas), node, TEST_GRAPH, new Float32Array(4), false, 'behind')
expect(r.auxFill.setBlendMode).toHaveBeenCalledWith(r.ck.BlendMode.Screen)
expect(r.auxFill.setBlendMode).toHaveBeenLastCalledWith(r.ck.BlendMode.SrcOver)
@@ -108,7 +111,7 @@ describe('Renderer handles all effect types (Behavioral)', () => {
test('handles INNER_SHADOW', () => {
const r = createMockRenderer()
const canvas = createMockCanvas()
- const node: Partial<SceneNode> = {
+ const node = effectNode({
type: 'RECTANGLE',
width: 100,
height: 100,
@@ -124,14 +127,15 @@ describe('Renderer handles all effect types (Behavioral)', () => {
spread: 0
}
]
- }
+ })
renderEffects(
r,
asCanvas(canvas),
- node as SceneNode,
+ node,
+ TEST_GRAPH,
new Float32Array([0, 0, 100, 100]),
false,
- 'front'
+ 'inner'
)
expect(canvas.drawPath).toHaveBeenCalled()
})
@@ -139,7 +143,7 @@ describe('Renderer handles all effect types (Behavioral)', () => {
test('renders raw Figma noise effects as a bounded visual fallback', () => {
const r = createMockRenderer()
const canvas = createMockCanvas()
- const node: Partial<SceneNode> = {
+ const node = effectNode({
type: 'RECTANGLE',
width: 20,
height: 20,
@@ -174,12 +178,13 @@ describe('Renderer handles all effect types (Behavioral)', () => {
uniformScaleFactor: null
}
}
- }
+ })
renderEffects(
r,
asCanvas(canvas),
- node as SceneNode,
+ node,
+ TEST_GRAPH,
new Float32Array([0, 0, 20, 20]),
false,
'front'
@@ -192,7 +197,7 @@ describe('Renderer handles all effect types (Behavioral)', () => {
test('bounds raw noise effect draw calls for large nodes', () => {
const r = createMockRenderer()
const canvas = createMockCanvas()
- const node: Partial<SceneNode> = {
+ const node = effectNode({
type: 'RECTANGLE',
width: 1000,
height: 1000,
@@ -226,12 +231,13 @@ describe('Renderer handles all effect types (Behavioral)', () => {
uniformScaleFactor: null
}
}
- }
+ })
renderEffects(
r,
asCanvas(canvas),
- node as SceneNode,
+ node,
+ TEST_GRAPH,
new Float32Array([0, 0, 1000, 1000]),
false,
'front'
@@ -243,7 +249,8 @@ describe('Renderer handles all effect types (Behavioral)', () => {
test('handles BACKGROUND_BLUR', () => {
const r = createMockRenderer()
const canvas = createMockCanvas()
- const node: Partial<SceneNode> = {
+ const node = effectNode({
+ type: 'RECTANGLE',
fills: [],
childIds: [],
effects: [
@@ -256,8 +263,8 @@ describe('Renderer handles all effect types (Behavioral)', () => {
spread: 0
}
]
- }
- renderEffects(r, asCanvas(canvas), node as SceneNode, new Float32Array(4), false, 'behind')
+ })
+ renderEffects(r, asCanvas(canvas), node, TEST_GRAPH, new Float32Array(4), false, 'behind')
expect(r.applyClippedBlur).toHaveBeenCalled()
})
@@ -269,16 +276,16 @@ describe('Renderer handles all effect types (Behavioral)', () => {
})
const canvas = createMockCanvas()
const rect = new Float32Array([0, 0, 100, 100])
- const node: Partial<SceneNode> = {
+ const node = effectNode({
type: 'RECTANGLE',
width: 100,
height: 100,
fills: [],
childIds: [],
effects: []
- }
+ })
- applyClippedBlur(r, asCanvas(canvas), node as SceneNode, rect, false, 5)
+ applyClippedBlur(r, asCanvas(canvas), node, rect, false, 5)
expect(r.effectLayerPaint.setImageFilter).toHaveBeenCalledWith(null)
expect(canvas.saveLayer).toHaveBeenCalledWith(
@@ -293,7 +300,8 @@ describe('Renderer handles all effect types (Behavioral)', () => {
test('handles LAYER_BLUR in renderNode', () => {
const r = createMockRenderer()
const canvas = createMockCanvas()
- const node: Partial<SceneNode> = {
+ const node = effectNode({
+ type: 'RECTANGLE',
id: 'n1',
visible: true,
x: 0,
@@ -314,9 +322,9 @@ describe('Renderer handles all effect types (Behavioral)', () => {
],
childIds: [],
source: createDefaultSourceMetadata()
- }
+ })
const graph: Partial<SceneGraph> = {
- getNode: mock(() => node as SceneNode)
+ getNode: mock(() => node)
}
renderNode(r, asCanvas(canvas), graph as SceneGraph, 'n1', {})
// Figma draws a blur radius as a Gaussian of 0.43 × radius.
@@ -328,7 +336,8 @@ describe('Renderer handles all effect types (Behavioral)', () => {
test('handles FOREGROUND_BLUR in renderNode', () => {
const r = createMockRenderer()
const canvas = createMockCanvas()
- const node: Partial<SceneNode> = {
+ const node = effectNode({
+ type: 'RECTANGLE',
id: 'n1',
visible: true,
x: 0,
@@ -349,9 +358,9 @@ describe('Renderer handles all effect types (Behavioral)', () => {
],
childIds: [],
source: createDefaultSourceMetadata()
- }
+ })
const graph: Partial<SceneGraph> = {
- getNode: mock(() => node as SceneNode)
+ getNode: mock(() => node)
}
renderNode(r, asCanvas(canvas), graph as SceneGraph, 'n1', {})
expect(r.getCachedBlur).toHaveBeenCalledWith(expect.closeTo(8.6))
diff --git a/tests/engine/render/canvas/picture-invalidation.test.ts b/tests/engine/render/canvas/picture-invalidation.test.ts
index 3c7471cc3..60dba68f6 100644
--- a/tests/engine/render/canvas/picture-invalidation.test.ts
+++ b/tests/engine/render/canvas/picture-invalidation.test.ts
@@ -26,7 +26,6 @@ test('full picture invalidation resets tiled font-dependent resources', () => {
sceneBackingBuild: null,
nodePictureCache: new Map([['node', nodePicture]]),
nodePictureCacheGenerations: new Map([['node', 1]]),
- nodePictureCacheDependencies: new Map([['node', []]]),
effectRasterCache: new EffectRasterCache(),
subtreePictureCache: new Map([['subtree', { picture: subtreePicture }]]),
subtreePictureCachePageId: 'page',
@@ -46,7 +45,7 @@ test('full picture invalidation resets tiled font-dependent resources', () => {
expect(subtreePicture.delete).toHaveBeenCalledTimes(1)
})
-test('node picture invalidation removes pictures that depend on a changed child', () => {
+test('node picture invalidation removes the changed node picture and keeps its parent', () => {
const parentPicture = deletable()
const childPicture = deletable()
const textPreparationCache = new TextPreparationCache()
@@ -61,10 +60,6 @@ test('node picture invalidation removes pictures that depend on a changed child'
['parent', 1],
['child', 1]
]),
- nodePictureCacheDependencies: new Map([
- ['parent', ['child']],
- ['child', []]
- ]),
effectRasterCache: new EffectRasterCache(),
subtreePictureCache: new Map()
})
@@ -74,9 +69,9 @@ test('node picture invalidation removes pictures that depend on a changed child'
expect(textPreparationCache.deleteNode).toHaveBeenCalledWith('child', {
keepShaping: false
})
- expect(parentPicture.delete).toHaveBeenCalledTimes(1)
+ expect(parentPicture.delete).not.toHaveBeenCalled()
expect(childPicture.delete).toHaveBeenCalledTimes(1)
- expect(renderer.nodePictureCache.size).toBe(0)
+ expect([...renderer.nodePictureCache.keys()]).toEqual(['parent'])
invalidateNodePicture(renderer, 'child', ['width', 'height', 'x'])
expect(textPreparationCache.deleteNode).toHaveBeenLastCalledWith('child', {
diff --git a/tests/helpers/canvas/effects/driver.ts b/tests/helpers/canvas/effects/driver.ts
index 6dafd161c..d36353759 100644
--- a/tests/helpers/canvas/effects/driver.ts
+++ b/tests/helpers/canvas/effects/driver.ts
@@ -18,3 +18,20 @@ export function blurEffectsDriver(page: () => Page) {
}
}
}
+
+/** Builds the shadow silhouette scene on the open page and leaves it unselected for a snapshot. */
+export function shadowSilhouetteDriver(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/effects/scene.ts'
+ const scenes: typeof EffectScenes = await import(sceneURL)
+ scenes.createShadowSilhouetteScene(store.graph, store.state.currentPageId)
+ store.clearSelection()
+ store.requestRender()
+ })
+ }
+ }
+}
diff --git a/tests/helpers/canvas/effects/scene.ts b/tests/helpers/canvas/effects/scene.ts
index 6fb67cff8..62b6424d5 100644
--- a/tests/helpers/canvas/effects/scene.ts
+++ b/tests/helpers/canvas/effects/scene.ts
@@ -86,3 +86,157 @@ export function createBlurEffectsScene(graph: SceneGraph, pageId: string): void
]
})
}
+
+function shadow(type: 'DROP_SHADOW' | 'INNER_SHADOW', showShadowBehindNode = false): Effect {
+ return {
+ type,
+ radius: 12,
+ spread: 0,
+ offset: { x: 8, y: 10 },
+ color: { r: 0, g: 0, b: 0, a: 0.45 },
+ visible: true,
+ blendMode: 'NORMAL',
+ showShadowBehindNode
+ }
+}
+
+/**
+ * Shadows cast from what each layer draws, in three rows: strokes and translucent fills, the
+ * children of frames and groups, and where inner shadows sit.
+ */
+export function createShadowSilhouetteScene(graph: SceneGraph, pageId: string): void {
+ const blue = solid(0.23, 0.4, 0.95)
+ const green = solid(0.1, 0.7, 0.45)
+ const yellow = solid(1, 0.85, 0.3)
+ const box = (index: number, row: number) => ({
+ x: 80 + index * 200,
+ y: 80 + row * 180,
+ width: 150,
+ height: 110
+ })
+ graph.createNode('RECTANGLE', pageId, {
+ name: 'Stroke without fill',
+ ...box(0, 0),
+ cornerRadius: 16,
+ fills: [],
+ strokes: [{ ...blue, weight: 6, align: 'CENTER' }],
+ strokeWeight: 6,
+ strokeAlign: 'CENTER',
+ effects: [shadow('DROP_SHADOW')]
+ })
+ for (const [index, showBehind] of [
+ [1, false],
+ [2, true]
+ ] as const) {
+ graph.createNode('RECTANGLE', pageId, {
+ name: showBehind ? 'Translucent, shown behind' : 'Translucent',
+ ...box(index, 0),
+ cornerRadius: 16,
+ fills: [solid(0.23, 0.4, 0.95, 0.35)],
+ effects: [shadow('DROP_SHADOW', showBehind)]
+ })
+ }
+ graph.createNode('RECTANGLE', pageId, {
+ name: 'Fill at 0%',
+ ...box(3, 0),
+ fills: [solid(1, 0, 0, 0)],
+ effects: [shadow('DROP_SHADOW', true)]
+ })
+
+ const wrapper = graph.createNode('FRAME', pageId, {
+ name: 'Frame without fill',
+ ...box(0, 1),
+ fills: [],
+ clipsContent: false,
+ effects: [shadow('DROP_SHADOW')]
+ })
+ graph.createNode('ELLIPSE', wrapper.id, { x: 0, y: 10, width: 64, height: 64, fills: [blue] })
+ graph.createNode('RECTANGLE', wrapper.id, {
+ x: 74,
+ y: 30,
+ width: 76,
+ height: 80,
+ cornerRadius: 12,
+ fills: [green]
+ })
+ const card = graph.createNode('FRAME', pageId, {
+ name: 'Overflowing child',
+ ...box(1, 1),
+ x: box(1, 1).x + 30,
+ width: 120,
+ cornerRadius: 12,
+ fills: [solid(1, 1, 1)],
+ clipsContent: false,
+ effects: [shadow('DROP_SHADOW')]
+ })
+ graph.createNode('RECTANGLE', card.id, {
+ x: -30,
+ y: 40,
+ width: 70,
+ height: 36,
+ cornerRadius: 8,
+ fills: [blue]
+ })
+ const group = graph.createNode('GROUP', pageId, {
+ name: 'Group with a 0% shape',
+ ...box(2, 1),
+ effects: [shadow('DROP_SHADOW')]
+ })
+ graph.createNode('RECTANGLE', group.id, {
+ x: 0,
+ y: 0,
+ width: 150,
+ height: 110,
+ fills: [solid(1, 0, 0, 0)]
+ })
+ graph.createNode('RECTANGLE', group.id, { x: 35, y: 25, width: 80, height: 60, fills: [green] })
+ const union = graph.createNode('BOOLEAN_OPERATION', pageId, {
+ name: 'Union',
+ ...box(3, 1),
+ booleanOperation: 'UNION',
+ fills: [blue],
+ effects: [shadow('DROP_SHADOW')]
+ })
+ graph.createNode('RECTANGLE', union.id, { x: 0, y: 0, width: 100, height: 60 })
+ graph.createNode('ELLIPSE', union.id, { x: 60, y: 30, width: 90, height: 80 })
+
+ graph.createNode('RECTANGLE', pageId, {
+ name: 'Inner shadow under stroke',
+ ...box(0, 2),
+ fills: [yellow],
+ strokes: [{ ...solid(0.23, 0.4, 0.95, 0.5), weight: 12, align: 'INSIDE' }],
+ strokeWeight: 12,
+ strokeAlign: 'INSIDE',
+ effects: [shadow('INNER_SHADOW')]
+ })
+ const clipped = graph.createNode('FRAME', pageId, {
+ name: 'Inner shadow over child',
+ ...box(1, 2),
+ fills: [yellow],
+ clipsContent: true,
+ effects: [shadow('INNER_SHADOW')]
+ })
+ graph.createNode('RECTANGLE', clipped.id, { x: 0, y: 0, width: 150, height: 40, fills: [blue] })
+ const innerWrapper = graph.createNode('FRAME', pageId, {
+ name: 'Inner shadow on every child',
+ ...box(2, 2),
+ fills: [],
+ clipsContent: false,
+ effects: [shadow('INNER_SHADOW')]
+ })
+ graph.createNode('ELLIPSE', innerWrapper.id, {
+ x: 0,
+ y: 10,
+ width: 64,
+ height: 64,
+ fills: [blue]
+ })
+ graph.createNode('RECTANGLE', innerWrapper.id, {
+ x: 74,
+ y: 30,
+ width: 76,
+ height: 80,
+ cornerRadius: 12,
+ fills: [green]
+ })
+}
diff --git a/tests/helpers/canvas/strokes/driver.ts b/tests/helpers/canvas/strokes/driver.ts
new file mode 100644
index 000000000..08ec8099f
--- /dev/null
+++ b/tests/helpers/canvas/strokes/driver.ts
@@ -0,0 +1,20 @@
+import type { Page } from '@playwright/test'
+
+import type * as StrokeScenes from '#tests/helpers/canvas/strokes/scene'
+
+/** Builds the side strokes scene on the open page and leaves it unselected for a snapshot. */
+export function sideStrokesDriver(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.createSideStrokesScene(store.graph, store.state.currentPageId)
+ store.clearSelection()
+ store.requestRender()
+ })
+ }
+ }
+}
diff --git a/tests/helpers/canvas/strokes/scene.ts b/tests/helpers/canvas/strokes/scene.ts
new file mode 100644
index 000000000..bc5868bdb
--- /dev/null
+++ b/tests/helpers/canvas/strokes/scene.ts
@@ -0,0 +1,44 @@
+import type { SceneGraph } from '@open-pencil/scene-graph'
+
+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] }
+]
+
+/** Translucent frames with sides of their own weights: one row per alignment, sharp, rounded, and dashed. */
+export function createSideStrokesScene(graph: SceneGraph, pageId: string): void {
+ for (const [row, align] of ALIGNS.entries()) {
+ for (const [column, corner] of CORNERS.entries()) {
+ graph.createNode('FRAME', pageId, {
+ name: `${align} ${corner.name}`,
+ x: 60 + column * 200,
+ y: 60 + row * 170,
+ width: 140,
+ height: 120,
+ cornerRadius: corner.cornerRadius,
+ fills: [],
+ clipsContent: false,
+ strokes: [
+ {
+ type: 'SOLID',
+ color: { r: 0.23, g: 0.4, b: 0.95, a: 1 },
+ opacity: 0.5,
+ visible: true,
+ weight: 8,
+ align,
+ dashPattern: corner.dashPattern
+ }
+ ],
+ strokeWeight: 8,
+ strokeAlign: align,
+ independentStrokeWeights: true,
+ borderTopWeight: 8,
+ borderRightWeight: 0,
+ borderBottomWeight: 16,
+ borderLeftWeight: 4
+ })
+ }
+ }
+}