AI-native design editor. Open-source Figma alternative.
feat: show each shape's own outline in the layers panel, as Figma does (#1333)
Danila Poyarkov918bf0692786
diff --git a/changes/1187/added.md b/changes/1187/added.mdindex c1a440e5a..1aa163aa3 100644--- a/changes/1187/added.md+++ b/changes/1187/added.md@@ -1 +1 @@-- Each vector's row in the layers panel shows the vector's own shape as its icon, as in Figma.+- Rows in the layers panel show each vector, rectangle, ellipse, line, polygon, and star as its own outline, turned and reflected as the layer is, as in Figma.diff --git a/changes/1333/fixed.md b/changes/1333/fixed.mdnew file mode 100644index 000000000..4c577bddd--- /dev/null+++ b/changes/1333/fixed.md@@ -0,0 +1 @@+- SVG export draws a whole donut's outer edge and hole instead of nothing.diff --git a/packages/core/src/canvas/paths/smooth-corners.ts b/packages/core/src/canvas/paths/smooth-corners.tsnew file mode 100644index 000000000..dc5a0ef6a--- /dev/null+++ b/packages/core/src/canvas/paths/smooth-corners.ts@@ -0,0 +1,358 @@+import type { SceneNode } from '@open-pencil/scene-graph'++/** What a rectangle's smoothed corners are drawn from. */+export type SmoothRectNode = Pick<+ SceneNode,+ | 'cornerRadius'+ | 'cornerSmoothing'+ | 'independentCorners'+ | 'topLeftRadius'+ | 'topRightRadius'+ | 'bottomRightRadius'+ | 'bottomLeftRadius'+>++/**+ * Where a smoothed rectangle is traced: a CanvasKit `PathBuilder`, or a writer of SVG path data.+ * `arcToRotated` takes CanvasKit's arguments, which match an SVG arc's.+ */+export interface SmoothCornerSink {+ moveTo(x: number, y: number): unknown+ lineTo(x: number, y: number): unknown+ cubicTo(x1: number, y1: number, x2: number, y2: number, x: number, y: number): unknown+ arcToRotated(+ rx: number,+ ry: number,+ xAxisRotate: number,+ useSmallArc: boolean,+ isCCW: boolean,+ x: number,+ y: number+ ): unknown+ close(): unknown+}++type SmoothCornerKey = 'topLeft' | 'topRight' | 'bottomRight' | 'bottomLeft'++type SmoothCorner = {+ radius: number+ budget: number+}++type SmoothCornerPathParams = {+ a: number+ b: number+ c: number+ d: number+ p: number+ radius: number+ arcSectionLength: number+}++function smoothCornerRadii(+ node: SmoothRectNode,+ width: number,+ height: number,+ spread: number+): Record<SmoothCornerKey, SmoothCorner> {+ const radius = (value: number) => Math.max(0, value + spread)+ const radii: Record<SmoothCornerKey, number> = node.independentCorners+ ? {+ topLeft: radius(node.topLeftRadius),+ topRight: radius(node.topRightRadius),+ bottomRight: radius(node.bottomRightRadius),+ bottomLeft: radius(node.bottomLeftRadius)+ }+ : {+ topLeft: radius(node.cornerRadius),+ topRight: radius(node.cornerRadius),+ bottomRight: radius(node.cornerRadius),+ bottomLeft: radius(node.cornerRadius)+ }++ if (+ radii.topLeft === radii.topRight &&+ radii.topRight === radii.bottomRight &&+ radii.bottomRight === radii.bottomLeft+ ) {+ const budget = Math.min(width, height) / 2+ const clampedRadius = Math.min(radii.topLeft, budget)+ return {+ topLeft: { radius: clampedRadius, budget },+ topRight: { radius: clampedRadius, budget },+ bottomRight: { radius: clampedRadius, budget },+ bottomLeft: { radius: clampedRadius, budget }+ }+ }++ const budgets: Record<SmoothCornerKey, number> = {+ topLeft: -1,+ topRight: -1,+ bottomRight: -1,+ bottomLeft: -1+ }+ const adjacentByCorner: Record<+ SmoothCornerKey,+ Array<{ corner: SmoothCornerKey; sideLength: number }>+ > = {+ topLeft: [+ { corner: 'topRight', sideLength: width },+ { corner: 'bottomLeft', sideLength: height }+ ],+ topRight: [+ { corner: 'topLeft', sideLength: width },+ { corner: 'bottomRight', sideLength: height }+ ],+ bottomRight: [+ { corner: 'bottomLeft', sideLength: width },+ { corner: 'topRight', sideLength: height }+ ],+ bottomLeft: [+ { corner: 'bottomRight', sideLength: width },+ { corner: 'topLeft', sideLength: height }+ ]+ }++ for (const corner of (Object.keys(radii) as SmoothCornerKey[]).sort(+ (a, b) => radii[b] - radii[a]+ )) {+ const cornerRadius = radii[corner]+ const budget = Math.min(+ ...adjacentByCorner[corner].map((adjacent) => {+ const adjacentRadius = radii[adjacent.corner]+ if (cornerRadius === 0 && adjacentRadius === 0) return 0+ if (budgets[adjacent.corner] >= 0) return adjacent.sideLength - budgets[adjacent.corner]+ return (cornerRadius / (cornerRadius + adjacentRadius)) * adjacent.sideLength+ })+ )+ budgets[corner] = budget+ radii[corner] = Math.min(cornerRadius, budget)+ }++ return {+ topLeft: { radius: radii.topLeft, budget: budgets.topLeft },+ topRight: { radius: radii.topRight, budget: budgets.topRight },+ bottomRight: { radius: radii.bottomRight, budget: budgets.bottomRight },+ bottomLeft: { radius: radii.bottomLeft, budget: budgets.bottomLeft }+ }+}++function degreesToRadians(degrees: number): number {+ return (degrees * Math.PI) / 180+}++function smoothCornerPathParams(corner: SmoothCorner, smoothing: number): SmoothCornerPathParams {+ let cornerSmoothing = smoothing+ let p = (1 + cornerSmoothing) * corner.radius+ if (corner.radius > 0) {+ const maxSmoothing = corner.budget / corner.radius - 1+ cornerSmoothing = Math.min(cornerSmoothing, maxSmoothing)+ p = Math.min(p, corner.budget)+ }++ const arcMeasure = 90 * (1 - cornerSmoothing)+ const arcSectionLength = Math.sin(degreesToRadians(arcMeasure / 2)) * corner.radius * Math.sqrt(2)+ const angleAlpha = (90 - arcMeasure) / 2+ const p3ToP4Distance = corner.radius * Math.tan(degreesToRadians(angleAlpha / 2))+ const angleBeta = 45 * cornerSmoothing+ const c = p3ToP4Distance * Math.cos(degreesToRadians(angleBeta))+ const d = c * Math.tan(degreesToRadians(angleBeta))+ const b = (p - arcSectionLength - c - d) / 3++ return {+ a: 2 * b,+ b,+ c,+ d,+ p,+ radius: corner.radius,+ arcSectionLength+ }+}++function drawTopRightSmoothCorner(+ path: SmoothCornerSink,+ corner: SmoothCornerPathParams,+ x: number,+ y: number+) {+ if (corner.radius === 0) {+ path.lineTo(x + corner.p, y)+ return+ }+ path.cubicTo(+ x + corner.a,+ y,+ x + corner.a + corner.b,+ y,+ x + corner.a + corner.b + corner.c,+ y + corner.d+ )+ path.arcToRotated(+ corner.radius,+ corner.radius,+ 0,+ true,+ false,+ x + corner.p - corner.d,+ y + corner.p - corner.a - corner.b - corner.c+ )+ path.cubicTo(+ x + corner.p,+ y + corner.p - corner.a - corner.b,+ x + corner.p,+ y + corner.p - corner.a,+ x + corner.p,+ y + corner.p+ )+}++function drawBottomRightSmoothCorner(+ path: SmoothCornerSink,+ corner: SmoothCornerPathParams,+ x: number,+ y: number+) {+ if (corner.radius === 0) {+ path.lineTo(x, y + corner.p)+ return+ }+ path.cubicTo(+ x,+ y + corner.a,+ x,+ y + corner.a + corner.b,+ x - corner.d,+ y + corner.a + corner.b + corner.c+ )+ path.arcToRotated(+ corner.radius,+ corner.radius,+ 0,+ true,+ false,+ x - corner.p + corner.a + corner.b + corner.c,+ y + corner.p - corner.d+ )+ path.cubicTo(+ x - corner.p + corner.a + corner.b,+ y + corner.p,+ x - corner.p + corner.a,+ y + corner.p,+ x - corner.p,+ y + corner.p+ )+}++function drawBottomLeftSmoothCorner(+ path: SmoothCornerSink,+ corner: SmoothCornerPathParams,+ x: number,+ y: number+) {+ if (corner.radius === 0) {+ path.lineTo(x - corner.p, y)+ return+ }+ path.cubicTo(+ x - corner.a,+ y,+ x - corner.a - corner.b,+ y,+ x - corner.a - corner.b - corner.c,+ y - corner.d+ )+ path.arcToRotated(+ corner.radius,+ corner.radius,+ 0,+ true,+ false,+ x - corner.p + corner.d,+ y - corner.p + corner.a + corner.b + corner.c+ )+ path.cubicTo(+ x - corner.p,+ y - corner.p + corner.a + corner.b,+ x - corner.p,+ y - corner.p + corner.a,+ x - corner.p,+ y - corner.p+ )+}++function drawTopLeftSmoothCorner(+ path: SmoothCornerSink,+ corner: SmoothCornerPathParams,+ x: number,+ y: number+) {+ if (corner.radius === 0) {+ path.lineTo(x, y - corner.p)+ return+ }+ path.cubicTo(+ x,+ y - corner.a,+ x,+ y - corner.a - corner.b,+ x + corner.d,+ y - corner.a - corner.b - corner.c+ )+ path.arcToRotated(+ corner.radius,+ corner.radius,+ 0,+ true,+ false,+ x + corner.p - corner.a - corner.b - corner.c,+ y - corner.p + corner.d+ )+ path.cubicTo(+ x + corner.p - corner.a - corner.b,+ y - corner.p,+ x + corner.p - corner.a,+ y - corner.p,+ x + corner.p,+ y - corner.p+ )+}++/**+ * Trace a rectangle with smoothed corners into `path`, as Figma rounds them. False, with nothing+ * traced, when no corner is rounded, so the caller can draw a plain rectangle.+ */+export function traceSmoothRect(+ path: SmoothCornerSink,+ node: SmoothRectNode,+ box: { left: number; top: number; right: number; bottom: number },+ spread = 0+): boolean {+ const { left, top, right, bottom } = box+ const smoothing = Math.max(0, Math.min(node.cornerSmoothing, 1))+ const corners = smoothCornerRadii(node, right - left, bottom - top, spread)+ const topLeftCorner = smoothCornerPathParams(corners.topLeft, smoothing)+ const topRightCorner = smoothCornerPathParams(corners.topRight, smoothing)+ const bottomRightCorner = smoothCornerPathParams(corners.bottomRight, smoothing)+ const bottomLeftCorner = smoothCornerPathParams(corners.bottomLeft, smoothing)++ if (+ topLeftCorner.radius === 0 &&+ topRightCorner.radius === 0 &&+ bottomRightCorner.radius === 0 &&+ bottomLeftCorner.radius === 0+ ) {+ return false+ }++ path.moveTo(right - topRightCorner.p, top)+ drawTopRightSmoothCorner(path, topRightCorner, right - topRightCorner.p, top)+ path.lineTo(right, bottom - bottomRightCorner.p)+ drawBottomRightSmoothCorner(path, bottomRightCorner, right, bottom - bottomRightCorner.p)+ path.lineTo(left + bottomLeftCorner.p, bottom)+ drawBottomLeftSmoothCorner(path, bottomLeftCorner, left + bottomLeftCorner.p, bottom)+ path.lineTo(left, top + topLeftCorner.p)+ drawTopLeftSmoothCorner(path, topLeftCorner, left, top + topLeftCorner.p)+ path.close()+ return true+}diff --git a/packages/core/src/canvas/shapes.ts b/packages/core/src/canvas/shapes.tsindex d85f44e0d..d99fa80c8 100644--- a/packages/core/src/canvas/shapes.ts+++ b/packages/core/src/canvas/shapes.ts@@ -1,4 +1,4 @@-import type { Canvas, Path, PathBuilder } from 'canvaskit-wasm'+import type { Canvas, Path } from 'canvaskit-wasm'import type { SceneNode } from '@open-pencil/scene-graph'import { polygonOutline, type PolygonOutlineCommand } from '@open-pencil/scene-graph/polygon'@@ -6,6 +6,7 @@ import { shapeWithTextGeometry } from '@open-pencil/scene-graph/shape-with-text'import { vectorNetworkToPath, geometryBlobToPath } from '#core/vector'+import { traceSmoothRect } from './paths/smooth-corners'import type { SkiaRenderer } from './renderer'export function nodeHasRadius(node: SceneNode): boolean {@@ -32,292 +33,6 @@ export function nodeHasSmoothCorners(node: SceneNode): boolean {return node.cornerRadius > 0}-type SmoothCornerKey = 'topLeft' | 'topRight' | 'bottomRight' | 'bottomLeft'--type SmoothCorner = {- radius: number- budget: number-}--type SmoothCornerPathParams = {- a: number- b: number- c: number- d: number- p: number- radius: number- arcSectionLength: number-}--function smoothCornerRadii(- node: SceneNode,- width: number,- height: number,- spread: number-): Record<SmoothCornerKey, SmoothCorner> {- const radius = (value: number) => Math.max(0, value + spread)- const radii: Record<SmoothCornerKey, number> = node.independentCorners- ? {- topLeft: radius(node.topLeftRadius),- topRight: radius(node.topRightRadius),- bottomRight: radius(node.bottomRightRadius),- bottomLeft: radius(node.bottomLeftRadius)- }- : {- topLeft: radius(node.cornerRadius),- topRight: radius(node.cornerRadius),- bottomRight: radius(node.cornerRadius),- bottomLeft: radius(node.cornerRadius)- }-- if (- radii.topLeft === radii.topRight &&- radii.topRight === radii.bottomRight &&- radii.bottomRight === radii.bottomLeft- ) {- const budget = Math.min(width, height) / 2- const clampedRadius = Math.min(radii.topLeft, budget)- return {- topLeft: { radius: clampedRadius, budget },- topRight: { radius: clampedRadius, budget },- bottomRight: { radius: clampedRadius, budget },- bottomLeft: { radius: clampedRadius, budget }- }- }-- const budgets: Record<SmoothCornerKey, number> = {- topLeft: -1,- topRight: -1,- bottomRight: -1,- bottomLeft: -1- }- const adjacentByCorner: Record<- SmoothCornerKey,- Array<{ corner: SmoothCornerKey; sideLength: number }>- > = {- topLeft: [- { corner: 'topRight', sideLength: width },- { corner: 'bottomLeft', sideLength: height }- ],- topRight: [- { corner: 'topLeft', sideLength: width },- { corner: 'bottomRight', sideLength: height }- ],- bottomRight: [- { corner: 'bottomLeft', sideLength: width },- { corner: 'topRight', sideLength: height }- ],- bottomLeft: [- { corner: 'bottomRight', sideLength: width },- { corner: 'topLeft', sideLength: height }- ]- }-- for (const corner of (Object.keys(radii) as SmoothCornerKey[]).sort(- (a, b) => radii[b] - radii[a]- )) {- const cornerRadius = radii[corner]- const budget = Math.min(- ...adjacentByCorner[corner].map((adjacent) => {- const adjacentRadius = radii[adjacent.corner]- if (cornerRadius === 0 && adjacentRadius === 0) return 0- if (budgets[adjacent.corner] >= 0) return adjacent.sideLength - budgets[adjacent.corner]- return (cornerRadius / (cornerRadius + adjacentRadius)) * adjacent.sideLength- })- )- budgets[corner] = budget- radii[corner] = Math.min(cornerRadius, budget)- }-- return {- topLeft: { radius: radii.topLeft, budget: budgets.topLeft },- topRight: { radius: radii.topRight, budget: budgets.topRight },- bottomRight: { radius: radii.bottomRight, budget: budgets.bottomRight },- bottomLeft: { radius: radii.bottomLeft, budget: budgets.bottomLeft }- }-}--function degreesToRadians(degrees: number): number {- return (degrees * Math.PI) / 180-}--function smoothCornerPathParams(corner: SmoothCorner, smoothing: number): SmoothCornerPathParams {- let cornerSmoothing = smoothing- let p = (1 + cornerSmoothing) * corner.radius- if (corner.radius > 0) {- const maxSmoothing = corner.budget / corner.radius - 1- cornerSmoothing = Math.min(cornerSmoothing, maxSmoothing)- p = Math.min(p, corner.budget)- }-- const arcMeasure = 90 * (1 - cornerSmoothing)- const arcSectionLength = Math.sin(degreesToRadians(arcMeasure / 2)) * corner.radius * Math.sqrt(2)- const angleAlpha = (90 - arcMeasure) / 2- const p3ToP4Distance = corner.radius * Math.tan(degreesToRadians(angleAlpha / 2))- const angleBeta = 45 * cornerSmoothing- const c = p3ToP4Distance * Math.cos(degreesToRadians(angleBeta))- const d = c * Math.tan(degreesToRadians(angleBeta))- const b = (p - arcSectionLength - c - d) / 3-- return {- a: 2 * b,- b,- c,- d,- p,- radius: corner.radius,- arcSectionLength- }-}--function drawTopRightSmoothCorner(- path: PathBuilder,- corner: SmoothCornerPathParams,- x: number,- y: number-) {- if (corner.radius === 0) {- path.lineTo(x + corner.p, y)- return- }- path.cubicTo(- x + corner.a,- y,- x + corner.a + corner.b,- y,- x + corner.a + corner.b + corner.c,- y + corner.d- )- path.arcToRotated(- corner.radius,- corner.radius,- 0,- true,- false,- x + corner.p - corner.d,- y + corner.p - corner.a - corner.b - corner.c- )- path.cubicTo(- x + corner.p,- y + corner.p - corner.a - corner.b,- x + corner.p,- y + corner.p - corner.a,- x + corner.p,- y + corner.p- )-}--function drawBottomRightSmoothCorner(- path: PathBuilder,- corner: SmoothCornerPathParams,- x: number,- y: number-) {- if (corner.radius === 0) {- path.lineTo(x, y + corner.p)- return- }- path.cubicTo(- x,- y + corner.a,- x,- y + corner.a + corner.b,- x - corner.d,- y + corner.a + corner.b + corner.c- )- path.arcToRotated(- corner.radius,- corner.radius,- 0,- true,- false,- x - corner.p + corner.a + corner.b + corner.c,- y + corner.p - corner.d- )- path.cubicTo(- x - corner.p + corner.a + corner.b,- y + corner.p,- x - corner.p + corner.a,- y + corner.p,- x - corner.p,- y + corner.p- )-}--function drawBottomLeftSmoothCorner(- path: PathBuilder,- corner: SmoothCornerPathParams,- x: number,- y: number-) {- if (corner.radius === 0) {- path.lineTo(x - corner.p, y)- return- }- path.cubicTo(- x - corner.a,- y,- x - corner.a - corner.b,- y,- x - corner.a - corner.b - corner.c,- y - corner.d- )- path.arcToRotated(- corner.radius,- corner.radius,- 0,- true,- false,- x - corner.p + corner.d,- y - corner.p + corner.a + corner.b + corner.c- )- path.cubicTo(- x - corner.p,- y - corner.p + corner.a + corner.b,- x - corner.p,- y - corner.p + corner.a,- x - corner.p,- y - corner.p- )-}--function drawTopLeftSmoothCorner(- path: PathBuilder,- corner: SmoothCornerPathParams,- x: number,- y: number-) {- if (corner.radius === 0) {- path.lineTo(x, y - corner.p)- return- }- path.cubicTo(- x,- y - corner.a,- x,- y - corner.a - corner.b,- x + corner.d,- y - corner.a - corner.b - corner.c- )- path.arcToRotated(- corner.radius,- corner.radius,- 0,- true,- false,- x + corner.p - corner.a - corner.b - corner.c,- y - corner.p + corner.d- )- path.cubicTo(- x + corner.p - corner.a - corner.b,- y - corner.p,- x + corner.p - corner.a,- y - corner.p,- x + corner.p,- y - corner.p- )-}-export function makeSmoothRRectPath(r: SkiaRenderer,node: SceneNode,@@ -337,32 +52,9 @@ export function makeSmoothRRectPath(return path.detachAndDelete()}- const smoothing = Math.max(0, Math.min(node.cornerSmoothing, 1))- const corners = smoothCornerRadii(node, width, height, spread)- const topLeftCorner = smoothCornerPathParams(corners.topLeft, smoothing)- const topRightCorner = smoothCornerPathParams(corners.topRight, smoothing)- const bottomRightCorner = smoothCornerPathParams(corners.bottomRight, smoothing)- const bottomLeftCorner = smoothCornerPathParams(corners.bottomLeft, smoothing)-- if (- topLeftCorner.radius === 0 &&- topRightCorner.radius === 0 &&- bottomRightCorner.radius === 0 &&- bottomLeftCorner.radius === 0- ) {+ if (!traceSmoothRect(path, node, { left, top, right, bottom }, spread)) {path.addRect(r.ck.LTRBRect(left, top, right, bottom))- return path.detachAndDelete()}-- path.moveTo(right - topRightCorner.p, top)- drawTopRightSmoothCorner(path, topRightCorner, right - topRightCorner.p, top)- path.lineTo(right, bottom - bottomRightCorner.p)- drawBottomRightSmoothCorner(path, bottomRightCorner, right, bottom - bottomRightCorner.p)- path.lineTo(left + bottomLeftCorner.p, bottom)- drawBottomLeftSmoothCorner(path, bottomLeftCorner, left + bottomLeftCorner.p, bottom)- path.lineTo(left, top + topLeftCorner.p)- drawTopLeftSmoothCorner(path, topLeftCorner, left, top + topLeftCorner.p)- path.close()return path.detachAndDelete()}diff --git a/packages/core/src/io/formats/svg/export.ts b/packages/core/src/io/formats/svg/export.tsindex 3a786a955..7a8a72ac9 100644--- a/packages/core/src/io/formats/svg/export.ts+++ b/packages/core/src/io/formats/svg/export.ts@@ -23,7 +23,12 @@ import {arcPath} from './paths'-export { geometryBlobToSVGPath, vectorNetworkToSVGPaths } from './paths'+export {+ geometryBlobToSVGPath,+ nodeOutlinePath,+ vectorNetworkToSVGPaths,+ type OutlineNode+} from './paths'import type {SceneGraph,diff --git a/packages/core/src/io/formats/svg/index.ts b/packages/core/src/io/formats/svg/index.tsindex d5a40b352..3311a7f7b 100644--- a/packages/core/src/io/formats/svg/index.ts+++ b/packages/core/src/io/formats/svg/index.ts@@ -1,4 +1,10 @@-export { renderNodesToSVG, geometryBlobToSVGPath, vectorNetworkToSVGPaths } from './export'+export {+ renderNodesToSVG,+ geometryBlobToSVGPath,+ nodeOutlinePath,+ vectorNetworkToSVGPaths,+ type OutlineNode+} from './export'export {createSVGNodes,createSVGNodesFromImport,diff --git a/packages/core/src/io/formats/svg/paths.ts b/packages/core/src/io/formats/svg/paths.tsindex a38f15b28..faf7e0a3e 100644--- a/packages/core/src/io/formats/svg/paths.ts+++ b/packages/core/src/io/formats/svg/paths.ts@@ -9,6 +9,7 @@ import type {import { polygonVertices } from '@open-pencil/scene-graph/geometry'import { outlineSVGPath, polygonOutline } from '@open-pencil/scene-graph/polygon'+import { traceSmoothRect, type SmoothCornerSink } from '#core/canvas/paths/smooth-corners'import { nodeHasRadius } from '#core/canvas/shapes'const CMD_CLOSE = 0@@ -247,7 +248,19 @@ export function makePolygonPoints(node: SceneNode): string {export const hasRadius = nodeHasRadius-export function roundedRectPath(node: SceneNode): string {+type RectOutlineNode = Pick<+ SceneNode,+ | 'width'+ | 'height'+ | 'cornerRadius'+ | 'independentCorners'+ | 'topLeftRadius'+ | 'topRightRadius'+ | 'bottomRightRadius'+ | 'bottomLeftRadius'+>++export function roundedRectPath(node: RectOutlineNode): string {const w = node.widthconst h = node.heightlet tl: number, tr: number, br: number, bl: number@@ -279,7 +292,7 @@ export function roundedRectPath(node: SceneNode): string {]).join('')}-export function arcPath(node: SceneNode): string {+export function arcPath(node: Pick<SceneNode, 'width' | 'height' | 'arcData'>): string {if (!node.arcData) return ''const { startingAngle, endingAngle, innerRadius } = node.arcDataconst cx = node.width / 2@@ -288,8 +301,13 @@ export function arcPath(node: SceneNode): string {const ry = node.height / 2const fullCircle = Math.abs(endingAngle - startingAngle) >= Math.PI * 2 - 0.001- if (fullCircle && innerRadius <= 0) {- return `M${round(cx - rx)} ${round(cy)}A${round(rx)} ${round(ry)} 0 1 1 ${round(cx + rx)} ${round(cy)}A${round(rx)} ${round(ry)} 0 1 1 ${round(cx - rx)} ${round(cy)}Z`+ const ring = (rx: number, ry: number, sweep: 0 | 1) =>+ `M${round(cx - rx)} ${round(cy)}A${round(rx)} ${round(ry)} 0 1 ${sweep} ${round(cx + rx)} ${round(cy)}A${round(rx)} ${round(ry)} 0 1 ${sweep} ${round(cx - rx)} ${round(cy)}Z`+ // A whole ring has no ends to join: it is its outer edge and, for a donut, its hole, wound+ // the other way so the default nonzero fill leaves the hole empty.+ if (fullCircle) {+ const outer = ring(rx, ry, 1)+ return innerRadius > 0 ? outer + ring(rx * innerRadius, ry * innerRadius, 0) : outer}const x1 = round(cx + rx * Math.cos(startingAngle))@@ -317,3 +335,53 @@ export function arcPath(node: SceneNode): string {return parts.join('')}++/** A rectangle with smoothed corners as path data, traced as the canvas draws it. */+function smoothRectPath(node: RectOutlineNode & Pick<SceneNode, 'cornerSmoothing'>): string {+ const parts: string[] = []+ const point = (x: number, y: number) => `${round(x)} ${round(y)}`+ const sink: SmoothCornerSink = {+ moveTo: (x, y) => parts.push(`M${point(x, y)}`),+ lineTo: (x, y) => parts.push(`L${point(x, y)}`),+ cubicTo: (x1, y1, x2, y2, x, y) =>+ parts.push(`C${point(x1, y1)} ${point(x2, y2)} ${point(x, y)}`),+ arcToRotated: (rx, ry, rotation, useSmallArc, isCCW, x, y) =>+ parts.push(+ `A${round(rx)} ${round(ry)} ${rotation} ${useSmallArc ? 0 : 1} ${isCCW ? 0 : 1} ${point(x, y)}`+ ),+ close: () => parts.push('Z')+ }+ const box = { left: 0, top: 0, right: node.width, bottom: node.height }+ return traceSmoothRect(sink, node, box) ? parts.join('') : roundedRectPath(node)+}++/** What a layer's outline is drawn from. */+export type OutlineNode = RectOutlineNode &+ Pick<+ SceneNode,+ 'type' | 'arcData' | 'pointCount' | 'starInnerRadius' | 'cornerSmoothing' | 'vectorNetwork'+ >++const FULL_ELLIPSE = { startingAngle: 0, endingAngle: Math.PI * 2, innerRadius: 0 }++/**+ * A shape layer's outline in its own box as path data: a rectangle with its corners, an ellipse+ * or arc, a line, a polygon or star, or a vector's network. Null for other layers.+ */+export function nodeOutlinePath(node: OutlineNode): string | null {+ switch (node.type) {+ case 'RECTANGLE':+ return node.cornerSmoothing > 0 ? smoothRectPath(node) : roundedRectPath(node)+ case 'ELLIPSE':+ return arcPath({ ...node, arcData: node.arcData ?? FULL_ELLIPSE })+ case 'LINE':+ return `M0 0L${round(node.width)} ${round(node.height)}`+ case 'POLYGON':+ case 'STAR':+ return outlineSVGPath(polygonOutline(node), (value) => round(value))+ case 'VECTOR':+ return node.vectorNetwork ? vectorNetworkToSVGPaths(node.vectorNetwork).join('') : null+ default:+ return null+ }+}diff --git a/packages/core/src/io/index.ts b/packages/core/src/io/index.tsindex 0985e13c8..01e3f923c 100644--- a/packages/core/src/io/index.ts+++ b/packages/core/src/io/index.ts@@ -38,7 +38,9 @@ export {prepareSVGImport,renderNodesToSVG,geometryBlobToSVGPath,+ nodeOutlinePath,vectorNetworkToSVGPaths,+ type OutlineNode,type SVGImportData,type SVGImportOptions} from './formats/svg'diff --git a/packages/core/tests/io/formats/svg/paths.test.ts b/packages/core/tests/io/formats/svg/paths.test.tsindex 18077520a..cceea471f 100644--- a/packages/core/tests/io/formats/svg/paths.test.ts+++ b/packages/core/tests/io/formats/svg/paths.test.ts@@ -1,8 +1,13 @@import { expect, test } from 'bun:test'-import { vectorNetworkToSVGPaths } from '#core/io/formats/svg/paths'+import {+ createDefaultNode,+ type NodeType,+ type SceneNode,+ type VectorNetwork+} from '@open-pencil/scene-graph'-import type { VectorNetwork } from '@open-pencil/scene-graph'+import { nodeOutlinePath, vectorNetworkToSVGPaths } from '#core/io/formats/svg/paths'const corner = { x: 0, y: 0 }const line = (start: number, end: number) => ({@@ -30,7 +35,52 @@ test('segments outside every region draw as open paths after the regions', () =>})test('a network with regions only draws the regions', () => {- expect(vectorNetworkToSVGPaths({ ...network, segments: network.segments.slice(0, 3) })).toEqual(- ['M19 20L9 12L19 4L19 20Z']+ expect(vectorNetworkToSVGPaths({ ...network, segments: network.segments.slice(0, 3) })).toEqual([+ 'M19 20L9 12L19 4L19 20Z'+ ])+})++const shape = (type: NodeType, overrides: Partial<SceneNode> = {}) =>+ createDefaultNode(() => 'shape', type, { width: 100, height: 50, ...overrides })++test("a shape layer's outline is drawn in its own box", () => {+ expect(nodeOutlinePath(shape('RECTANGLE'))).toBe('M0 0L100 0L100 50L0 50L0 0Z')+ expect(nodeOutlinePath(shape('RECTANGLE', { cornerRadius: 10 }))).toContain('A10 10')+ expect(nodeOutlinePath(shape('LINE', { height: 0 }))).toBe('M0 0L100 0')+ expect(nodeOutlinePath(shape('VECTOR', { vectorNetwork: network }))).toBe(+ 'M19 20L9 12L19 4L19 20ZM5 19L5 5'+ )+})++test('an ellipse without arc data draws whole, and an arc draws its sweep', () => {+ expect(nodeOutlinePath(shape('ELLIPSE', { arcData: null }))).toBe(+ 'M0 25A50 25 0 1 1 100 25A50 25 0 1 1 0 25Z'+ )+ const half = { startingAngle: 0, endingAngle: Math.PI, innerRadius: 0 }+ expect(nodeOutlinePath(shape('ELLIPSE', { arcData: half }))).toBe(+ 'M100 25A50 25 0 0 1 0 25L50 25Z'+ )+})++test('a polygon and a star draw their points, and other layers have no outline', () => {+ expect(nodeOutlinePath(shape('POLYGON', { pointCount: 3 }))?.match(/L/g)).toHaveLength(2)+ expect(nodeOutlinePath(shape('STAR', { pointCount: 5 }))?.match(/L/g)).toHaveLength(9)+ expect(nodeOutlinePath(shape('FRAME'))).toBeNull()+ expect(nodeOutlinePath(shape('VECTOR', { vectorNetwork: null }))).toBeNull()+})++test('a whole donut draws its outer edge and its hole the other way, so the hole stays empty', () => {+ const donut = { startingAngle: 0, endingAngle: Math.PI * 2, innerRadius: 0.5 }+ expect(nodeOutlinePath(shape('ELLIPSE', { arcData: donut }))).toBe(+ 'M0 25A50 25 0 1 1 100 25A50 25 0 1 1 0 25ZM25 25A25 12.5 0 1 0 75 25A25 12.5 0 1 0 25 25Z'+ )+})++test('a smoothed rectangle traces its corners as the canvas does', () => {+ const smooth = nodeOutlinePath(shape('RECTANGLE', { cornerRadius: 20, cornerSmoothing: 0.6 }))+ expect(smooth).toMatch(/^M[^Z]*C[^Z]*A[^Z]*Z$/)+ expect(smooth).not.toBe(nodeOutlinePath(shape('RECTANGLE', { cornerRadius: 20 })))+ expect(nodeOutlinePath(shape('RECTANGLE', { cornerSmoothing: 0.6 }))).toBe(+ 'M0 0L100 0L100 50L0 50L0 0Z')})diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.tsindex d6142a968..afa0e18ad 100644--- a/packages/vue/src/index.ts+++ b/packages/vue/src/index.ts@@ -253,8 +253,8 @@ export type {LayerRow,LayerSelectionMode,LayerTreeContext,- LayerTreeVirtualizer,- LayerVectorIcon+ LayerOutline,+ LayerTreeVirtualizer} from '#vue/primitives/LayerTree'export { LayoutControlsRoot, useLayoutControlsContext } from '#vue/primitives/LayoutControls'export type {diff --git a/packages/vue/src/primitives/LayerTree/LayerTreeRoot.vue b/packages/vue/src/primitives/LayerTree/LayerTreeRoot.vueindex a5b061247..1f188cf6c 100644--- a/packages/vue/src/primitives/LayerTree/LayerTreeRoot.vue+++ b/packages/vue/src/primitives/LayerTree/LayerTreeRoot.vue@@ -5,7 +5,7 @@ import { computed, nextTick, onScopeDispose, reactive, ref } from 'vue'import type { SceneNode } from '@open-pencil/scene-graph'import { useEditor } from '#vue/editor/context'-import { provideLayerTree } from '#vue/primitives/LayerTree/context'+import { LAYER_OUTLINE_FIELDS, provideLayerTree } from '#vue/primitives/LayerTree/context'import type {LayerNode,LayerSelectionMode,@@ -85,13 +85,10 @@ const PATCHABLE_NODE_KEYS = new Set<keyof SceneNode>(['visible','locked','variableModes',- // A vector's row icon is drawn from its network in its box, turned and reflected.- 'vectorNetwork',- 'width',- 'height',- 'rotation',- 'flipX',- 'flipY'+ 'isMask',+ 'fills',+ 'strokes',+ ...LAYER_OUTLINE_FIELDS])function patchTreeNode(id: string, changes: Partial<SceneNode>) {diff --git a/packages/vue/src/primitives/LayerTree/context.ts b/packages/vue/src/primitives/LayerTree/context.tsindex 77d68ba0b..c82e0dae8 100644--- a/packages/vue/src/primitives/LayerTree/context.ts+++ b/packages/vue/src/primitives/LayerTree/context.ts@@ -1,18 +1,31 @@import { type ComputedRef, type InjectionKey, type Ref, inject, provide } from 'vue'import type { Editor } from '@open-pencil/core/editor'-import type { VectorNetwork } from '@open-pencil/scene-graph'+import type { SceneNode } from '@open-pencil/scene-graph'import type { ShapeWithTextType } from '@open-pencil/scene-graph/shape-with-text'-/** What a vector's row draws as its icon: its network in its box, turned and reflected. */-export interface LayerVectorIcon {- network: VectorNetwork- width: number- height: number- rotation: number- flipX: boolean- flipY: boolean-}+/** What a shape layer's row draws as its icon: its outline in its box, turned and reflected. */+export const LAYER_OUTLINE_FIELDS = [+ 'type',+ 'width',+ 'height',+ 'rotation',+ 'flipX',+ 'flipY',+ 'cornerRadius',+ 'independentCorners',+ 'topLeftRadius',+ 'topRightRadius',+ 'bottomRightRadius',+ 'bottomLeftRadius',+ 'cornerSmoothing',+ 'arcData',+ 'pointCount',+ 'starInnerRadius',+ 'vectorNetwork'+] as const satisfies readonly (keyof SceneNode)[]++export type LayerOutline = Pick<SceneNode, (typeof LAYER_OUTLINE_FIELDS)[number]>export interface LayerNode {id: string@@ -25,8 +38,12 @@ export interface LayerNode {icon?: boolean/** A shape with text's kind, which its row draws. */shapeWithTextType?: ShapeWithTextType- /** A vector's own shape, which its row draws as its icon. */- vector?: LayerVectorIcon+ /** A shape layer's own outline, which its row draws as its icon. */+ outline?: LayerOutline+ /** Whether the layer shows an image, which its row marks in place of the outline. */+ image?: boolean+ /** Whether the layer masks the layers above it. */+ mask?: booleanvisible: booleanlocked: boolean/** The variable modes set on the layer itself, which Figma tags its row with. */diff --git a/packages/vue/src/primitives/LayerTree/index.ts b/packages/vue/src/primitives/LayerTree/index.tsindex f21da333b..e6a3defa9 100644--- a/packages/vue/src/primitives/LayerTree/index.ts+++ b/packages/vue/src/primitives/LayerTree/index.ts@@ -7,8 +7,8 @@ export type {LayerRow,LayerSelectionMode,LayerTreeContext,- LayerTreeVirtualizer,- LayerVectorIcon+ LayerOutline,+ LayerTreeVirtualizer} from '#vue/primitives/LayerTree/context'export {buildLayerTreeModel,diff --git a/packages/vue/src/primitives/LayerTree/model.ts b/packages/vue/src/primitives/LayerTree/model.tsindex c1d3cfd02..c020e88f8 100644--- a/packages/vue/src/primitives/LayerTree/model.ts+++ b/packages/vue/src/primitives/LayerTree/model.ts@@ -1,15 +1,16 @@-import { isEqual } from 'es-toolkit'+import { isEqual, pick } from 'es-toolkit'import { toRaw } from 'vue'import { isGeneratedFrame, readIcon, slotPropertyId } from '@open-pencil/scene-graph'import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'import type { ShapeWithTextType } from '@open-pencil/scene-graph/shape-with-text'+import { LAYER_OUTLINE_FIELDS } from '#vue/primitives/LayerTree/context'import type {LayerNode,+ LayerOutline,LayerRow,- LayerSelectionMode,- LayerVectorIcon+ LayerSelectionMode} from '#vue/primitives/LayerTree/context'function explicitModeIds(node: SceneNode): string[] | undefined {@@ -21,26 +22,29 @@ function shapeWithTextTypeOf(node: SceneNode): ShapeWithTextType | undefined {return node.type === 'SHAPE_WITH_TEXT' ? node.shapeWithTextType : undefined}-/** A vector's row draws its own shape in its box, turned and reflected, as Figma's does. */-function vectorIconOf(node: SceneNode): LayerVectorIcon | undefined {- if (node.type !== 'VECTOR' || !node.vectorNetwork) return undefined- const { vectorNetwork: network, width, height, rotation, flipX, flipY } = node- return { network, width, height, rotation, flipX, flipY }+/** The layers whose rows draw their own outline, as Figma's do; others keep their kind's glyph. */+const OUTLINE_TYPES = new Set(['RECTANGLE', 'ELLIPSE', 'LINE', 'POLYGON', 'STAR', 'VECTOR'])++function outlineOf(node: SceneNode): LayerOutline | undefined {+ if (!OUTLINE_TYPES.has(node.type) || (node.type === 'VECTOR' && !node.vectorNetwork)) {+ return undefined+ }+ return pick(node, LAYER_OUTLINE_FIELDS)}-function sameVectorIcon(target: LayerVectorIcon | undefined, source: LayerVectorIcon | undefined) {- if (!target || !source) return target === source- // The target may be a reactive row, which hands back a proxy of the network it holds.- return (- toRaw(target.network) === source.network &&- target.width === source.width &&- target.height === source.height &&- target.rotation === source.rotation &&- target.flipX === source.flipX &&- target.flipY === source.flipY+/** A visible image paint, in fills or strokes, which Figma marks a layer's row with. */+function showsImage(node: SceneNode): boolean {+ return [...node.fills, ...node.strokes].some(+ (paint) => paint.type === 'IMAGE' && paint.visible && paint.opacity > 0)}+function sameOutline(target: LayerOutline | undefined, source: LayerOutline | undefined) {+ if (!target || !source) return target === source+ // The target may be a reactive row, which hands back proxies of the objects it holds.+ return LAYER_OUTLINE_FIELDS.every((field) => toRaw(target[field]) === source[field])+}+function nodeToLayerNode(node: SceneNode): LayerNode {return {id: node.id,@@ -50,7 +54,9 @@ function nodeToLayerNode(node: SceneNode): LayerNode {slot: !!slotPropertyId(node),icon: !!readIcon(node),shapeWithTextType: shapeWithTextTypeOf(node),- vector: vectorIconOf(node),+ outline: outlineOf(node),+ image: showsImage(node),+ mask: node.isMask,visible: node.visible,locked: node.locked,modeIds: explicitModeIds(node)@@ -99,7 +105,7 @@ export function indexLayerNodes(items: readonly LayerNode[]): Map<string, LayerN}export function patchLayerNode(target: LayerNode, source: SceneNode): boolean {- const vector = vectorIconOf(source)+ const outline = outlineOf(source)const changed =target.name !== source.name ||target.type !== source.type ||@@ -107,7 +113,9 @@ export function patchLayerNode(target: LayerNode, source: SceneNode): boolean {target.slot !== !!slotPropertyId(source) ||target.icon !== !!readIcon(source) ||target.shapeWithTextType !== shapeWithTextTypeOf(source) ||- !sameVectorIcon(target.vector, vector) ||+ !sameOutline(target.outline, outline) ||+ target.image !== showsImage(source) ||+ target.mask !== source.isMask ||target.visible !== source.visible ||target.locked !== source.locked ||!isEqual(target.modeIds, explicitModeIds(source))@@ -118,7 +126,9 @@ export function patchLayerNode(target: LayerNode, source: SceneNode): boolean {target.slot = !!slotPropertyId(source)target.icon = !!readIcon(source)target.shapeWithTextType = shapeWithTextTypeOf(source)- target.vector = vector+ target.outline = outline+ target.image = showsImage(source)+ target.mask = source.isMasktarget.visible = source.visibletarget.locked = source.lockedtarget.modeIds = explicitModeIds(source)diff --git a/packages/vue/tests/primitives/LayerTree/model.test.ts b/packages/vue/tests/primitives/LayerTree/model.test.tsindex 844cb54d4..7fef819ef 100644--- a/packages/vue/tests/primitives/LayerTree/model.test.ts+++ b/packages/vue/tests/primitives/LayerTree/model.test.ts@@ -3,6 +3,7 @@ import { describe, expect, test } from 'bun:test'import { reactive } from 'vue'import { createShapeWithText, SceneGraph, withIcon } from '@open-pencil/scene-graph'+import { colorToFill } from '@open-pencil/scene-graph/color'import { buildLayerTreeModel, patchLayerNode } from '@open-pencil/vue'import { dropIndex } from '#vue/primitives/LayerTree/model'@@ -57,7 +58,7 @@ describe('layer tree model', () => {expect(row.shapeWithTextType).toBe('ELLIPSE')})- test("carries a vector's network and placement, so its row draws the shape", () => {+ test("carries a shape's outline and placement, so its row draws the shape", () => {const graph = new SceneGraph()const pageId = graph.getPages()[0].idconst line = (x: number) => ({@@ -70,22 +71,52 @@ describe('layer tree model', () => {})const vector = graph.createNode('VECTOR', pageId, { vectorNetwork: line(10) })const rect = graph.createNode('RECTANGLE', pageId)+ const frame = graph.createNode('FRAME', pageId)const model = buildLayerTreeModel(graph, pageId)const row = model.byId.get(vector.id)if (!row) throw new Error('Expected the vector in the model')- expect(row.vector?.network).toBe(vector.vectorNetwork ?? undefined)- expect(model.byId.get(rect.id)?.vector).toBeUndefined()+ expect(row.outline?.vectorNetwork).toBe(vector.vectorNetwork)+ expect(model.byId.get(rect.id)?.outline).toMatchObject({ type: 'RECTANGLE' })+ expect(model.byId.get(frame.id)?.outline).toBeUndefined()// The layer tree patches its rows through their reactive proxies.expect(patchLayerNode(reactive(row), vector)).toBe(false)graph.updateNode(vector.id, { vectorNetwork: line(20) })expect(patchLayerNode(reactive(row), vector)).toBe(true)- expect(row.vector?.network).toBe(vector.vectorNetwork ?? undefined)+ expect(row.outline?.vectorNetwork).toBe(vector.vectorNetwork)graph.updateNode(vector.id, { rotation: 30, flipX: true })expect(patchLayerNode(reactive(row), vector)).toBe(true)- expect(row.vector).toMatchObject({ rotation: 30, flipX: true })+ expect(row.outline).toMatchObject({ rotation: 30, flipX: true })++ const rectRow = model.byId.get(rect.id)+ if (!rectRow) throw new Error('Expected the rectangle in the model')+ graph.updateNode(rect.id, { cornerRadius: 8 })+ expect(patchLayerNode(reactive(rectRow), rect)).toBe(true)+ expect(rectRow.outline?.cornerRadius).toBe(8)+ })+})++describe('layer marks', () => {+ test('marks a layer that masks or shows an image, whose row shows that in place of its shape', () => {+ const graph = new SceneGraph()+ const pageId = graph.getPages()[0].id+ const image = { ...colorToFill('#000000'), type: 'IMAGE' as const, imageHash: 'hash' }+ const rect = graph.createNode('RECTANGLE', pageId, { fills: [image] })+ const hidden = graph.createNode('RECTANGLE', pageId, { fills: [{ ...image, visible: false }] })+ const mask = graph.createNode('ELLIPSE', pageId, { isMask: true })++ const model = buildLayerTreeModel(graph, pageId)+ expect(model.byId.get(rect.id)).toMatchObject({ image: true, mask: false })+ expect(model.byId.get(hidden.id)?.image).toBe(false)+ expect(model.byId.get(mask.id)?.mask).toBe(true)++ const row = model.byId.get(rect.id)+ if (!row) throw new Error('Expected the rectangle in the model')+ graph.updateNode(rect.id, { fills: [] })+ expect(patchLayerNode(reactive(row), rect)).toBe(true)+ expect(row.image).toBe(false)})})diff --git a/src/components/LayerTree/examples/States.vue b/src/components/LayerTree/examples/States.vueindex d12ba9189..f44abd30b 100644--- a/src/components/LayerTree/examples/States.vue+++ b/src/components/LayerTree/examples/States.vue@@ -1,6 +1,11 @@<script setup lang="ts">-import type { VectorNetwork } from '@open-pencil/scene-graph'-import type { LayerNode, LayerVectorIcon } from '@open-pencil/vue'+import {+ createDefaultNode,+ type NodeType,+ type SceneNode,+ type VectorNetwork+} from '@open-pencil/scene-graph'+import type { LayerNode, LayerOutline } from '@open-pencil/vue'import type { LayerIssueMark } from '@/app/editor/design-check/layers'import LayerTreeNodeRow from '@/components/LayerTree/LayerTreeNodeRow.vue'@@ -71,9 +76,12 @@ const curveNetwork: VectorNetwork = {segments: [{ start: 0, end: 1, tangentStart: { x: 0, y: -100 }, tangentEnd: { x: 0, y: -100 } }],regions: []}-const placed = { rotation: 0, flipX: false, flipY: false }-const triangle: LayerVectorIcon = { network: triangleNetwork, width: 100, height: 100, ...placed }-const curve: LayerVectorIcon = { network: curveNetwork, width: 100, height: 75, ...placed }+/** A shape layer's outline, which its row draws as its icon. */+function outline(type: NodeType, overrides: Partial<SceneNode> = {}): LayerOutline {+ return createDefaultNode(() => type, type, { width: 100, height: 100, ...overrides })+}+const triangle = outline('VECTOR', { vectorNetwork: triangleNetwork })+const curve = outline('VECTOR', { vectorNetwork: curveNetwork, height: 75 })function chrome(overrides: Partial<LayerTreeChrome> = {}): LayerTreeChrome {return {@@ -150,25 +158,66 @@ const states: Array<{},{label: 'Vector',- node: node('Vector', { type: 'VECTOR', vector: triangle }),+ node: node('Vector', { type: 'VECTOR', outline: triangle }),selected: false,chrome: chrome()},{label: 'Selected vector',- node: node('Selected vector', { type: 'VECTOR', vector: curve }),+ node: node('Selected vector', { type: 'VECTOR', outline: curve }),selected: true,chrome: chrome({ focused: true })},{label: 'Hidden vector',- node: node('Hidden vector', { type: 'VECTOR', vector: triangle, visible: false }),+ node: node('Hidden vector', { type: 'VECTOR', outline: triangle, visible: false }),selected: false,chrome: chrome()},{label: 'Turned vector',- node: node('Turned vector', { type: 'VECTOR', vector: { ...triangle, rotation: -45 } }),+ node: node('Turned vector', { type: 'VECTOR', outline: { ...triangle, rotation: -45 } }),+ selected: false,+ chrome: chrome()+ },+ {+ label: 'Rounded rectangle',+ node: node('Rounded rectangle', {+ outline: outline('RECTANGLE', { width: 200, height: 100, cornerRadius: 24 })+ }),+ selected: false,+ chrome: chrome()+ },+ {+ label: 'Ellipse',+ node: node('Ellipse', { type: 'ELLIPSE', outline: outline('ELLIPSE', { height: 60 }) }),+ selected: false,+ chrome: chrome()+ },+ {+ label: 'Star',+ node: node('Star', { type: 'STAR', outline: outline('STAR', { pointCount: 5 }) }),+ selected: false,+ chrome: chrome()+ },+ {+ label: 'Image',+ node: node('Image', { outline: outline('RECTANGLE'), image: true }),+ selected: false,+ chrome: chrome()+ },+ {+ label: 'Mask',+ node: node('Mask', { type: 'ELLIPSE', outline: outline('ELLIPSE'), mask: true }),+ selected: false,+ chrome: chrome()+ },+ {+ label: 'Turned line',+ node: node('Turned line', {+ type: 'LINE',+ outline: outline('LINE', { height: 0, rotation: -30 })+ }),selected: false,chrome: chrome()},diff --git a/src/components/icons/index.ts b/src/components/icons/index.tsindex 6fbea1921..9215a6702 100644--- a/src/components/icons/index.ts+++ b/src/components/icons/index.ts@@ -7,6 +7,7 @@ import IconFrame from '~icons/lucide/frame'import IconGrid from '~icons/lucide/grid-3x3'import IconGroup from '~icons/lucide/group'import IconHand from '~icons/lucide/hand'+import IconImage from '~icons/lucide/image'import IconSection from '~icons/lucide/layout-grid'import IconMessageCircle from '~icons/lucide/message-circle'import IconMinus from '~icons/lucide/minus'@@ -19,6 +20,7 @@ import IconSmile from '~icons/lucide/smile'import IconSpline from '~icons/lucide/spline'import IconSquare from '~icons/lucide/square'import IconSlot from '~icons/lucide/square-dashed'+import IconMask from '~icons/lucide/squares-intersect'import IconStar from '~icons/lucide/star'import IconStickyNote from '~icons/lucide/sticky-note'import IconTriangle from '~icons/lucide/triangle'@@ -26,10 +28,10 @@ import IconType from '~icons/lucide/type'import { readIcon, slotPropertyId, type SceneNode } from '@open-pencil/scene-graph'import type { ShapeWithTextType } from '@open-pencil/scene-graph/shape-with-text'-import type { LayerVectorIcon, Tool } from '@open-pencil/vue'+import type { LayerOutline, Tool } from '@open-pencil/vue'+import { outlineIcon } from './outlines'import { SHAPE_KIND_ICONS } from './shapes'-import { vectorIcon } from './vectors'export const toolIcons: Record<Tool, Component> = {SELECT: IconMousePointer,@@ -78,7 +80,8 @@ export { IconFrame, IconSquare }/*** The glyph for a layer: its kind, or a slot or icon frame. A component keeps its own glyph, a- * shape with text shows its outline, and a layer row's vector shows its own shape.+ * shape with text shows its kind, a layer that masks shows the mask glyph, and a layer row's shape+ * or vector shows its own outline, or the image glyph when it shows an image, as in Figma.*/export function nodeIcon(node: {type: string@@ -86,14 +89,19 @@ export function nodeIcon(node: {slot?: booleanicon?: booleanshapeWithTextType?: ShapeWithTextType- vector?: LayerVectorIcon+ outline?: LayerOutline+ image?: boolean+ mask?: boolean}) {if (node.slot) return IconSlot+ // Figma marks any masking layer, frames and text too, but marks images on shapes only.+ if (node.mask) return IconMaskif (node.type === 'SHAPE_WITH_TEXT' && node.shapeWithTextType) {return SHAPE_KIND_ICONS[node.shapeWithTextType]}- if (node.vector) {- const icon = vectorIcon(node.vector)+ if (node.outline) {+ if (node.image) return IconImage+ const icon = outlineIcon(node.outline)if (icon) return icon}if (node.icon && node.type === 'FRAME') return IconSmilediff --git a/src/components/icons/outlines.ts b/src/components/icons/outlines.tsnew file mode 100644index 000000000..0fa1f8560--- /dev/null+++ b/src/components/icons/outlines.ts@@ -0,0 +1,79 @@+import { toRaw, type FunctionalComponent } from 'vue'++import { nodeOutlinePath } from '@open-pencil/core/io'+import { validateVectorNetwork } from '@open-pencil/scene-graph'+import { getNodeLocalMatrix } from '@open-pencil/scene-graph/coordinate'+import Matrix from '@open-pencil/scene-graph/matrix'+import type { LayerOutline } from '@open-pencil/vue'++import { maskIcon } from './mask'++/** The layer row's icon slot (`size-3` in the layer tree theme), so the outline draws at 1:1. */+const SLOT = 12+/** Figma draws a layer's row outline 9 px across, inside a 10 px square, stroked 1 px. */+const SHAPE = 9+const STROKE = 1+/** Figma shows its generic vector glyph once vertices and segments together reach this many. */+const MAX_VECTOR_ELEMENTS = 129++const round = (value: number) => Math.round(value * 10_000) / 10_000++/** A vector Figma draws as its outline: something to draw, not too much, and no broken indices. */+function drawsVector(outline: LayerOutline): boolean {+ const network = outline.vectorNetwork+ if (!network || network.segments.length === 0) return false+ if (network.vertices.length + network.segments.length >= MAX_VECTOR_ELEMENTS) return false+ return validateVectorNetwork(network).length === 0+}++/**+ * A shape layer's outline as icon markup, as Figma draws its layer row+ * (`generateObjectsPanelIcon`): turned and reflected as the layer is, with the layer's box+ * fitted to the icon and centred, and never filled. Null when Figma keeps the generic glyph.+ */+export function outlineIconSVG(outline: LayerOutline): string | null {+ if (outline.type === 'VECTOR' && !drawsVector(outline)) return null+ const path = nodeOutlinePath(outline)+ if (!path) return null++ // Figma fits the layer's turned box, not the outline, so a turned shape keeps its size.+ const { width, height } = outline+ const placement = getNodeLocalMatrix({ ...outline, x: 0, y: 0 })+ const corners = Matrix.mapPoints(placement, [0, 0, width, 0, width, height, 0, height])+ const xs = corners.filter((_, index) => index % 2 === 0)+ const ys = corners.filter((_, index) => index % 2 === 1)+ const minX = Math.min(...xs)+ const minY = Math.min(...ys)+ const boxWidth = Math.max(...xs) - minX+ const boxHeight = Math.max(...ys) - minY+ const extent = Math.max(boxWidth, boxHeight)+ if (!(extent > 0)) return null++ const scale = SHAPE / extent+ const [a, c, e, b, d, f] = Matrix.multiply(+ Matrix.translated(+ (SLOT - boxWidth * scale) / 2 - minX * scale,+ (SLOT - boxHeight * scale) / 2 - minY * scale+ ),+ Matrix.scaled(scale, scale),+ placement+ ).map(round)+ // The path stays in the layer's box, so arcs and rounded corners need no re-deriving; the+ // stroke keeps its width however far the box is scaled down.+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${SLOT} ${SLOT}"><path d="${path}" transform="matrix(${a} ${b} ${c} ${d} ${e} ${f})" fill="none" stroke="black" stroke-width="${STROKE}" vector-effect="non-scaling-stroke"/></svg>`+}++/** Each outline's icon, built once: the row replaces its outline when the layer changes. */+const icons = new WeakMap<LayerOutline, FunctionalComponent | null>()++/** A shape layer's own outline as an icon component. */+export function outlineIcon(outline: LayerOutline): FunctionalComponent | null {+ const raw = toRaw(outline)+ let icon = icons.get(raw)+ if (icon === undefined) {+ const svg = outlineIconSVG(raw)+ icon = svg ? maskIcon(svg) : null+ icons.set(raw, icon)+ }+ return icon+}diff --git a/src/components/icons/vectors.ts b/src/components/icons/vectors.tsdeleted file mode 100644index a8a6d8ea6..000000000--- a/src/components/icons/vectors.ts+++ /dev/null@@ -1,74 +0,0 @@-import { toRaw, type FunctionalComponent } from 'vue'--import { vectorNetworkToSVGPaths } from '@open-pencil/core/io'-import {- transformVectorNetwork,- validateVectorNetwork,- type VectorNetwork-} from '@open-pencil/scene-graph'-import { getNodeLocalMatrix } from '@open-pencil/scene-graph/coordinate'-import Matrix from '@open-pencil/scene-graph/matrix'-import type { LayerVectorIcon } from '@open-pencil/vue'--import { maskIcon } from './mask'--/** The layer row's icon slot (`size-3` in the layer tree theme), so the outline draws at 1:1. */-const SLOT = 12-/** Figma draws a vector's row icon 9 px across, inside a 10 px square, stroked 1 px. */-const SHAPE = 9-const STROKE = 1-/** Figma shows its generic vector glyph once vertices and segments together reach this many. */-const MAX_ELEMENTS = 129--/**- * A vector's outline as icon markup, as Figma draws its layer row (`generateObjectsPanelIcon`):- * turned and reflected as the layer is, with the layer's box fitted to the icon and centred, and- * never filled. Null for a network with nothing to draw, too much to draw, or broken indices.- */-export function vectorIconSVG(vector: LayerVectorIcon): string | null {- const { network, width, height } = vector- const { vertices, segments } = network- if (segments.length === 0 || vertices.length + segments.length >= MAX_ELEMENTS) return null- // A network whose segments or region loops name missing parts keeps the generic glyph.- if (validateVectorNetwork(network).length > 0) return null-- // Figma fits the layer's turned box, not the outline, so a turned shape keeps its size.- const placement = getNodeLocalMatrix({ ...vector, type: 'VECTOR', x: 0, y: 0 })- const corners = Matrix.mapPoints(placement, [0, 0, width, 0, width, height, 0, height])- const xs = corners.filter((_, index) => index % 2 === 0)- const ys = corners.filter((_, index) => index % 2 === 1)- const minX = Math.min(...xs)- const minY = Math.min(...ys)- const boxWidth = Math.max(...xs) - minX- const boxHeight = Math.max(...ys) - minY- const extent = Math.max(boxWidth, boxHeight)- if (!(extent > 0)) return null-- const scale = SHAPE / extent- const fit = Matrix.multiply(- Matrix.translated(- (SLOT - boxWidth * scale) / 2 - minX * scale,- (SLOT - boxHeight * scale) / 2 - minY * scale- ),- Matrix.scaled(scale, scale),- placement- )- const d = vectorNetworkToSVGPaths(transformVectorNetwork(fit, network)).join('')- return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${SLOT} ${SLOT}"><path d="${d}" fill="none" stroke="black" stroke-width="${STROKE}"/></svg>`-}--/** Each network's latest icon only, so a rotate or resize drag does not keep every frame's. */-const icons = new WeakMap<VectorNetwork, { key: string; icon: FunctionalComponent | null }>()--/** A vector's own outline as an icon component, built once per network and placement. */-export function vectorIcon(vector: LayerVectorIcon): FunctionalComponent | null {- const network = toRaw(vector.network)- const { width, height, rotation, flipX, flipY } = vector- const key = `${width} ${height} ${rotation} ${flipX} ${flipY}`- const cached = icons.get(network)- if (cached?.key === key) return cached.icon- const svg = vectorIconSVG({ ...vector, network })- const icon = svg ? maskIcon(svg) : null- icons.set(network, { key, icon })- return icon-}