AI-native design editor. Open-source Figma alternative.
fix(canvas): draw boolean operations and outside vector strokes as Figma does (#1610)
Andrew Avsenin697b62ba71ff
diff --git a/changes/1610/fixed.md b/changes/1610/fixed.mdnew file mode 100644index 000000000..abdd2ff90--- /dev/null+++ b/changes/1610/fixed.md@@ -0,0 +1,2 @@+- Boolean operations draw as in Figma: operands with a hidden fill add only their strokes, strokes keep their alignment, reflected operands keep their orientation, vector operands take their saved fill shape, and the operation's corner radius rounds its outline.+- A vector's saved outside stroke no longer covers its fill.diff --git a/packages/core/src/canvas/boolean.ts b/packages/core/src/canvas/boolean.tsindex 721ce5cd4..a8a87c6d3 100644--- a/packages/core/src/canvas/boolean.ts+++ b/packages/core/src/canvas/boolean.ts@@ -1,10 +1,15 @@-import type { Canvas, Path, PathBuilder, PathOp } from 'canvaskit-wasm'+import type { Canvas, Path, PathOp } from 'canvaskit-wasm'-import type { SceneGraph, SceneNode, Stroke } from '@open-pencil/scene-graph'+import type { Fill, SceneGraph, SceneNode, Stroke, WindingRule } from '@open-pencil/scene-graph'+import { getNodeLocalMatrix } from '@open-pencil/scene-graph/coordinate'import type { GroupFitOptions } from '@open-pencil/scene-graph/group-bounds'+import { parseSVGPath } from '@open-pencil/scene-graph/parse-path'import { getTextOutlineSupport } from '#core/text/outlines'+import { isOpenVectorNetwork } from '#core/vector/connectivity'+import { addOpenSegmentsToPath } from '#core/vector/path-helpers'+import { sharedPath } from './paths/shared'import type { SkiaRenderer } from './renderer'import { makeLineStrokeOutline } from './strokes/line'import { textNodeToOutlinePath } from './text/outlines'@@ -19,27 +24,6 @@ const BOOLEAN_PATH_OP: Record<EXCLUDE: 'XOR'}-export function nodePathTransform(r: SkiaRenderer, child: SceneNode): number[] {- const transforms = [r.ck.Matrix.translated(child.x, child.y)]- if (child.rotation !== 0) {- transforms.push(- r.ck.Matrix.rotated((child.rotation * Math.PI) / 180, child.width / 2, child.height / 2)- )- }- if (child.flipX || child.flipY) {- transforms.push(- r.ck.Matrix.scaled(- child.flipX ? -1 : 1,- child.flipY ? -1 : 1,- child.width / 2,- child.height / 2- )- )- }- if (transforms.length === 1) return transforms[0]- return r.ck.Matrix.multiply(...transforms)-}-function hasVisibleImageFill(node: SceneNode): boolean {return node.fills.some((fill) => fill.visible && fill.type === 'IMAGE')}@@ -62,6 +46,49 @@ export function canMakeBooleanSourceNode(node: SceneNode, graph: SceneGraph): bo})}+function unitedPath(r: SkiaRenderer, regions: Path[]): Path | null {+ let merged = regions[0].copy()+ for (let index = 1; index < regions.length; index++) {+ const union = r.ck.Path.MakeFromOp(merged, regions[index], r.ck.PathOp.Union)+ merged.delete()+ if (!union) {+ return null+ }+ merged = union+ }+ return merged+}++function fillGeometryPath(r: SkiaRenderer, node: SceneNode): Path | null {+ if (typeof r.getFillGeometry !== 'function') {+ return null+ }+ const regions = r.getFillGeometry(node)+ if (!regions || regions.length === 0) {+ return null+ }+ return sharedPath(r.nodePaths, `${node.id}|saved-fill`, 'united', regions, () =>+ unitedPath(r, regions)+ )+}++function networkRegionsPath(r: SkiaRenderer, node: SceneNode): Path | null {+ if ((node.vectorNetwork?.regions.length ?? 0) < 2) {+ return null+ }+ const regions = r.getVectorPaths(node)+ if (!regions || regions.length === 0) {+ return null+ }+ return sharedPath(r.nodePaths, `${node.id}|network-fill`, 'united', regions, () =>+ unitedPath(r, regions)+ )+}++function savedFillShape(r: SkiaRenderer, node: SceneNode): Path | null {+ return fillGeometryPath(r, node) ?? networkRegionsPath(r, node)+}+/** A layer's shape in its own box: its outline, a line's stroke, or text's glyph outlines. */export function baseShapePath(r: SkiaRenderer, node: SceneNode): Path | null {if (node.type === 'TEXT') return textNodeToOutlinePath(r, node)@@ -69,6 +96,59 @@ export function baseShapePath(r: SkiaRenderer, node: SceneNode): Path | null {return r.makeNodeShapePath(node)}+function strokeSourcePath(r: SkiaRenderer, node: SceneNode): Path | null {+ const network = node.type === 'VECTOR' ? r.getVectorPaths(node) : null+ if (!network || network.length === 0) {+ return baseShapePath(r, node)+ }+ return joinedPath(r, network)+}++function joinedPath(r: SkiaRenderer, parts: Path[]): Path {+ const path = new r.ck.PathBuilder()+ for (const part of parts) {+ path.addPath(part)+ }+ const joined = path.detachAndDelete()+ const fillType = parts[0].getFillType()+ if (parts.every((part) => part.getFillType().value === fillType.value)) {+ joined.setFillType(fillType)+ }+ return joined+}++interface VectorStrokeSides {+ fill: Path+ regions: Path+ looseSegments: Path | null+}++function addVectorStrokeOutlines(+ r: SkiaRenderer,+ pieces: Path[],+ outline: Path,+ node: SceneNode,+ fill: Path+): void {+ const regionCount = node.vectorNetwork?.regions.length ?? 0+ const parts = regionCount > 0 ? r.getVectorPaths(node) : null+ if (!parts || parts.length <= regionCount) {+ addVisibleStrokeOutlines(r, pieces, outline, node, {+ fill,+ regions: outline,+ looseSegments: null+ })+ return+ }+ const regions = joinedPath(r, parts.slice(0, regionCount))+ addVisibleStrokeOutlines(r, pieces, outline, node, {+ fill,+ regions,+ looseSegments: parts[regionCount]+ })+ regions.delete()+}+export function nodeHasVisibleFill(node: SceneNode): boolean {return node.fills.some((fill) => fill.visible)}@@ -78,48 +158,146 @@ export function nodeHasVisibleStroke(node: SceneNode): boolean {}/**- * The area a stroke paints along `source`, as the canvas draws it: centred on the path, or, on a- * layer whose outline it keeps to, twice its weight cut to inside or outside the outline. Vectors- * stroke their paths centred whatever the alignment, as the canvas draws them.+ * Figma shapes a boolean operand by the paints that draw, visible and above 0%: a fill gives its+ * area and each stroke its band. An operand none of whose paints draw gives its area (live-verified).*/-function strokeArea(r: SkiaRenderer, source: Path, node: SceneNode, stroke: Stroke): Path | null {- const aligned = stroke.align !== 'CENTER' && node.type !== 'VECTOR'- const outline = source.makeStroked({ width: aligned ? stroke.weight * 2 : stroke.weight })- if (!outline || !aligned) return outline- const op = stroke.align === 'INSIDE' ? r.ck.PathOp.Intersect : r.ck.PathOp.Difference- const area = r.ck.Path.MakeFromOp(outline, source, op)- outline.delete()- // An op's result fills even-odd; turned to non-zero, it keeps its holes when added to others.- const winding = area?.makeAsWinding() ?? null- area?.delete()- return winding+function drawsPaint(paint: Fill | Stroke): boolean {+ return paint.visible && paint.opacity > 0+}++function drawsFill(node: SceneNode): boolean {+ return node.fills.some(drawsPaint)+}++function drawsStroke(node: SceneNode): boolean {+ return node.strokes.some((stroke) => drawsPaint(stroke) && stroke.weight > 0)+}++function strokeSide(node: SceneNode, stroke: Stroke): Stroke['align'] {+ const network = node.type === 'VECTOR' ? node.vectorNetwork : null+ return network && isOpenVectorNetwork(network) ? 'CENTER' : stroke.align+}++function strokeArea(+ r: SkiaRenderer,+ source: Path,+ weight: number,+ side: Stroke['align'],+ filledShape: Path = source+): Path | null {+ if (side === 'CENTER') {+ return source.makeStroked({ width: weight })+ }+ const band = source.makeStroked({ width: weight * 2 })+ if (!band) {+ return null+ }+ const keptSide = side === 'INSIDE' ? r.ck.PathOp.Intersect : r.ck.PathOp.Difference+ const area = r.ck.Path.MakeFromOp(band, filledShape, keptSide)+ band.delete()+ return area}/** The area every visible stroke of `node` paints along `source`, or null when none paints. */export function strokeAreaPath(r: SkiaRenderer, source: Path, node: SceneNode): Path | null {- const builder = new r.ck.PathBuilder()- addVisibleStrokeOutlines(r, builder, source, node)- const path = builder.detachAndDelete()- if (!path.isEmpty()) return path- path.delete()+ const pieces: Path[] = []+ addVisibleStrokeOutlines(r, pieces, source, node, null)+ const path = unitedPieces(r, pieces)+ if (path && !path.isEmpty()) return path+ path?.delete()return null}function addVisibleStrokeOutlines(r: SkiaRenderer,- target: PathBuilder,+ pieces: Path[],source: Path,- node: SceneNode+ node: SceneNode,+ vectorSides: VectorStrokeSides | null): void {for (const stroke of node.strokes) {- if (!stroke.visible || stroke.weight <= 0) continue- const area = strokeArea(r, source, node, stroke)- if (!area) continue- target.addPath(area)- area.delete()+ if (!drawsPaint(stroke) || stroke.weight <= 0) continue+ const side = strokeSide(node, stroke)+ if (vectorSides && side !== 'CENTER') {+ addSidedVectorStroke(r, pieces, node, stroke.weight, side, vectorSides)+ continue+ }+ keepPiece(pieces, strokeArea(r, source, stroke.weight, side))+ }+}++function addSidedVectorStroke(+ r: SkiaRenderer,+ pieces: Path[],+ node: SceneNode,+ weight: number,+ side: Stroke['align'],+ sides: VectorStrokeSides+): void {+ keepPiece(pieces, vectorStrokeArea(r, sides.regions, node, weight, side, sides.fill))+ if (sides.looseSegments) {+ keepPiece(pieces, strokeArea(r, sides.looseSegments, weight, 'CENTER'))+ }+}++function addStrokePieces(+ r: SkiaRenderer,+ pieces: Path[],+ outline: Path,+ node: SceneNode,+ fill: Path+): void {+ if (node.type === 'VECTOR') {+ addVectorStrokeOutlines(r, pieces, outline, node, fill)+ } else {+ addVisibleStrokeOutlines(r, pieces, outline, node, null)}}+function keepPiece(pieces: Path[], path: Path | null): void {+ if (path) {+ pieces.push(path)+ }+}++// A union op reads each piece's own fill rule; concatenating them under one rule fills their holes.+function unitedPieces(r: SkiaRenderer, pieces: Path[]): Path | null {+ if (pieces.length <= 1) {+ return pieces[0] ?? null+ }+ const united = unitedPath(r, pieces)+ deletePaths(pieces)+ return united+}++function operandPath(r: SkiaRenderer, node: SceneNode, pieces: Path[]): Path | null {+ if (pieces.length <= 1) {+ return pieces[0] ?? null+ }+ const united = sharedPath(r.nodePaths, `${node.id}|operand`, 'operand', pieces, () =>+ unitedPath(r, pieces)+ )+ deletePaths(pieces)+ return united+}++function vectorStrokeArea(+ r: SkiaRenderer,+ source: Path,+ node: SceneNode,+ weight: number,+ side: Stroke['align'],+ filledShape: Path+): Path | null {+ return sharedPath(+ r.nodePaths,+ `${node.id}|aligned|${weight}|${side}`,+ `band|${weight}|${side}`,+ [source, filledShape],+ () => strokeArea(r, source, weight, side, filledShape)+ )+}+export function canContainFlattenableChildren(node: SceneNode): boolean {return (node.type === 'GROUP' ||@@ -129,63 +307,23 @@ export function canContainFlattenableChildren(node: SceneNode): boolean {)}-function appendVisibleChildPaths(- r: SkiaRenderer,- graph: SceneGraph,- parent: SceneNode,- target: PathBuilder,- makeChildPath: (child: SceneNode) => Path | null,- failOnMissing: boolean-): boolean | null {- let hasPath = false- for (const childId of parent.childIds) {+/**+ * A frame, group, component or instance gives a boolean operation, or Flatten, only its children's+ * shapes: Figma leaves its own fill and stroke out (live-verified).+ */+function containerSourcePath(r: SkiaRenderer, node: SceneNode, graph: SceneGraph): Path | null {+ const pieces: Path[] = []+ for (const childId of node.childIds) {const child = graph.getNode(childId)if (!child || !child.visible) continue- const childPath = makeChildPath(child)+ const childPath = transformedShapePath(r, child, graph)if (!childPath) {- if (failOnMissing) return null- continue+ deletePaths(pieces)+ return null}- target.addPath(childPath, nodePathTransform(r, child))- childPath.delete()- hasPath = true+ pieces.push(childPath)}- return hasPath-}--function containerSourcePath(r: SkiaRenderer, node: SceneNode, graph: SceneGraph): Path | null {- const path = new r.ck.PathBuilder()- let hasPath = false-- if (nodeHasVisibleFill(node) || nodeHasVisibleStroke(node)) {- const ownPath = baseShapePath(r, node)- if (ownPath) {- if (nodeHasVisibleFill(node)) path.addPath(ownPath)- addVisibleStrokeOutlines(r, path, ownPath, node)- ownPath.delete()- hasPath = true- }- }-- const childPaths = appendVisibleChildPaths(- r,- graph,- node,- path,- (child) => makeBooleanSourcePath(r, child, graph),- true- )- if (childPaths === null) {- path.delete()- return null- }- hasPath ||= childPaths-- if (!hasPath) {- path.delete()- return null- }- return path.detachAndDelete()+ return operandPath(r, node, pieces)}export function makeBooleanSourcePath(@@ -198,23 +336,46 @@ export function makeBooleanSourcePath(if (canContainFlattenableChildren(node)) return containerSourcePath(r, node, graph)if (node.type === 'LINE') return baseShapePath(r, node)- const path = baseShapePath(r, node)- if (!path) return null- if (!nodeHasVisibleStroke(node)) return path- const combined = new r.ck.PathBuilder()- combined.addPath(path)- addVisibleStrokeOutlines(r, combined, path, node)- path.delete()- return combined.detachAndDelete()+ const savedFill = node.type === 'VECTOR' ? savedFillShape(r, node) : null+ const stroked = drawsStroke(node)+ if (savedFill && !stroked) {+ return savedFill+ }+ const outline = strokeSourcePath(r, node)+ if (!outline) {+ savedFill?.delete()+ return null+ }+ if (!stroked) {+ return outline+ }+ const fill = savedFill ?? outline+ const pieces = drawsFill(node) ? [fill.copy()] : []+ addStrokePieces(r, pieces, outline, node, fill)+ savedFill?.delete()+ outline.delete()+ return operandPath(r, node, pieces)}function transformedShapePath(r: SkiaRenderer, child: SceneNode, graph: SceneGraph): Path | null {const path = makeBooleanSourcePath(r, child, graph)if (!path) return null- const transformed = new r.ck.PathBuilder()- transformed.addPath(path, nodePathTransform(r, child))+ const placed = placedPath(r, path, getNodeLocalMatrix(child))path.delete()- return transformed.detachAndDelete()+ return placed+}++/** `path` moved by `matrix`; a builder drops the fill rule, so it is set back. */+export function placedPath(r: SkiaRenderer, path: Path, matrix: number[]): Path {+ const builder = new r.ck.PathBuilder()+ builder.addPath(path, matrix)+ const placed = builder.detachAndDelete()+ placed.setFillType(path.getFillType())+ return placed+}++export function windingRuleOf(r: SkiaRenderer, path: Path): WindingRule {+ return path.getFillType().value === r.ck.FillType.EvenOdd.value ? 'EVENODD' : 'NONZERO'}function operationForNode(r: SkiaRenderer, node: SceneNode): PathOp {@@ -222,43 +383,75 @@ function operationForNode(r: SkiaRenderer, node: SceneNode): PathOp {return r.ck.PathOp[BOOLEAN_PATH_OP[operation]]}-function makeImportedFillGeometryPath(r: SkiaRenderer, node: SceneNode): Path | null {- if (typeof r.getFillGeometry !== 'function') return null- const fillGeometry = r.getFillGeometry(node)- if (!fillGeometry) return null- const result = new r.ck.PathBuilder()- for (const path of fillGeometry) result.addPath(path)- return result.detachAndDelete()-}-export function makeBooleanOperationPath(r: SkiaRenderer,node: SceneNode,graph: SceneGraph): Path | null {- const childPaths: Path[] = []+ const operands: Path[] = []for (const childId of node.childIds) {const child = graph.getNode(childId)- if (!child || !child.visible) continue+ if (!child || !child.visible) {+ continue+ }const path = transformedShapePath(r, child, graph)- if (path) childPaths.push(path)+ if (path) {+ operands.push(path)+ }+ }+ if (operands.length === 0) {+ return fillGeometryPath(r, node)}+ const signature = `${node.booleanOperation ?? 'UNION'}|${node.cornerRadius}`+ const result = sharedPath(+ r.nodePaths,+ `${node.id}|boolean|${signature}`,+ `boolean|${signature}`,+ operands,+ () => combinedOperands(r, node, operands)+ )+ deletePaths(operands)+ return result ?? fillGeometryPath(r, node)+}- if (childPaths.length === 0) return makeImportedFillGeometryPath(r, node)+function deletePaths(paths: Path[]): void {+ for (const path of paths) {+ path.delete()+ }+}- let result = childPaths[0]+function combinedOperands(r: SkiaRenderer, node: SceneNode, operands: Path[]): Path | null {const operation = operationForNode(r, node)- for (let index = 1; index < childPaths.length; index++) {- const path = childPaths[index]- const combined = r.ck.Path.MakeFromOp(result, path, operation)+ let result = operands[0].copy()+ for (let index = 1; index < operands.length; index++) {+ const combined = r.ck.Path.MakeFromOp(result, operands[index], operation)result.delete()- path.delete()if (!combined) {- for (const remaining of childPaths.slice(index + 1)) remaining.delete()- return makeImportedFillGeometryPath(r, node)+ return null}result = combined}+ if (node.cornerRadius <= 0) {+ return result+ }+ const rounded = withRoundedCorners(r, result, node.cornerRadius)+ result.delete()+ return rounded+}++function withRoundedCorners(r: SkiaRenderer, path: Path, radius: number): Path {+ const { vertices, segments, regions } = parseSVGPath(path.toSVGString(), 'NONZERO', {+ includeOpenRegions: true+ })+ const rounded = new r.ck.PathBuilder()+ for (const region of regions) {+ for (const loop of region.loops) {+ const contour = loop.map((index) => segments[index])+ addOpenSegmentsToPath(rounded, contour, vertices, radius)+ }+ }+ const result = rounded.detachAndDelete()+ result.setFillType(path.getFillType())return result}@@ -314,15 +507,28 @@ export function paintBooleanOperation(if (!stroke.visible) continueconst color = r.resolveStrokeColor(stroke, 0, node, graph)r.strokePaint.setColor(r.ck.Color4f(color.r, color.g, color.b, color.a))- r.strokePaint.setStrokeWidth(stroke.weight)r.strokePaint.setAlphaf(stroke.opacity)- canvas.drawPath(path, r.strokePaint)+ drawAlignedStroke(r, canvas, path, stroke)}} finally {path.delete()}}+function drawAlignedStroke(r: SkiaRenderer, canvas: Canvas, path: Path, stroke: Stroke): void {+ if (stroke.align === 'CENTER') {+ r.strokePaint.setStrokeWidth(stroke.weight)+ canvas.drawPath(path, r.strokePaint)+ return+ }+ const keptSide = stroke.align === 'INSIDE' ? r.ck.ClipOp.Intersect : r.ck.ClipOp.Difference+ canvas.save()+ canvas.clipPath(path, keptSide, true)+ r.strokePaint.setStrokeWidth(stroke.weight * 2)+ canvas.drawPath(path, r.strokePaint)+ canvas.restore()+}+/** Draws a boolean operation with its shadows: inner shadows sit over its fills, under strokes. */export function renderBooleanOperation(r: SkiaRenderer,diff --git a/packages/core/src/canvas/flatten.ts b/packages/core/src/canvas/flatten.tsindex 9d85452a8..13a8f5f86 100644--- a/packages/core/src/canvas/flatten.ts+++ b/packages/core/src/canvas/flatten.ts@@ -1,8 +1,13 @@-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import type { Path } from 'canvaskit-wasm'++import type { SceneGraph, SceneNode, VectorNetwork } from '@open-pencil/scene-graph'+import { getNodeLocalMatrix } from '@open-pencil/scene-graph/coordinate'import { copyFills } from '@open-pencil/scene-graph/copy'import { parseSVGPath } from '@open-pencil/scene-graph/parse-path'+import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'+import { mergeVectorNetworks } from '@open-pencil/scene-graph/vector-network'-import { makeBooleanSourcePath, nodePathTransform } from './boolean'+import { makeBooleanSourcePath, placedPath, windingRuleOf } from './boolean'import type { SkiaRenderer } from './renderer'export type VectorFlattenProps = Pick<@@ -22,37 +27,44 @@ function nodesToVectorProps(nodes: SceneNode[],makeNodePath: NodePathFactory): VectorFlattenProps | null {- const path = new renderer.ck.PathBuilder()- for (const node of nodes) {- const nodePath = makeNodePath(renderer, graph, node)- if (!nodePath) {- path.delete()- return null+ const placed: Path[] = []+ try {+ for (const node of nodes) {+ const nodePath = makeNodePath(renderer, graph, node)+ if (!nodePath) return null+ placed.push(placedPath(renderer, nodePath, getNodeLocalMatrix(node)))+ nodePath.delete()}- path.addPath(nodePath, nodePathTransform(renderer, node))- nodePath.delete()- }-- const bounds = path.getBounds()- if (bounds[2] <= bounds[0] || bounds[3] <= bounds[1]) {- path.delete()- return null+ const drawn = placed.filter((path) => !path.isEmpty())+ const box = boundsOf(drawn)+ if (!box) return null+ return {+ name: 'Flatten',+ ...box,+ fills: copyFills(nodes[0].fills),+ vectorNetwork: mergeVectorNetworks(drawn.map((path) => networkIn(renderer, path, box)))+ }+ } finally {+ for (const path of placed) path.delete()}+}- path.transform(renderer.ck.Matrix.translated(-bounds[0], -bounds[1]))- const immutablePath = path.detachAndDelete()- const vectorNetwork = parseSVGPath(immutablePath.toSVGString())- immutablePath.delete()+function boundsOf(paths: Path[]): Rect | null {+ if (paths.length === 0) return null+ const all = paths.map((path) => path.getBounds())+ const left = Math.min(...all.map((bounds) => bounds[0]))+ const top = Math.min(...all.map((bounds) => bounds[1]))+ const right = Math.max(...all.map((bounds) => bounds[2]))+ const bottom = Math.max(...all.map((bounds) => bounds[3]))+ if (right <= left || bottom <= top) return null+ return { x: left, y: top, width: right - left, height: bottom - top }+}- return {- name: 'Flatten',- x: bounds[0],- y: bounds[1],- width: bounds[2] - bounds[0],- height: bounds[3] - bounds[1],- fills: copyFills(nodes[0].fills),- vectorNetwork- }+function networkIn(renderer: SkiaRenderer, path: Path, box: Vector): VectorNetwork {+ const moved = placedPath(renderer, path, renderer.ck.Matrix.translated(-box.x, -box.y))+ const network = parseSVGPath(moved.toSVGString(), windingRuleOf(renderer, moved))+ moved.delete()+ return network}export function flattenNodesToVectorProps(diff --git a/packages/core/src/canvas/outline-stroke.ts b/packages/core/src/canvas/outline-stroke.tsindex 1214e7189..14735bb71 100644--- a/packages/core/src/canvas/outline-stroke.ts+++ b/packages/core/src/canvas/outline-stroke.ts@@ -14,7 +14,9 @@ import {makeBooleanOperationPath,nodeHasVisibleFill,nodeHasVisibleStroke,- strokeAreaPath+ placedPath,+ strokeAreaPath,+ windingRuleOf} from './boolean'import type { SkiaRenderer } from './renderer'import { textGlyphPaths } from './text/outlines'@@ -76,10 +78,8 @@ function boundsOf(paths: readonly Path[]): Box | null {/** A path as a vector network, moved so `box` starts at the origin. */function networkIn(r: SkiaRenderer, path: Path, box: Box): SceneNode['vectorNetwork'] {- const builder = new r.ck.PathBuilder()- builder.addPath(path, r.ck.Matrix.translated(-box.x, -box.y))- const moved = builder.detachAndDelete()- const network = parseSVGPath(moved.toSVGString())+ const moved = placedPath(r, path, r.ck.Matrix.translated(-box.x, -box.y))+ const network = parseSVGPath(moved.toSVGString(), windingRuleOf(r, moved))moved.delete()return network}diff --git a/packages/core/src/canvas/paths/cache.ts b/packages/core/src/canvas/paths/cache.tsindex 6f3e27b3c..e68250923 100644--- a/packages/core/src/canvas/paths/cache.ts+++ b/packages/core/src/canvas/paths/cache.ts@@ -56,6 +56,8 @@ export class NodePathCaches {readonly strokeOutline: NodePathCachereadonly fillGeometry: NodePathCachereadonly strokeGeometry: NodePathCache+ readonly shared: NodePathCache+ readonly sharedKeys: ResourceCache<string, string>private readonly caches: readonly NodePathCache[]private uncached: Path[][] = []@@ -65,12 +67,17 @@ export class NodePathCaches {this.strokeOutline = createPathCache(limits)this.fillGeometry = createPathCache(limits)this.strokeGeometry = createPathCache(limits)+ this.shared = createPathCache(limits)+ this.sharedKeys = new ResourceCache<string, string>({+ maxEntries: limits.maxEntries ?? PATH_CACHE_ENTRIES+ })this.caches = [this.vector,this.vectorStroke,this.strokeOutline,this.fillGeometry,- this.strokeGeometry+ this.strokeGeometry,+ this.shared]}@@ -84,6 +91,7 @@ export class NodePathCaches {for (const cache of this.caches) cache.delete(nodeId)const outlinePrefix = `${nodeId}|`this.strokeOutline.deleteWhere((_, key) => key.startsWith(outlinePrefix))+ this.sharedKeys.deleteWhere((_, key) => key.startsWith(outlinePrefix))}/** Deletes the paths `store` could not cache. */@@ -96,6 +104,7 @@ export class NodePathCaches {clear(): void {for (const cache of this.caches) cache.clear()+ this.sharedKeys.clear()this.releaseUncached()}}diff --git a/packages/core/src/canvas/paths/shared.ts b/packages/core/src/canvas/paths/shared.tsnew file mode 100644index 000000000..777240202--- /dev/null+++ b/packages/core/src/canvas/paths/shared.ts@@ -0,0 +1,51 @@+import type { Path } from 'canvaskit-wasm'++import type { NodePathCaches } from './cache'++export function sharedPath(+ caches: NodePathCaches,+ ownKey: string,+ scope: string,+ inputs: Path[],+ build: () => Path | null+): Path | null {+ const previousKey = caches.sharedKeys.get(ownKey)+ const previous = previousKey === undefined ? null : builtFrom(caches, previousKey, inputs)+ if (previous) {+ return previous.copy()+ }+ const key = `${scope}|${pathsDigest(inputs)}`+ const matching = builtFrom(caches, key, inputs)+ if (matching) {+ caches.sharedKeys.set(ownKey, key)+ return matching.copy()+ }+ const result = build()+ if (!result) {+ return null+ }+ if (previousKey !== undefined && previousKey !== key) {+ caches.shared.delete(previousKey)+ }+ caches.store(caches.shared, key, [...inputs.map((input) => input.copy()), result.copy()])+ caches.sharedKeys.set(ownKey, key)+ return result+}++function builtFrom(caches: NodePathCaches, key: string, inputs: Path[]): Path | null {+ const cached = caches.shared.get(key)+ if (!cached || cached.length !== inputs.length + 1) {+ return null+ }+ return inputs.every((input, index) => cached[index].equals(input)) ? cached[inputs.length] : null+}++function pathsDigest(paths: Path[]): string {+ return paths.map(pathDigest).join('|')+}++function pathDigest(path: Path): string {+ const points = path.countPoints()+ const ends = points > 0 ? [...path.getPoint(0), ...path.getPoint(points - 1)].join(',') : ''+ return `${path.getFillType().value}:${points}:${path.getBounds().join(',')}:${ends}`+}diff --git a/packages/core/src/canvas/scene.ts b/packages/core/src/canvas/scene.tsindex 83de14a4a..1c14de2b4 100644--- a/packages/core/src/canvas/scene.ts+++ b/packages/core/src/canvas/scene.ts@@ -22,6 +22,7 @@ import {vectorNetworkToCenterlinePath,vectorNetworkToPath} from '#core/vector'+import { isOpenVectorNetwork } from '#core/vector/connectivity'import { figmaBlendModeToSkia, needsIsolatedBlendLayer } from './blend'import { renderBooleanOperation } from './boolean'@@ -779,22 +780,15 @@ function drawAlignedVectorPathStrokes(// `vectorNetworkToPath` lists a path for each region, then one for the open segments.const regions = node.vectorNetwork?.regions.length ?? 0const closed = vectorPaths.slice(0, regions)- // The inside of the regions, which an inside stroke keeps to; a union that fails strokes centred.const inside = stroke.align === 'INSIDE' && closed.length > 0 ? unitePaths(r, closed) : null- const sided = stroke.align === 'OUTSIDE' ? closed.length > 0 : !!inside+ const sided = clipToStrokeSide(r, canvas, closed, stroke.align, inside)+ inside?.delete()if (!sided) {const outlineKey = strokeOutlineKey(node, stroke, 'regions')drawVectorPathStrokes(r, canvas, vectorPaths, stroke, sc, miter, outlineKey)return}const doubled = { ...stroke, weight: stroke.weight * 2 }- canvas.save()- if (inside) {- canvas.clipPath(inside, r.ck.ClipOp.Intersect, true)- inside.delete()- } else {- for (const path of closed) canvas.clipPath(path, r.ck.ClipOp.Difference, true)- }drawVectorPathStrokes(r,canvas,@@ -818,6 +812,41 @@ function drawAlignedVectorPathStrokes()}+function clipToStrokeSide(+ r: SkiaRenderer,+ canvas: Canvas,+ closed: Path[],+ align: SceneNode['strokes'][0]['align'],+ inside: Path | null+): boolean {+ if (align === 'OUTSIDE' && closed.length > 0) {+ canvas.save()+ for (const path of closed) {+ canvas.clipPath(path, r.ck.ClipOp.Difference, true)+ }+ return true+ }+ if (align !== 'INSIDE' || !inside) {+ return false+ }+ canvas.save()+ canvas.clipPath(inside, r.ck.ClipOp.Intersect, true)+ return true+}++function cachedFillUnion(r: SkiaRenderer, node: SceneNode, fillPaths: Path[]): Path | null {+ const key = `${node.id}|fill-union`+ const cached = r.nodePaths.strokeOutline.get(key)+ if (cached) {+ return cached[0]+ }+ const united = unitePaths(r, fillPaths)+ if (united) {+ r.nodePaths.store(r.nodePaths.strokeOutline, key, [united])+ }+ return united+}+/** One path covering every path given, which a clip can keep the inside of. */function unitePaths(r: SkiaRenderer, paths: Path[]): Path | null {let united: Path | null = paths[0]?.copy() ?? null@@ -856,6 +885,10 @@ function drawNodeStroke(else drawRegularStroke(r, canvas, node, stroke, sc)return}+ if (node.type === 'VECTOR' && stroke.align !== 'CENTER') {+ drawFillSideStrokeGeometry(r, canvas, node, stroke, sc, sg)+ return+ }if (stroke.align !== 'INSIDE') {if (node.type === 'VECTOR' || node.type === 'TEXT') {drawVectorStrokeGeometry(r, canvas, sg, sc, stroke.opacity)@@ -863,18 +896,27 @@ function drawNodeStroke(return}- const clipPaths = node.type === 'VECTOR' ? r.getFillGeometry(node) : null- if (node.type === 'VECTOR' && !clipPaths) {+ canvas.save()+ r.clipNodeShape(canvas, node)+ drawVectorStrokeGeometry(r, canvas, sg, sc, stroke.opacity)+ canvas.restore()+}++function drawFillSideStrokeGeometry(+ r: SkiaRenderer,+ canvas: Canvas,+ node: SceneNode,+ stroke: SceneNode['strokes'][0],+ sc: Color,+ sg: Path[]+): void {+ const fillPaths = r.getFillGeometry(node)+ const sideable = fillPaths && !(node.vectorNetwork && isOpenVectorNetwork(node.vectorNetwork))+ const inside = sideable && stroke.align === 'INSIDE' ? cachedFillUnion(r, node, fillPaths) : null+ if (!sideable || !clipToStrokeSide(r, canvas, fillPaths, stroke.align, inside)) {drawVectorStrokeGeometry(r, canvas, sg, sc, stroke.opacity)return}-- canvas.save()- if (clipPaths) {- for (const path of clipPaths) canvas.clipPath(path, r.ck.ClipOp.Intersect, true)- } else {- r.clipNodeShape(canvas, node)- }drawVectorStrokeGeometry(r, canvas, sg, sc, stroke.opacity)canvas.restore()}diff --git a/packages/core/src/vector/connectivity.ts b/packages/core/src/vector/connectivity.tsindex a86f8230f..833415408 100644--- a/packages/core/src/vector/connectivity.ts+++ b/packages/core/src/vector/connectivity.ts@@ -93,3 +93,15 @@ export function extractSubNetwork(network: VectorNetwork, vertexIndices: number[return { vertices: newVertices, segments: newSegments, regions: newRegions }}++export function isOpenVectorNetwork(network: VectorNetwork): boolean {+ if (network.regions.length > 0) {+ return false+ }+ const segmentEnds = new Uint16Array(network.vertices.length)+ for (const segment of network.segments) {+ segmentEnds[segment.start]+++ segmentEnds[segment.end]+++ }+ return segmentEnds.some((count) => count === 1)+}diff --git a/packages/core/tests/canvas/boolean.test.ts b/packages/core/tests/canvas/boolean.test.tsnew file mode 100644index 000000000..84584ff11--- /dev/null+++ b/packages/core/tests/canvas/boolean.test.ts@@ -0,0 +1,566 @@+import { afterAll, describe, expect, spyOn, test } from 'bun:test'++import { expectDefined } from '#core-tests/helpers/assert'+import { renderRow } from '#core-tests/helpers/figma-rows'++import { SkiaRenderer } from '@open-pencil/core/canvas'+import { initCanvasKit } from '@open-pencil/core/io/formats/raster'+import { SceneGraph, type Stroke } from '@open-pencil/scene-graph'++import { makeBooleanOperationPath } from '#core/canvas/boolean'++const ck = await initCanvasKit()+const renderer = new SkiaRenderer(ck, expectDefined(ck.MakeSurface(1, 1)))+afterAll(() => renderer.destroy())++const SIZE = 160+const WEIGHT = 8+const RED = { r: 1, g: 0, b: 0, a: 1 }++/** The opacities of the operand's fill and stroke. */+interface OperandOpacity {+ fill: number+ stroke: number+}++function unionWithStrokedOperand(+ align: Stroke['align'],+ operandFillVisible: boolean,+ opacity: OperandOpacity = { fill: 1, stroke: 1 }+) {+ return (graph: SceneGraph, hostId: string) => {+ const operation = graph.createNode('BOOLEAN_OPERATION', hostId, {+ x: 120,+ y: 70,+ width: SIZE,+ height: SIZE,+ booleanOperation: 'UNION',+ fills: [{ type: 'SOLID', color: RED, opacity: 1, visible: true }]+ })+ graph.createNode('RECTANGLE', operation.id, {+ width: SIZE,+ height: SIZE,+ fills: [{ type: 'SOLID', color: RED, opacity: opacity.fill, visible: operandFillVisible }],+ strokes: [+ { type: 'SOLID', color: RED, opacity: opacity.stroke, visible: true, weight: WEIGHT, align }+ ],+ strokeWeight: WEIGHT,+ strokeAlign: align+ })+ graph.createNode('RECTANGLE', operation.id, {+ width: 10,+ height: 10,+ fills: [{ type: 'SOLID', color: RED, opacity: 1, visible: true }]+ })+ }+}++function unionWithOpenOutsideStroke(graph: SceneGraph, hostId: string) {+ const operation = graph.createNode('BOOLEAN_OPERATION', hostId, {+ x: 120,+ y: 70,+ width: SIZE,+ height: SIZE,+ booleanOperation: 'UNION',+ fills: [{ type: 'SOLID', color: RED, opacity: 1, visible: true }]+ })+ graph.createNode('VECTOR', operation.id, {+ width: SIZE,+ height: SIZE,+ strokes: [+ { type: 'SOLID', color: RED, opacity: 1, visible: true, weight: WEIGHT, align: 'OUTSIDE' }+ ],+ strokeWeight: WEIGHT,+ strokeAlign: 'OUTSIDE',+ vectorNetwork: {+ vertices: [+ { x: 0, y: SIZE / 2 },+ { x: SIZE, y: SIZE / 2 }+ ],+ segments: [{ start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }],+ regions: []+ }+ })+ graph.createNode('RECTANGLE', operation.id, {+ width: 10,+ height: 10,+ fills: [{ type: 'SOLID', color: RED, opacity: 1, visible: true }]+ })+}++function leftEdgeAlpha(+ align: Stroke['align'],+ operandFillVisible: boolean,+ opacity?: OperandOpacity+): number[] {+ const scene = unionWithStrokedOperand(align, operandFillVisible, opacity)+ return renderRow(ck, renderer, scene, 150, 104, 134)+}++function unionWithOpenStrokedOperand(graph: SceneGraph, hostId: string) {+ const operation = graph.createNode('BOOLEAN_OPERATION', hostId, {+ x: 120,+ y: 70,+ width: SIZE,+ height: SIZE,+ booleanOperation: 'UNION',+ fills: [{ type: 'SOLID', color: RED, opacity: 1, visible: true }]+ })+ graph.createNode('VECTOR', operation.id, {+ width: SIZE,+ height: SIZE,+ fills: [{ type: 'SOLID', color: RED, opacity: 1, visible: false }],+ strokes: [+ { type: 'SOLID', color: RED, opacity: 1, visible: true, weight: WEIGHT, align: 'CENTER' }+ ],+ strokeWeight: WEIGHT,+ strokeAlign: 'CENTER',+ vectorNetwork: {+ vertices: [+ { x: 0, y: 0 },+ { x: SIZE, y: 0 },+ { x: SIZE, y: SIZE }+ ],+ segments: [+ { start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },+ { start: 1, end: 2, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }+ ],+ regions: []+ },+ fillGeometry: [+ {+ windingRule: 'NONZERO',+ commandsBlob: contoursBlob([+ [+ [0, 0],+ [SIZE, 0],+ [SIZE, SIZE]+ ]+ ])+ }+ ]+ })+}++describe('a vector boolean operand’s stroke', () => {+ test('follows its open path, without the edge that closes its fill', () => {+ expect(renderRow(ck, renderer, unionWithOpenStrokedOperand, 150, 190, 210)).toEqual([+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0+ ])+ })+})++function unionWithOverlappingRegionsOperand(graph: SceneGraph, hostId: string) {+ const operation = graph.createNode('BOOLEAN_OPERATION', hostId, {+ x: 120,+ y: 70,+ width: SIZE,+ height: SIZE,+ booleanOperation: 'UNION',+ fills: [{ type: 'SOLID', color: RED, opacity: 1, visible: true }]+ })+ graph.createNode('VECTOR', operation.id, {+ width: SIZE,+ height: SIZE,+ fills: [{ type: 'SOLID', color: RED, opacity: 1, visible: true }],+ vectorNetwork: { vertices: [], segments: [], regions: [] },+ fillGeometry: [+ { windingRule: 'NONZERO', commandsBlob: contoursBlob([box(0, 0, 100, 100)]) },+ { windingRule: 'NONZERO', commandsBlob: contoursBlob([box(50, 50, 150, 150).reverse()]) }+ ]+ })+}++describe('a vector boolean operand with several fill regions', () => {+ test('covers their overlap whatever their directions', () => {+ expect(renderRow(ck, renderer, unionWithOverlappingRegionsOperand, 145, 170, 230)).toEqual(+ Array.from({ length: 31 }, () => 255)+ )+ })+})++function countPathOps(build: () => void): number {+ const pathOps = spyOn(ck.Path, 'MakeFromOp')+ try {+ build()+ return pathOps.mock.calls.length+ } finally {+ pathOps.mockRestore()+ }+}++function unionWithInsideStrokedVector(graph: SceneGraph, hostId: string) {+ const operation = graph.createNode('BOOLEAN_OPERATION', hostId, {+ width: SIZE,+ height: SIZE,+ booleanOperation: 'UNION',+ fills: [{ type: 'SOLID', color: RED, opacity: 1, visible: true }]+ })+ graph.createNode('VECTOR', operation.id, {+ width: SIZE,+ height: SIZE,+ fills: [{ type: 'SOLID', color: RED, opacity: 1, visible: false }],+ strokes: [+ { type: 'SOLID', color: RED, opacity: 1, visible: true, weight: WEIGHT, align: 'INSIDE' }+ ],+ strokeWeight: WEIGHT,+ strokeAlign: 'INSIDE',+ vectorNetwork: {+ vertices: [+ { x: 0, y: 0 },+ { x: SIZE, y: 0 },+ { x: SIZE, y: SIZE },+ { x: 0, y: SIZE }+ ],+ segments: [+ { start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },+ { start: 1, end: 2, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },+ { start: 2, end: 3, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },+ { start: 3, end: 0, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }+ ],+ regions: [{ windingRule: 'NONZERO', loops: [[0, 1, 2, 3]] }]+ }+ })+ return operation.id+}++function withFreshRenderer<T>(use: (fresh: SkiaRenderer) => T): T {+ const fresh = new SkiaRenderer(ck, expectDefined(ck.MakeSurface(1, 1)))+ try {+ return use(fresh)+ } finally {+ fresh.destroy()+ }+}++function pathOpsOnRepeatedBuild(build: (graph: SceneGraph, hostId: string) => string): number {+ const graph = new SceneGraph()+ const operation = expectDefined(graph.getNode(build(graph, graph.getPages()[0].id)))+ return withFreshRenderer((fresh) => {+ const buildPath = () => makeBooleanOperationPath(fresh, operation, graph)?.delete()+ buildPath()+ return countPathOps(buildPath)+ })+}++describe('a vector boolean operand’s saved fill', () => {+ test('merges its regions once, not on every frame', () => {+ expect(+ pathOpsOnRepeatedBuild((graph, hostId) => {+ unionWithOverlappingRegionsOperand(graph, hostId)+ return graph.getNode(hostId)?.childIds.at(-1) ?? ''+ })+ ).toBe(0)+ })+})++describe('a boolean operand with a stroke, as Figma combines it', () => {+ test('adds only its inside stroke band when its fill is hidden', () => {+ expect(leftEdgeAlpha('INSIDE', false)).toEqual([+ 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0+ ])+ })++ test('strokes an open vector operand on its centre line whatever the alignment', () => {+ expect(renderRow(ck, renderer, unionWithOpenOutsideStroke, 144, 190, 210)).toEqual(+ Array.from({ length: 11 }, () => 0)+ )+ expect(renderRow(ck, renderer, unionWithOpenOutsideStroke, 150, 190, 210)).toEqual(+ Array.from({ length: 11 }, () => 255)+ )+ })++ test('adds only its outside stroke band when its fill is hidden', () => {+ expect(leftEdgeAlpha('OUTSIDE', false)).toEqual([+ 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0+ ])+ })++ test('adds a centred stroke band across its outline when its fill is hidden', () => {+ expect(leftEdgeAlpha('CENTER', false)).toEqual([+ 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0+ ])+ })++ test('adds its visible fill with an outside stroke band around it', () => {+ expect(leftEdgeAlpha('OUTSIDE', true)).toEqual([+ 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255+ ])+ })++ // A paint at 0% shapes nothing, as a hidden one (live-verified).+ test('adds only its stroke band when its fill is at 0%', () => {+ expect(leftEdgeAlpha('INSIDE', true, { fill: 0, stroke: 1 })).toEqual(+ leftEdgeAlpha('INSIDE', false)+ )+ })++ test('adds its whole area when its fill is hidden and its stroke at 0%', () => {+ expect(leftEdgeAlpha('INSIDE', false, { fill: 1, stroke: 0 })).toEqual([+ 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255+ ])+ })++ test('outlines a vector operand’s aligned stroke once, not on every frame', () => {+ expect(pathOpsOnRepeatedBuild(unionWithInsideStrokedVector)).toBe(0)+ })+})++type Point = readonly [x: number, y: number]++function box(left: number, top: number, right: number, bottom: number): Point[] {+ return [+ [left, top],+ [right, top],+ [right, bottom],+ [left, bottom]+ ]+}++function contoursBlob(contours: Point[][]): Uint8Array {+ const commands = contours.flatMap((points) => [+ ...points.map(([x, y], index) => [index === 0 ? 1 : 2, x, y]),+ [0, 0, 0]+ ])+ const blob = new Uint8Array(commands.reduce((length, [command]) => length + (command ? 9 : 1), 0))+ const view = new DataView(blob.buffer)+ let offset = 0+ for (const [command, x, y] of commands) {+ blob[offset++] = command+ if (command) {+ view.setFloat32(offset, x, true)+ view.setFloat32(offset + 4, y, true)+ offset += 8+ }+ }+ return blob+}++function unionWithSavedFrameOperand(graph: SceneGraph, hostId: string) {+ const operation = graph.createNode('BOOLEAN_OPERATION', hostId, {+ x: 120,+ y: 70,+ width: SIZE,+ height: SIZE,+ booleanOperation: 'UNION',+ fills: [{ type: 'SOLID', color: RED, opacity: 1, visible: true }]+ })+ graph.createNode('VECTOR', operation.id, {+ width: SIZE,+ height: SIZE,+ fills: [{ type: 'SOLID', color: RED, opacity: 1, visible: true }],+ vectorNetwork: {+ vertices: [+ { x: 0, y: 0 },+ { x: SIZE, y: 0 },+ { x: 0, y: SIZE }+ ],+ segments: [+ { start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },+ { start: 1, end: 2, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }+ ],+ regions: []+ },+ fillGeometry: [+ {+ windingRule: 'EVENODD',+ commandsBlob: contoursBlob([box(0, 0, SIZE, SIZE), box(40, 40, SIZE - 40, SIZE - 40)])+ }+ ]+ })+ graph.createNode('RECTANGLE', operation.id, {+ width: 10,+ height: 10,+ fills: [{ type: 'SOLID', color: RED, opacity: 1, visible: true }]+ })+}++function unionWithStrokedSavedOperand(graph: SceneGraph, hostId: string) {+ const operation = graph.createNode('BOOLEAN_OPERATION', hostId, {+ x: 120,+ y: 70,+ width: SIZE,+ height: SIZE,+ booleanOperation: 'UNION',+ fills: [{ type: 'SOLID', color: RED, opacity: 1, visible: true }]+ })+ graph.createNode('VECTOR', operation.id, {+ width: SIZE,+ height: SIZE,+ fills: [{ type: 'SOLID', color: RED, opacity: 1, visible: true }],+ strokes: [+ { type: 'SOLID', color: RED, opacity: 1, visible: true, weight: WEIGHT, align: 'OUTSIDE' }+ ],+ strokeWeight: WEIGHT,+ strokeAlign: 'OUTSIDE',+ vectorNetwork: {+ vertices: [+ { x: 0, y: 0 },+ { x: SIZE, y: 0 },+ { x: SIZE, y: SIZE },+ { x: 0, y: SIZE }+ ],+ segments: [+ { start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },+ { start: 1, end: 2, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },+ { start: 2, end: 3, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },+ { start: 3, end: 0, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }+ ],+ regions: []+ },+ fillGeometry: [+ { windingRule: 'NONZERO', commandsBlob: contoursBlob([box(0, 0, SIZE / 2, SIZE)]) }+ ]+ })+}++function unionWithOverlappingNetworkRegions(graph: SceneGraph, hostId: string) {+ const operation = graph.createNode('BOOLEAN_OPERATION', hostId, {+ x: 120,+ y: 70,+ width: SIZE,+ height: SIZE,+ booleanOperation: 'UNION',+ fills: [{ type: 'SOLID', color: RED, opacity: 1, visible: true }]+ })+ const zero = { x: 0, y: 0 }+ const corners = [box(0, 0, 100, 100), box(50, 50, 150, 150).reverse()]+ graph.createNode('VECTOR', operation.id, {+ width: SIZE,+ height: SIZE,+ vectorNetwork: {+ vertices: corners.flat().map(([x, y]) => ({ x, y })),+ segments: [0, 1, 2, 3, 4, 5, 6, 7].map((index) => ({+ start: index,+ end: index % 4 === 3 ? index - 3 : index + 1,+ tangentStart: zero,+ tangentEnd: zero+ })),+ regions: [+ { windingRule: 'NONZERO', loops: [[0, 1, 2, 3]] },+ { windingRule: 'NONZERO', loops: [[4, 5, 6, 7]] }+ ]+ }+ })+}++describe('a vector boolean operand', () => {+ test('covers the overlap of its network regions whatever their directions', () => {+ expect(renderRow(ck, renderer, unionWithOverlappingNetworkRegions, 145, 170, 230)).toEqual(+ Array.from({ length: 31 }, () => 255)+ )+ })++ test('takes its stroke’s side from its saved fill geometry', () => {+ expect(renderRow(ck, renderer, unionWithStrokedSavedOperand, 74, 220, 260)).toEqual(+ Array.from({ length: 21 }, () => 255)+ )+ })++ test('takes its shape from its saved fill geometry, holes included', () => {+ expect(renderRow(ck, renderer, unionWithSavedFrameOperand, 150, 150, 170)).toEqual([+ 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0+ ])+ })+})++function insideStrokedSquareWithTail(graph: SceneGraph, hostId: string) {+ const operation = graph.createNode('BOOLEAN_OPERATION', hostId, {+ x: 120,+ y: 70,+ width: SIZE,+ height: SIZE,+ booleanOperation: 'UNION',+ fills: [{ type: 'SOLID', color: RED, opacity: 1, visible: true }]+ })+ const zero = { x: 0, y: 0 }+ const edge = (start: number, end: number) => ({+ start,+ end,+ tangentStart: zero,+ tangentEnd: zero+ })+ graph.createNode('VECTOR', operation.id, {+ width: SIZE,+ height: SIZE,+ fills: [{ type: 'SOLID', color: RED, opacity: 1, visible: false }],+ strokes: [+ { type: 'SOLID', color: RED, opacity: 1, visible: true, weight: WEIGHT, align: 'INSIDE' }+ ],+ strokeWeight: WEIGHT,+ strokeAlign: 'INSIDE',+ vectorNetwork: {+ vertices: [...box(0, 0, SIZE, SIZE), [SIZE, SIZE + 40] as const].map(([x, y]) => ({ x, y })),+ segments: [edge(0, 1), edge(1, 2), edge(2, 3), edge(3, 0), edge(2, 4)],+ regions: [{ windingRule: 'NONZERO', loops: [[0, 1, 2, 3]] }]+ }+ })+}++function openOperandPath(cornerRadius: number) {+ const graph = new SceneGraph()+ const operation = graph.createNode('BOOLEAN_OPERATION', graph.getPages()[0].id, {+ width: SIZE,+ height: SIZE,+ booleanOperation: 'UNION',+ cornerRadius,+ fills: [{ type: 'SOLID', color: RED, opacity: 1, visible: true }]+ })+ const zero = { x: 0, y: 0 }+ graph.createNode('VECTOR', operation.id, {+ width: SIZE,+ height: SIZE,+ fills: [{ type: 'SOLID', color: RED, opacity: 1, visible: true }],+ vectorNetwork: {+ vertices: box(0, 0, SIZE, SIZE)+ .slice(0, 3)+ .map(([x, y]) => ({ x, y })),+ segments: [+ { start: 0, end: 1, tangentStart: zero, tangentEnd: zero },+ { start: 1, end: 2, tangentStart: zero, tangentEnd: zero }+ ],+ regions: []+ }+ })+ return withFreshRenderer((fresh) =>+ expectDefined(makeBooleanOperationPath(fresh, operation, graph))+ )+}++function overlappingRegionsPathWithoutUnions() {+ const graph = new SceneGraph()+ unionWithOverlappingNetworkRegions(graph, graph.getPages()[0].id)+ const operation = expectDefined(graph.getNode(graph.getPages()[0].childIds[0]))+ const pathOps = spyOn(ck.Path, 'MakeFromOp').mockReturnValue(null)+ try {+ return withFreshRenderer((fresh) =>+ expectDefined(makeBooleanOperationPath(fresh, operation, graph))+ )+ } finally {+ pathOps.mockRestore()+ }+}++describe('a vector boolean operand whose regions do not unite', () => {+ test('keeps every region of its outline', () => {+ const path = overlappingRegionsPathWithoutUnions()+ expect([path.contains(20, 20), path.contains(140, 140)]).toEqual([true, true])+ path.delete()+ })+})++describe('a vector boolean operand with a region and a loose segment', () => {+ test('strokes the loose segment on its centre line', () => {+ expect(renderRow(ck, renderer, insideStrokedSquareWithTail, 250, 270, 290)).toEqual([+ 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0+ ])+ })+})++describe('a rounded boolean operation of a single open path', () => {+ test('fills the path with its corner rounded', () => {+ const path = openOperandPath(20)+ expect([path.contains(SIZE - 10, 10), path.contains(SIZE - 1, 1)]).toEqual([true, false])+ path.delete()+ })+})diff --git a/packages/core/tests/canvas/boolean/cache.test.ts b/packages/core/tests/canvas/boolean/cache.test.tsnew file mode 100644index 000000000..9f4c154bb--- /dev/null+++ b/packages/core/tests/canvas/boolean/cache.test.ts@@ -0,0 +1,297 @@+import { describe, expect, spyOn, test } from 'bun:test'++import { SkiaRenderer } from '@open-pencil/core/canvas'+import { initCanvasKit } from '@open-pencil/core/io/formats/raster'+import { SceneGraph, type VectorNetwork } from '@open-pencil/scene-graph'++import { makeBooleanOperationPath, makeBooleanSourcePath } from '#core/canvas/boolean'+import { NodePathCaches } from '#core/canvas/paths/cache'++import { expectDefined } from '#core-tests/helpers/assert'++const ck = await initCanvasKit()++const SIZE = 160+const RED = { r: 1, g: 0, b: 0, a: 1 }+const SOLID_RED = { type: 'SOLID' as const, color: RED, opacity: 1, visible: true }++function withFreshRenderer<T>(use: (fresh: SkiaRenderer) => T): T {+ const fresh = new SkiaRenderer(ck, expectDefined(ck.MakeSurface(1, 1)))+ try {+ return use(fresh)+ } finally {+ fresh.destroy()+ }+}++function countPathOps(build: () => void): number {+ const pathOps = spyOn(ck.Path, 'MakeFromOp')+ try {+ build()+ return pathOps.mock.calls.length+ } finally {+ pathOps.mockRestore()+ }+}++function pathOpsOnRepeatedBuild(build: (graph: SceneGraph, hostId: string) => string): number {+ const graph = new SceneGraph()+ const operation = expectDefined(graph.getNode(build(graph, graph.getPages()[0].id)))+ return withFreshRenderer((fresh) => {+ const buildPath = () => makeBooleanOperationPath(fresh, operation, graph)?.delete()+ buildPath()+ return countPathOps(buildPath)+ })+}++function squareBlob(left: number, top: number, side: number): Uint8Array {+ const corners = [+ [left, top],+ [left + side, top],+ [left + side, top + side],+ [left, top + side]+ ]+ const blob = new Uint8Array(corners.length * 9 + 1)+ const view = new DataView(blob.buffer)+ corners.forEach(([x, y], index) => {+ blob[index * 9] = index === 0 ? 1 : 2+ view.setFloat32(index * 9 + 1, x, true)+ view.setFloat32(index * 9 + 5, y, true)+ })+ return blob+}++function squareNetwork(): VectorNetwork {+ const corners = [+ { x: 0, y: 0 },+ { x: SIZE, y: 0 },+ { x: SIZE, y: SIZE },+ { x: 0, y: SIZE }+ ]+ const straight = { tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }+ return {+ vertices: corners,+ segments: corners.map((_, index) => ({ start: index, end: (index + 1) % 4, ...straight })),+ regions: [{ windingRule: 'NONZERO', loops: [[0, 1, 2, 3]] }]+ }+}++function unionWithVector(+ graph: SceneGraph,+ hostId: string,+ vector: Parameters<SceneGraph['createNode']>[2]+): string {+ const operation = graph.createNode('BOOLEAN_OPERATION', hostId, {+ width: SIZE,+ height: SIZE,+ booleanOperation: 'UNION',+ fills: [SOLID_RED]+ })+ graph.createNode('VECTOR', operation.id, { width: SIZE, height: SIZE, ...vector })+ return operation.id+}++function unionWithOverlappingRegionsOperand(graph: SceneGraph, hostId: string): string {+ return unionWithVector(graph, hostId, {+ fills: [SOLID_RED],+ vectorNetwork: { vertices: [], segments: [], regions: [] },+ fillGeometry: [+ { windingRule: 'NONZERO', commandsBlob: squareBlob(0, 0, 100) },+ { windingRule: 'NONZERO', commandsBlob: squareBlob(50, 50, 100) }+ ]+ })+}++function unionWithInsideStrokedVector(graph: SceneGraph, hostId: string): string {+ return unionWithVector(graph, hostId, {+ fills: [{ ...SOLID_RED, visible: false }],+ strokes: [{ ...SOLID_RED, weight: 8, align: 'INSIDE' }],+ strokeWeight: 8,+ strokeAlign: 'INSIDE',+ vectorNetwork: squareNetwork()+ })+}++function overlappingSquares(graph: SceneGraph, hostId: string): string {+ const operation = graph.createNode('BOOLEAN_OPERATION', hostId, {+ width: SIZE,+ height: SIZE,+ booleanOperation: 'UNION',+ fills: [SOLID_RED]+ })+ for (const x of [0, SIZE / 2]) {+ graph.createNode('RECTANGLE', operation.id, {+ x,+ width: SIZE / 2 + 10,+ height: SIZE,+ fills: [SOLID_RED]+ })+ }+ return operation.id+}++function resultAfterEdit(edit: (graph: SceneGraph, operationId: string) => void): {+ rebuilt: number[]+ fresh: number[]+} {+ const graph = new SceneGraph()+ const operationId = overlappingSquares(graph, graph.getPages()[0].id)+ const bounds = (r: SkiaRenderer) => {+ const path = expectDefined(+ makeBooleanOperationPath(r, expectDefined(graph.getNode(operationId)), graph)+ )+ const tight = Array.from(path.computeTightBounds())+ path.delete()+ return tight+ }+ return withFreshRenderer((cached) => {+ bounds(cached)+ edit(graph, operationId)+ return { rebuilt: bounds(cached), fresh: withFreshRenderer(bounds) }+ })+}++function operandIds(graph: SceneGraph, operationId: string): string[] {+ return expectDefined(graph.getNode(operationId)).childIds+}++describe('a boolean operation’s result', () => {+ test('is combined once while its operands stay the same', () => {+ expect(pathOpsOnRepeatedBuild(overlappingSquares)).toBe(0)+ })++ test('is shared by operations whose operands match', () => {+ const graph = new SceneGraph()+ const hostId = graph.getPages()[0].id+ const first = expectDefined(graph.getNode(overlappingSquares(graph, hostId)))+ const second = expectDefined(graph.getNode(overlappingSquares(graph, hostId)))+ withFreshRenderer((fresh) => {+ makeBooleanOperationPath(fresh, first, graph)?.delete()+ expect(countPathOps(() => makeBooleanOperationPath(fresh, second, graph)?.delete())).toBe(0)+ })+ })++ test('follows a moved operand', () => {+ const { rebuilt, fresh } = resultAfterEdit((graph, operationId) => {+ graph.updateNode(operandIds(graph, operationId)[1], { x: SIZE })+ })+ expect(rebuilt).toEqual(fresh)+ expect(rebuilt).toEqual([0, 0, SIZE * 1.5 + 10, SIZE])+ })++ test('follows a resized operand', () => {+ const { rebuilt, fresh } = resultAfterEdit((graph, operationId) => {+ graph.updateNode(operandIds(graph, operationId)[1], { height: SIZE * 2 })+ })+ expect(rebuilt).toEqual(fresh)+ expect(rebuilt).toEqual([0, 0, SIZE + 10, SIZE * 2])+ })++ test('follows a change of its corner radius', () => {+ const graph = new SceneGraph()+ const operationId = overlappingSquares(graph, graph.getPages()[0].id)+ const coversOuterCorner = (r: SkiaRenderer) => {+ const operation = expectDefined(graph.getNode(operationId))+ const path = expectDefined(makeBooleanOperationPath(r, operation, graph))+ const covered = path.contains(1, 1)+ path.delete()+ return covered+ }+ withFreshRenderer((cached) => {+ expect(coversOuterCorner(cached)).toBe(true)+ graph.updateNode(operationId, { cornerRadius: 20 })+ expect(coversOuterCorner(cached)).toBe(false)+ })+ })++ test('follows a hidden operand', () => {+ const { rebuilt, fresh } = resultAfterEdit((graph, operationId) => {+ graph.updateNode(operandIds(graph, operationId)[1], { visible: false })+ })+ expect(rebuilt).toEqual(fresh)+ expect(rebuilt).toEqual([0, 0, SIZE / 2 + 10, SIZE])+ })++ test('follows an added operand', () => {+ const { rebuilt, fresh } = resultAfterEdit((graph, operationId) => {+ graph.createNode('RECTANGLE', operationId, {+ x: SIZE,+ width: SIZE,+ height: 10,+ fills: [SOLID_RED]+ })+ })+ expect(rebuilt).toEqual(fresh)+ expect(rebuilt).toEqual([0, 0, SIZE * 2, SIZE])+ })++ test('follows reordered operands of a subtraction', () => {+ const { rebuilt, fresh } = resultAfterEdit((graph, operationId) => {+ graph.updateNode(operationId, { booleanOperation: 'SUBTRACT' })+ graph.insertChildAt(operandIds(graph, operationId)[1], operationId, 0)+ })+ expect(rebuilt).toEqual(fresh)+ expect(rebuilt).toEqual([SIZE / 2 + 10, 0, SIZE + 10, SIZE])+ })++ test('follows a change of its operation', () => {+ const { rebuilt, fresh } = resultAfterEdit((graph, operationId) => {+ graph.updateNode(operationId, { booleanOperation: 'INTERSECT' })+ })+ expect(rebuilt).toEqual(fresh)+ expect(rebuilt).toEqual([SIZE / 2, 0, SIZE / 2 + 10, SIZE])+ })+})++function pathOpsForSecondOperand(build: (graph: SceneGraph, hostId: string) => string): number {+ const graph = new SceneGraph()+ const hostId = graph.getPages()[0].id+ const [first, second] = [build(graph, hostId), build(graph, hostId)].map((operationId) =>+ expectDefined(graph.getNode(expectDefined(graph.getNode(operationId)).childIds[0]))+ )+ return withFreshRenderer((fresh) => {+ makeBooleanSourcePath(fresh, first, graph)?.delete()+ return countPathOps(() => makeBooleanSourcePath(fresh, second, graph)?.delete())+ })+}++describe('a vector boolean operand’s shared outlines', () => {+ test('merge another vector’s identical saved fill without path ops', () => {+ expect(pathOpsForSecondOperand(unionWithOverlappingRegionsOperand)).toBe(0)+ })++ test('reuse another vector’s identical aligned stroke band', () => {+ expect(pathOpsForSecondOperand(unionWithInsideStrokedVector)).toBe(0)+ })+})++describe('a renderer whose path budget holds two entries', () => {+ test('builds every operation as an unbounded one does, without freeing a path twice', () => {+ const graph = new SceneGraph()+ const hostId = graph.getPages()[0].id+ const operations = [+ overlappingSquares(graph, hostId),+ unionWithInsideStrokedVector(graph, hostId),+ overlappingSquares(graph, hostId)+ ].map((id) => expectDefined(graph.getNode(id)))+ const boundsWith = (r: SkiaRenderer) =>+ [0, 1, 2].flatMap(() =>+ operations.map((operation) => {+ const path = expectDefined(makeBooleanOperationPath(r, operation, graph))+ const tight = Array.from(path.computeTightBounds())+ path.delete()+ return tight+ })+ )+ const unbounded = withFreshRenderer(boundsWith)+ const bounded = withFreshRenderer((tiny) => {+ tiny.nodePaths = new NodePathCaches({ maxEntries: 2 })+ const built = boundsWith(tiny)+ expect(tiny.nodePaths.shared.size).toBeLessThanOrEqual(2)+ expect(tiny.nodePaths.sharedKeys.size).toBeLessThanOrEqual(2)+ tiny.nodePaths.clear()+ return built+ })+ expect(bounded).toEqual(unbounded)+ })+})diff --git a/packages/core/tests/canvas/boolean/fill-rule.test.ts b/packages/core/tests/canvas/boolean/fill-rule.test.tsnew file mode 100644index 000000000..f981a2d82--- /dev/null+++ b/packages/core/tests/canvas/boolean/fill-rule.test.ts@@ -0,0 +1,120 @@+import { afterAll, describe, expect, test } from 'bun:test'++import { expectDefined } from '#core-tests/helpers/assert'++import { SkiaRenderer } from '@open-pencil/core/canvas'+import { initCanvasKit } from '@open-pencil/core/io/formats/raster'+import { SceneGraph, type Stroke } from '@open-pencil/scene-graph'++import { makeBooleanOperationPath } from '#core/canvas/boolean'++const ck = await initCanvasKit()+const renderer = new SkiaRenderer(ck, expectDefined(ck.MakeSurface(1, 1)))+afterAll(() => renderer.destroy())++const RED = { r: 1, g: 0, b: 0, a: 1 }+const STRAIGHT = { tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }++function square(first: number, from: number, to: number) {+ return {+ vertices: [+ { x: from, y: from },+ { x: to, y: from },+ { x: to, y: to },+ { x: from, y: to }+ ],+ segments: [0, 1, 2, 3].map((index) => ({+ start: first + index,+ end: first + ((index + 1) % 4),+ ...STRAIGHT+ }))+ }+}++function unionWithEvenOddRing(graph: SceneGraph, strokes: Stroke[], fillVisible: boolean): string {+ const operation = graph.createNode('BOOLEAN_OPERATION', graph.getPages()[0].id, {+ width: 200,+ height: 100,+ booleanOperation: 'UNION',+ fills: [{ type: 'SOLID', color: RED, opacity: 1, visible: true }]+ })+ const outer = square(0, 0, 100)+ const inner = square(4, 30, 70)+ graph.createNode('VECTOR', operation.id, {+ width: 100,+ height: 100,+ fills: [{ type: 'SOLID', color: RED, opacity: 1, visible: fillVisible }],+ strokes,+ strokeWeight: strokes[0]?.weight ?? 0,+ vectorNetwork: {+ vertices: [...outer.vertices, ...inner.vertices],+ segments: [...outer.segments, ...inner.segments],+ regions: [+ {+ windingRule: 'EVENODD',+ loops: [+ [0, 1, 2, 3],+ [4, 5, 6, 7]+ ]+ }+ ]+ }+ })+ graph.createNode('RECTANGLE', operation.id, {+ x: 150,+ width: 20,+ height: 20,+ fills: [{ type: 'SOLID', color: RED, opacity: 1, visible: true }]+ })+ return operation.id+}++function covers(strokes: Stroke[], fillVisible: boolean, points: Record<string, [number, number]>) {+ const graph = new SceneGraph()+ const operation = expectDefined(graph.getNode(unionWithEvenOddRing(graph, strokes, fillVisible)))+ const path = expectDefined(makeBooleanOperationPath(renderer, operation, graph))+ const covered = Object.fromEntries(+ Object.entries(points).map(([name, [x, y]]) => [name, path.contains(x, y)])+ )+ path.delete()+ return covered+}++function coveredPoints(strokes: Stroke[]) {+ return covers(strokes, true, { ring: [15, 50], hole: [50, 50], rectangle: [160, 10] })+}++function stroke(align: Stroke['align']): Stroke {+ return { type: 'SOLID', color: RED, opacity: 1, visible: true, weight: 4, align }+}++describe('a vector boolean operand with one even-odd region', () => {+ test('keeps the hole its fill rule cuts', () => {+ expect(coveredPoints([])).toEqual({ ring: true, hole: false, rectangle: true })+ })++ test('keeps the hole when it also draws a stroke', () => {+ expect(coveredPoints([stroke('CENTER')])).toEqual({ ring: true, hole: false, rectangle: true })+ })++ test('keeps the hole under an inside stroke alone', () => {+ expect(+ covers([stroke('INSIDE')], false, {+ outerBand: [2, 50],+ innerBand: [28, 50],+ ring: [15, 50],+ hole: [32, 50]+ })+ ).toEqual({ outerBand: true, innerBand: true, ring: false, hole: false })+ })++ test('keeps the hole under an outside stroke alone', () => {+ expect(+ covers([stroke('OUTSIDE')], false, {+ innerBand: [32, 50],+ ring: [15, 50],+ hole: [50, 50]+ })+ ).toEqual({ innerBand: true, ring: false, hole: false })+ })+})diff --git a/packages/core/tests/canvas/boolean/frame-operand.test.ts b/packages/core/tests/canvas/boolean/frame-operand.test.tsnew file mode 100644index 000000000..104969715--- /dev/null+++ b/packages/core/tests/canvas/boolean/frame-operand.test.ts@@ -0,0 +1,57 @@+import { afterAll, expect, test } from 'bun:test'++import { expectDefined } from '#core-tests/helpers/assert'++import { SkiaRenderer } from '@open-pencil/core/canvas'+import { initCanvasKit } from '@open-pencil/core/io/formats/raster'+import { SceneGraph } from '@open-pencil/scene-graph'++import { makeBooleanOperationPath } from '#core/canvas/boolean'++const ck = await initCanvasKit()+const renderer = new SkiaRenderer(ck, expectDefined(ck.MakeSurface(1, 1)))+afterAll(() => renderer.destroy())++const SOLID = {+ type: 'SOLID' as const,+ color: { r: 0, g: 0, b: 0, a: 1 },+ opacity: 1,+ visible: true+}++// Live-verified: a frame operand gives a boolean operation its children's shapes only.+test("a frame operand gives only its children's shapes, not its own fill or stroke", () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const operation = graph.createNode('BOOLEAN_OPERATION', page.id, {+ width: 100,+ height: 100,+ booleanOperation: 'UNION',+ fills: [SOLID]+ })+ const frame = graph.createNode('FRAME', operation.id, {+ x: 20,+ y: 20,+ width: 40,+ height: 40,+ fills: [SOLID],+ strokes: [{ ...SOLID, weight: 4, align: 'INSIDE' }]+ })+ graph.createNode('RECTANGLE', frame.id, { x: 30, y: 2, width: 8, height: 8, fills: [SOLID] })+ graph.createNode('RECTANGLE', operation.id, {+ x: 70,+ y: 70,+ width: 10,+ height: 10,+ fills: [SOLID]+ })++ const path = expectDefined(makeBooleanOperationPath(renderer, operation, graph))+ try {+ expect(path.contains(30, 45)).toBe(false)+ expect(path.contains(54, 26)).toBe(true)+ expect(path.contains(75, 75)).toBe(true)+ } finally {+ path.delete()+ }+})diff --git a/packages/core/tests/canvas/boolean/own-stroke.test.ts b/packages/core/tests/canvas/boolean/own-stroke.test.tsnew file mode 100644index 000000000..f533511c5--- /dev/null+++ b/packages/core/tests/canvas/boolean/own-stroke.test.ts@@ -0,0 +1,77 @@+import { afterAll, describe, expect, test } from 'bun:test'++import { expectDefined } from '#core-tests/helpers/assert'+import { renderRow } from '#core-tests/helpers/figma-rows'++import { SkiaRenderer } from '@open-pencil/core/canvas'+import { initCanvasKit } from '@open-pencil/core/io/formats/raster'+import type { SceneGraph, Stroke } from '@open-pencil/scene-graph'++const ck = await initCanvasKit()+const renderer = new SkiaRenderer(ck, expectDefined(ck.MakeSurface(1, 1)))+afterAll(() => renderer.destroy())++const SIZE = 160+const WEIGHT = 8+const RED = { r: 1, g: 0, b: 0, a: 1 }++const BLUE_CHANNEL = 2++function strokedUnion(align: Stroke['align']) {+ return (graph: SceneGraph, hostId: string) => {+ const operation = graph.createNode('BOOLEAN_OPERATION', hostId, {+ x: 120,+ y: 70,+ width: SIZE,+ height: SIZE,+ booleanOperation: 'UNION',+ fills: [{ type: 'SOLID', color: RED, opacity: 1, visible: true }],+ strokes: [+ {+ type: 'SOLID',+ color: { r: 0, g: 0, b: 1, a: 1 },+ opacity: 1,+ visible: true,+ weight: WEIGHT,+ align+ }+ ],+ strokeWeight: WEIGHT,+ strokeAlign: align+ })+ graph.createNode('RECTANGLE', operation.id, {+ width: SIZE,+ height: SIZE,+ fills: [{ type: 'SOLID', color: RED, opacity: 1, visible: true }]+ })+ graph.createNode('RECTANGLE', operation.id, {+ width: 10,+ height: 10,+ fills: [{ type: 'SOLID', color: RED, opacity: 1, visible: true }]+ })+ }+}++function leftEdgeStroke(align: Stroke['align']): number[] {+ return renderRow(ck, renderer, strokedUnion(align), 150, 104, 134, BLUE_CHANNEL)+}++describe('a boolean operation’s own stroke', () => {+ test('lies outside the result when aligned outside', () => {+ expect(leftEdgeStroke('OUTSIDE')).toEqual([+ 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0+ ])+ })++ test('lies within the result when aligned inside', () => {+ expect(leftEdgeStroke('INSIDE')).toEqual([+ 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0+ ])+ })++ test('straddles the outline when centred', () => {+ expect(leftEdgeStroke('CENTER')).toEqual([+ 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0+ ])+ })+})diff --git a/packages/core/tests/canvas/strokes/saved-geometry.test.ts b/packages/core/tests/canvas/strokes/saved-geometry.test.tsnew file mode 100644index 000000000..7d8608411--- /dev/null+++ b/packages/core/tests/canvas/strokes/saved-geometry.test.ts@@ -0,0 +1,229 @@+import { afterAll, describe, expect, test } from 'bun:test'++import { SkiaRenderer } from '@open-pencil/core/canvas'+import { initCanvasKit } from '@open-pencil/core/io/formats/raster'+import type { SceneGraph, Stroke } from '@open-pencil/scene-graph'++import { expectDefined } from '#core-tests/helpers/assert'+import { renderRow } from '#core-tests/helpers/figma-rows'++const ck = await initCanvasKit()+const renderer = new SkiaRenderer(ck, expectDefined(ck.MakeSurface(1, 1)))+afterAll(() => renderer.destroy())++const RED = 0+const BLUE = 2+const ALPHA = 3+const SIZE = 160+const WEIGHT = 8++type Point = readonly [x: number, y: number]++function box(left: number, top: number, right: number, bottom: number): Point[] {+ return [+ [left, top],+ [right, top],+ [right, bottom],+ [left, bottom]+ ]+}++function contoursBlob(contours: Point[][]): Uint8Array {+ const commands = contours.flatMap((points) => [+ ...points.map(([x, y], index) => [index === 0 ? 1 : 2, x, y]),+ [0, 0, 0]+ ])+ const blob = new Uint8Array(commands.reduce((length, [command]) => length + (command ? 9 : 1), 0))+ const view = new DataView(blob.buffer)+ let offset = 0+ for (const [command, x, y] of commands) {+ blob[offset++] = command+ if (command) {+ view.setFloat32(offset, x, true)+ view.setFloat32(offset + 4, y, true)+ offset += 8+ }+ }+ return blob+}++function vectorWithSavedBand(align: Stroke['align']) {+ return (graph: SceneGraph, hostId: string) => {+ graph.createNode('VECTOR', hostId, {+ x: 120,+ y: 70,+ width: SIZE,+ height: SIZE,+ fills: [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }],+ strokes: [+ {+ type: 'SOLID',+ color: { r: 0, g: 0, b: 1, a: 1 },+ opacity: 1,+ visible: true,+ weight: WEIGHT,+ align+ }+ ],+ strokeWeight: WEIGHT,+ strokeAlign: align,+ fillGeometry: [+ { windingRule: 'NONZERO', commandsBlob: contoursBlob([box(0, 0, SIZE, SIZE)]) }+ ],+ strokeGeometry: [+ {+ windingRule: 'EVENODD',+ commandsBlob: contoursBlob([+ box(-WEIGHT, -WEIGHT, SIZE + WEIGHT, SIZE + WEIGHT),+ box(WEIGHT, WEIGHT, SIZE - WEIGHT, SIZE - WEIGHT)+ ])+ }+ ]+ })+ }+}++function leftEdgeRow(align: Stroke['align'], channel: number): number[] {+ return renderRow(ck, renderer, vectorWithSavedBand(align), 150, 104, 134, channel)+}++describe('a vector’s saved stroke geometry, a band twice the weight around the outline', () => {+ test('keeps an outside stroke off the fill', () => {+ expect(leftEdgeRow('OUTSIDE', BLUE)).toEqual([+ 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0+ ])+ expect(leftEdgeRow('OUTSIDE', RED)).toEqual([+ 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255+ ])+ })++ test('keeps an inside stroke within the fill', () => {+ expect(leftEdgeRow('INSIDE', ALPHA)).toEqual([+ 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255+ ])+ expect(leftEdgeRow('INSIDE', BLUE)).toEqual([+ 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0+ ])+ })+})++const HALF = WEIGHT / 2++function openPathWithCentredSavedStroke(graph: SceneGraph, hostId: string) {+ graph.createNode('VECTOR', hostId, {+ x: 120,+ y: 70,+ width: SIZE,+ height: SIZE,+ fills: [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }],+ strokes: [+ {+ type: 'SOLID',+ color: { r: 0, g: 0, b: 1, a: 1 },+ opacity: 1,+ visible: true,+ weight: WEIGHT,+ align: 'OUTSIDE'+ }+ ],+ strokeWeight: WEIGHT,+ strokeAlign: 'OUTSIDE',+ vectorNetwork: {+ vertices: [+ { x: 0, y: 0 },+ { x: SIZE, y: 0 },+ { x: SIZE, y: SIZE }+ ],+ segments: [+ { start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },+ { start: 1, end: 2, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }+ ],+ regions: []+ },+ fillGeometry: [+ {+ windingRule: 'NONZERO',+ commandsBlob: contoursBlob([+ [+ [0, 0],+ [SIZE, 0],+ [SIZE, SIZE]+ ]+ ])+ }+ ],+ strokeGeometry: [+ {+ windingRule: 'NONZERO',+ commandsBlob: contoursBlob([+ box(-HALF, -HALF, SIZE + HALF, HALF),+ box(SIZE - HALF, -HALF, SIZE + HALF, SIZE + HALF)+ ])+ }+ ]+ })+}++describe('an open vector’s saved stroke geometry', () => {+ test('draws whole, as Figma strokes an open path on its centre line', () => {+ expect(renderRow(ck, renderer, openPathWithCentredSavedStroke, 72, 140, 260, BLUE)).toEqual(+ Array.from({ length: 61 }, () => 255)+ )+ })+})++function twoRegionsWithInsideStroke(graph: SceneGraph, hostId: string) {+ graph.createNode('VECTOR', hostId, {+ x: 120,+ y: 70,+ width: SIZE,+ height: SIZE,+ fills: [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }],+ strokes: [+ {+ type: 'SOLID',+ color: { r: 0, g: 0, b: 1, a: 1 },+ opacity: 1,+ visible: true,+ weight: WEIGHT,+ align: 'INSIDE'+ }+ ],+ strokeWeight: WEIGHT,+ strokeAlign: 'INSIDE',+ fillGeometry: [+ { windingRule: 'NONZERO', commandsBlob: contoursBlob([box(0, 0, 60, SIZE)]) },+ { windingRule: 'NONZERO', commandsBlob: contoursBlob([box(100, 0, SIZE, SIZE)]) }+ ],+ strokeGeometry: [+ {+ windingRule: 'EVENODD',+ commandsBlob: contoursBlob([+ box(-WEIGHT, -WEIGHT, 60 + WEIGHT, SIZE + WEIGHT),+ box(WEIGHT, WEIGHT, 60 - WEIGHT, SIZE - WEIGHT),+ box(100 - WEIGHT, -WEIGHT, SIZE + WEIGHT, SIZE + WEIGHT),+ box(100 + WEIGHT, WEIGHT, SIZE - WEIGHT, SIZE - WEIGHT)+ ])+ }+ ]+ })+}++const INSIDE_BANDS = [+ [0, WEIGHT],+ [60 - WEIGHT, 60],+ [100, 100 + WEIGHT],+ [SIZE - WEIGHT, SIZE]+]++describe('a vector with several fill regions', () => {+ test('keeps an inside stroke within each of them', () => {+ const expected = Array.from({ length: 91 }, (_, index) => {+ const x = index * 2 - 10+ return INSIDE_BANDS.some(([start, end]) => x >= start && x < end) ? 255 : 0+ })+ expect(renderRow(ck, renderer, twoRegionsWithInsideStroke, 150, 110, 290, BLUE)).toEqual(+ expected+ )+ })+})diff --git a/packages/core/tests/editor/structure/flatten.test.ts b/packages/core/tests/editor/structure/flatten.test.tsindex f2a8a31a8..8777b5a01 100644--- a/packages/core/tests/editor/structure/flatten.test.ts+++ b/packages/core/tests/editor/structure/flatten.test.ts@@ -5,6 +5,7 @@ import { SkiaRenderer } from '@open-pencil/core/canvas'import { BLACK, TRANSPARENT } from '@open-pencil/core/constants'import { initCanvasKit } from '@open-pencil/core/io/formats/raster'import { fontManager } from '@open-pencil/core/text'+import { vectorNetworkToPath } from '@open-pencil/core/vector'import { textNodeToOutlineLayout } from '#core/text/outlines'@@ -82,6 +83,50 @@ describe('flattenSelected', () => {expect(editor.graph.getNode(second.id)).toBeUndefined()})+ // The shape only: Figma keeps each layer's fill on its own region, which needs region fills.+ test("shapes a flattened frame by its children, leaving the frame's own area out", async () => {+ const { editor } = await createEditorWithRenderer()+ const pageId = editor.state.currentPageId+ const solid = { type: 'SOLID' as const, color: BLACK, opacity: 1, visible: true }+ const frame = editor.graph.createNode('FRAME', pageId, {+ x: 20,+ y: 20,+ width: 40,+ height: 40,+ fills: [solid],+ strokes: [{ ...solid, weight: 4, align: 'INSIDE' as const }]+ })+ editor.graph.createNode('RECTANGLE', frame.id, { x: 30, y: 2, width: 8, height: 8 })++ editor.select([frame.id])+ editor.flattenSelected()++ const vector = editor.graph.getNode([...editor.state.selectedIds][0])+ expect([vector?.x, vector?.y, vector?.width, vector?.height]).toEqual([50, 22, 8, 8])+ })++ test('keeps the shape an outside stroke surrounds empty', async () => {+ const { editor } = await createEditorWithRenderer()+ const solid = { type: 'SOLID' as const, color: BLACK, opacity: 1, visible: true }+ const ellipse = editor.graph.createNode('ELLIPSE', editor.state.currentPageId, {+ width: 120,+ height: 70,+ fills: [{ ...solid, visible: false }],+ strokes: [{ ...solid, weight: 4, align: 'OUTSIDE' as const }]+ })++ editor.select([ellipse.id])+ editor.flattenSelected()++ const vector = editor.graph.getNode([...editor.state.selectedIds][0])+ const network = vector?.vectorNetwork+ if (!vector || !network) throw new Error('Expected a flattened vector')+ const [path] = vectorNetworkToPath(await initCanvasKit(), network)+ expect(path?.contains(60 - vector.x, 35 - vector.y)).toBe(false)+ expect(path?.contains(60 - vector.x, -2 - vector.y)).toBe(true)+ path?.delete()+ })+test('outlines loaded text through the shared text outline path', async () => {await loadInterRegular()const { editor } = await createEditorWithRenderer()diff --git a/packages/core/tests/vector/connectivity.test.ts b/packages/core/tests/vector/connectivity.test.tsnew file mode 100644index 000000000..1738951e4--- /dev/null+++ b/packages/core/tests/vector/connectivity.test.ts@@ -0,0 +1,45 @@+import { describe, expect, test } from 'bun:test'++import type { VectorNetwork, VectorSegment } from '@open-pencil/scene-graph'++import { isOpenVectorNetwork } from '#core/vector/connectivity'++const zero = { x: 0, y: 0 }+const line = (start: number, end: number): VectorSegment => ({+ start,+ end,+ tangentStart: zero,+ tangentEnd: zero+})+const corners = [+ { x: 0, y: 0 },+ { x: 10, y: 0 },+ { x: 10, y: 10 },+ { x: 0, y: 10 }+]++function network(segments: VectorSegment[], loops: number[][] = []): VectorNetwork {+ return {+ vertices: corners,+ segments,+ regions: loops.length > 0 ? [{ windingRule: 'NONZERO', loops }] : []+ }+}++describe('isOpenVectorNetwork', () => {+ test('is true for a path with loose ends', () => {+ expect(isOpenVectorNetwork(network([line(0, 1), line(1, 2)]))).toBe(true)+ })++ test('is false for a loop saved without a region', () => {+ expect(isOpenVectorNetwork(network([line(0, 1), line(1, 2), line(2, 3), line(3, 0)]))).toBe(+ false+ )+ })++ test('is false for a network with a region, even with a loose tail', () => {+ expect(+ isOpenVectorNetwork(network([line(0, 1), line(1, 2), line(2, 0), line(2, 3)], [[0, 1, 2]]))+ ).toBe(false)+ })+})diff --git a/tests/e2e/canvas/boolean-visual.spec.ts b/tests/e2e/canvas/boolean-visual.spec.tsindex 7b14df9b0..a1d5e5c70 100644--- a/tests/e2e/canvas/boolean-visual.spec.ts+++ b/tests/e2e/canvas/boolean-visual.spec.ts@@ -1,6 +1,8 @@import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'+import { booleanStrokeAlignmentDriver } from '#tests/helpers/canvas/boolean/driver'const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')+const strokeAlignment = booleanStrokeAlignmentDriver(() => editor.page)async function expectCanvas(name: string) {editor.canvas.assertNoErrors()@@ -64,3 +66,9 @@ test('boolean operations', async () => {await editor.canvas.waitForRender()await expectCanvas('boolean-operations')})++test('boolean operation strokes keep their alignment and corner radius', async () => {+ await strokeAlignment.show()+ await editor.canvas.waitForRender()+ await expectCanvas('boolean-stroke-alignment')+})diff --git a/tests/e2e/canvas/boolean-visual.spec.ts-snapshots/boolean-stroke-alignment-openpencil-darwin.png b/tests/e2e/canvas/boolean-visual.spec.ts-snapshots/boolean-stroke-alignment-openpencil-darwin.pngnew file mode 100644index 000000000..6fa315167Binary files /dev/null and b/tests/e2e/canvas/boolean-visual.spec.ts-snapshots/boolean-stroke-alignment-openpencil-darwin.png differdiff --git a/tests/engine/render/canvas/boolean.test.ts b/tests/engine/render/canvas/boolean.test.tsindex e649933ce..9cdb38f64 100644--- a/tests/engine/render/canvas/boolean.test.ts+++ b/tests/engine/render/canvas/boolean.test.ts@@ -1,9 +1,10 @@-import { describe, expect, test } from 'bun:test'+import { describe, expect, spyOn, test } from 'bun:test'import { createDefaultNode } from '@open-pencil/scene-graph/node-defaults'import { initCanvasKit } from '#cli/headless'import { makeBooleanOperationPath } from '#core/canvas/boolean'+import { NodePathCaches } from '#core/canvas/paths/cache'import type { SkiaRenderer } from '#core/canvas/renderer'import { makeNodeShapePath, makePolygonPath, makeRRect } from '#core/canvas/shapes'import { BLACK } from '#core/constants'@@ -30,7 +31,8 @@ async function createRenderer(): Promise<SkiaRenderer> {},getFillGeometry() {return null- }+ },+ nodePaths: new NodePathCaches()} satisfies Partial<SkiaRenderer>return asRenderer(renderer)}@@ -113,6 +115,29 @@ describe('boolean operation paths', () => {path?.delete()})+ test('reflects a turned child after turning it, as the canvas places it', async () => {+ const r = await createRenderer()+ const api = createAPI()+ const first = api.createRectangle()+ const second = api.createRectangle()+ for (const stick of [first, second]) {+ stick.resize(160, 20)+ stick.y = 70+ }+ api.graph.updateNode(first.id, { rotation: 45 })+ api.graph.updateNode(second.id, { rotation: 45, flipX: true })++ const booleanNode = api.union([first, second], asPageNode(api.currentPage))+ const node = api.graph.getNode(booleanNode.id)+ expect(node).toBeDefined()+ if (!node) return+ const path = makeBooleanOperationPath(r, node, api.graph)+ const crossing = (x: number) => path?.contains(x, 30)++ expect([crossing(30), crossing(node.width - 30)]).toEqual([true, true])+ path?.delete()+ })+test('supports ellipse arc wedges', async () => {const r = await createRenderer()const api = createAPI()@@ -213,4 +238,75 @@ describe('boolean operation paths', () => {expect(path?.getBounds()).toEqual(new Float32Array([0, 0, 175, 100]))path?.delete()})++ test('rounds the combined outline by the operation’s own corner radius', async () => {+ const r = await createRenderer()+ const api = createAPI()+ const first = api.createRectangle()+ const second = api.createRectangle()+ first.resize(100, 100)+ second.resize(50, 50)+ second.x = 100++ const booleanNode = api.union([first, second], asPageNode(api.currentPage))+ api.graph.updateNode(booleanNode.id, { cornerRadius: 20 })+ const node = api.graph.getNode(booleanNode.id)+ expect(node).toBeDefined()+ if (!node) return+ const path = makeBooleanOperationPath(r, node, api.graph)++ expect([path?.contains(2, 2), path?.contains(2, 50), path?.contains(125, 25)]).toEqual([+ false,+ true,+ true+ ])+ path?.delete()+ })++ test('rounds an unchanged outline once, not on every frame', async () => {+ const r = await createRenderer()+ const api = createAPI()+ const first = api.createRectangle()+ const second = api.createRectangle()+ first.resize(100, 100)+ second.resize(50, 50)+ second.x = 100+ const booleanNode = api.union([first, second], asPageNode(api.currentPage))+ api.graph.updateNode(booleanNode.id, { cornerRadius: 20 })+ const node = api.graph.getNode(booleanNode.id)+ expect(node).toBeDefined()+ if (!node) return+ makeBooleanOperationPath(r, node, api.graph)?.delete()++ const outlineReads = spyOn(r.ck.Path.prototype, 'toSVGString')+ try {+ makeBooleanOperationPath(r, node, api.graph)?.delete()+ expect(outlineReads).not.toHaveBeenCalled()+ } finally {+ outlineReads.mockRestore()+ }+ })++ test('rounds the outline again after an operand changes', async () => {+ const r = await createRenderer()+ const api = createAPI()+ const first = api.createRectangle()+ const second = api.createRectangle()+ first.resize(100, 100)+ second.resize(50, 50)+ second.x = 100+ const booleanNode = api.union([first, second], asPageNode(api.currentPage))+ api.graph.updateNode(booleanNode.id, { cornerRadius: 20 })+ const node = api.graph.getNode(booleanNode.id)+ expect(node).toBeDefined()+ if (!node) return+ makeBooleanOperationPath(r, node, api.graph)?.delete()++ second.resize(80, 50)+ const path = makeBooleanOperationPath(r, node, api.graph)+ const bounds = path?.computeTightBounds()++ expect(bounds && bounds[2] - bounds[0]).toBe(180)+ path?.delete()+ })})diff --git a/tests/helpers/canvas/boolean/driver.ts b/tests/helpers/canvas/boolean/driver.tsnew file mode 100644index 000000000..67e2ba215--- /dev/null+++ b/tests/helpers/canvas/boolean/driver.ts@@ -0,0 +1,21 @@+import type { Page } from '@playwright/test'++import type * as BooleanScenes from '#tests/helpers/canvas/boolean/scene'++export function booleanStrokeAlignmentDriver(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/boolean/scene.ts'+ const scenes: typeof BooleanScenes = await import(sceneURL)+ scenes.createBooleanStrokeAlignmentScene(store.graph, store.state.currentPageId)+ store.clearSelection()+ store.requestRender()+ })+ }+ }+}diff --git a/tests/helpers/canvas/boolean/scene.ts b/tests/helpers/canvas/boolean/scene.tsnew file mode 100644index 000000000..e53031322--- /dev/null+++ b/tests/helpers/canvas/boolean/scene.ts@@ -0,0 +1,49 @@+import type { SceneGraph } from '@open-pencil/scene-graph'++const STROKE_VARIANTS = [+ { align: 'INSIDE', cornerRadius: 0 },+ { align: 'CENTER', cornerRadius: 0 },+ { align: 'OUTSIDE', cornerRadius: 0 },+ { align: 'OUTSIDE', cornerRadius: 24 }+] as const++export function createBooleanStrokeAlignmentScene(graph: SceneGraph, pageId: string): void {+ for (const [index, { align, cornerRadius }] of STROKE_VARIANTS.entries()) {+ const group = graph.createNode('BOOLEAN_OPERATION', pageId, {+ name: `${align} ${cornerRadius} boolean`,+ x: 72 + index * 152,+ y: 92,+ width: 124,+ height: 104,+ booleanOperation: 'UNION',+ cornerRadius,+ fills: [+ { type: 'SOLID', color: { r: 0.23, g: 0.51, b: 0.96, a: 1 }, visible: true, opacity: 1 }+ ],+ strokes: [+ {+ type: 'SOLID',+ color: { r: 0.96, g: 0.35, b: 0.35, a: 1 },+ weight: 10,+ visible: true,+ opacity: 0.6,+ align+ }+ ]+ })+ graph.createNode('RECTANGLE', group.id, {+ name: `${align} rectangle`,+ x: 0,+ y: 18,+ width: 82,+ height: 70+ })+ graph.createNode('RECTANGLE', group.id, {+ name: `${align} square`,+ x: 42,+ y: 0,+ width: 82,+ height: 104+ })+ }+}