AI-native design editor. Open-source Figma alternative.
feat(canvas): round polygons and stars and edit their points as Figma does (#1048)
Danila Poyarkov46c808035d0e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5f01ba6be..0c1fe6d59 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -41,13 +41,14 @@- `buildDerivedTextDataV4` is removed from `@open-pencil/core`, and `sceneNodeToKiwi` no longer writes glyph outlines by itself: pass the `runtime` that `withFigExportRuntime(graph, canvasKit, write)` hands its callback. In `@open-pencil/fig/node-change`, `FigNodeChangeExportRuntime` takes `shapeText(node)` instead of `getGlyphOutlineMetrics`, `buildDerivedTextData` takes the `baselines` it writes, and `convertFigmaDerivedTextGlyphs` takes the text's characters.- The `updates` messages from `@open-pencil/vue` no longer include `availableTitle`, `installPrompt`, `installedTitle`, and `downloading`, which only the system update dialogs and download toast used; `installed` now takes only `{ version }`, and `install` reads "Install Update". The Software Update window uses the new `windowTitle`, `currentVersion`, `whatsNew`, `installAndRestart`, `restartNow`, and related messages.- `fetchIcon`, `fetchIcons`, `searchIcons`, `searchIconsBatch`, and `clearIconCache` are removed from `@open-pencil/core`. Icons come from an `IconProvider` instead: `iconify` is the default Iconify provider, `createIconifyProvider()` makes one with its own cache, and `placeIcon` places an icon that keeps its name. A custom provider also implements `previews()`, `collections()`, and `browse()`, which give pickers each icon's SVG markup, the sets, and a set's icons.-- The editor's view state has a required `cornerRadiusHover`, the selected rectangle whose corner radius handles the canvas shows; code that creates editor state itself must set it, as `createDefaultEditorViewState` does.+- The editor's view state has a required `shapeHandleHover`, the selected shape whose radius, point count, and ratio handles the canvas shows; code that creates editor state itself must set it, as `createDefaultEditorViewState` does.- `defineTool` from `@open-pencil/core/tools` takes its `input` as a `v.strictObject` instead of a `v.object`, and `ToolDef.input` is a strict object schema, so a tool rejects arguments it does not declare.- `RulerTheme` from `@open-pencil/core/canvas` no longer has `label`: ruler badges and size pills draw their text in the `foreground` of the editor state's new `selectionTheme`, which also sets the canvas selection color and defaults to the previous blue with white text.### Added-- Round a rectangle's corners on the canvas, as in Figma: while the pointer is over a selected rectangle at least 108 screen pixels across, a handle sits inside each corner. Dragging one sets every corner while they are equal and only that corner while they differ, <kbd>⌥</kbd> swaps the two, and <kbd>⇧</kbd> rounds to tens; a label beside the pointer shows the radius.+- Edit a polygon's or star's corner radius, point count, and a star's inner ratio in the properties panel, as in Figma: **Count** from 3 to 60 and **Ratio** as a percentage.+- Round a rectangle's, polygon's, or star's corners on the canvas, as in Figma: while the pointer is over a selected shape at least 108 screen pixels across, a handle sits inside each corner of a rectangle and below the top point of a polygon or star, and handles on a polygon's or star's next point and a star's first inner point set its point count and inner ratio. Dragging a rectangle's handle sets every corner while they are equal and only that corner while they differ, <kbd>⌥</kbd> swaps the two, and <kbd>⇧</kbd> rounds to tens; a label beside the pointer shows the radius.- Edit several layers at once as in Figma: the properties panel gives a multi-selection a Layout section with sizes, text resizing, flow, clip content, and a Spacing field that spaces a row or column evenly; Typography for the text among it; corner radius for the layers that have one; the stroke of the layers that have strokes; and Selection colors, which lists every fill and stroke colour in the selection and its children and recolours one everywhere it is used. The panel's header reads "N selected".- Edit gradients on the canvas, as in Figma: while a fill or stroke gradient's picker is open, the layer shows the gradient's line or ellipse with its end dots and stop squares. Dragging a dot moves it, <kbd>Shift</kbd> turns it in 15° steps, and dragging a square slides its stop; the stop selected on the canvas is the one selected in the picker.- Paste SVG markup copied as text, such as from a code editor or Figma's Copy as SVG, as layers.@@ -157,6 +158,7 @@### Fixed+- Polygons and stars draw and export to SVG with their corner radius and smoothing as Figma rounds them, inner star corners included, and copy to and from Figma with their point count and a star's inner ratio; they were drawn with sharp corners, also from `.fig` files, and pasted into Figma as empty shapes.- The font picker opens at the current font instead of the top of the list.- Cmd+Z and Shift+Cmd+Z undo and redo while a fill, stroke, or colour picker is open, as in Figma, and undo reverts the picker's latest change rather than the edit before it.- A frame's name reads on the section it sits in: on a dark page, frames in a white section had white names on white. Names now fade more on light backgrounds than on dark ones, as Figma's do.diff --git a/packages/core/src/canvas/overlays/corner-radius.ts b/packages/core/src/canvas/overlays/shape-handles.tssimilarity index 71%rename from packages/core/src/canvas/overlays/corner-radius.tsrename to packages/core/src/canvas/overlays/shape-handles.tsindex 6132bc55f..31b0de124 100644--- a/packages/core/src/canvas/overlays/corner-radius.ts+++ b/packages/core/src/canvas/overlays/shape-handles.ts@@ -10,32 +10,33 @@ import {SIZE_PILL_PADDING_X,SIZE_PILL_RADIUS} from '#core/constants'-import type { CornerRadiusHover } from '#core/editor/types'+import type { ShapeHandleHover } from '#core/editor/types'import {- CORNER_RADIUS_HANDLE,- cornerRadiusHandleLayout,- cornerRadii,+ SHAPE_HANDLE,+ shapeHandleLayout,+ shapeHandleValue,createSceneGeometry,type RotationPreview} from '#core/geometry'/**- * The selected rectangle's corner radius handles while the pointer is over it: white circles the- * size of the resize handles with a border in the selection colour, dotted when a drag changes one- * corner, and a "Radius" label by the pointer for the handle in use, as in Figma desktop.+ * The selected rectangle's, polygon's, or star's handles while the pointer is over it: white+ * circles the size of the resize handles with a border in the selection colour, dotted when a drag+ * changes one corner, and a label such as "Radius 12" by the pointer for the handle in use, as in+ * Figma desktop.*/-export function drawCornerRadiusHandles(+export function drawShapeHandles(r: SkiaRenderer,canvas: Canvas,graph: SceneGraph,selectedIds: ReadonlySet<string>,- hover: CornerRadiusHover | null | undefined,+ hover: ShapeHandleHover | null | undefined,preview?: RotationPreview | null): void {if (!hover || selectedIds.size !== 1 || !selectedIds.has(hover.nodeId)) returnconst node = graph.getNode(hover.nodeId)if (!node) return- const handles = cornerRadiusHandleLayout(node, createSceneGeometry(graph, preview), r)+ const handles = shapeHandleLayout(node, createSceneGeometry(graph, preview), r)if (!handles) returnconst color = r.outlineColor(node, graph)const fill = r.auxFill@@ -50,13 +51,13 @@ export function drawCornerRadiusHandles(canvas.drawCircle(point.x, point.y, HANDLE_HALF_SIZE, border)if (!hover.single) continuefill.setColor(color)- canvas.drawCircle(point.x, point.y, CORNER_RADIUS_HANDLE.dotRadius, fill)+ canvas.drawCircle(point.x, point.y, SHAPE_HANDLE.dotRadius, fill)}const provider = r.fontProvider- if (!hover.corner || !provider) return+ if (!hover.handle || !provider) return// A paragraph rather than the size label's single font, so every script has a fallback face.- const text = `${hover.label} ${Math.round(cornerRadii(node)[hover.corner])}`+ const text = `${hover.label} ${shapeHandleValue(node, hover.handle)}`const white = r.ck.WHITEconst measured = r.labelParagraphCache.measure(r.ck,@@ -67,7 +68,7 @@ export function drawCornerRadiusHandles(white,r.fontGeneration)- const { labelOffset } = CORNER_RADIUS_HANDLE+ const { labelOffset } = SHAPE_HANDLEconst left = hover.pointer.x + labelOffset.xconst top = hover.pointer.y + labelOffset.y - SIZE_PILL_HEIGHT / 2fill.setColor(color)diff --git a/packages/core/src/canvas/renderer/overlay-pass.ts b/packages/core/src/canvas/renderer/overlay-pass.tsindex d9d52e8a6..ebbc7e5f3 100644--- a/packages/core/src/canvas/renderer/overlay-pass.ts+++ b/packages/core/src/canvas/renderer/overlay-pass.ts@@ -6,13 +6,13 @@ import { drawGuides } from '#core/canvas/guides/draw'import { drawIssueHighlight, drawIssueMarkers } from '#core/canvas/issues/draw'import { layoutIssueMarkers } from '#core/canvas/issues/layout'import { drawComponentSetBorders } from '#core/canvas/overlays/component-sets'-import { drawCornerRadiusHandles } from '#core/canvas/overlays/corner-radius'import { drawDropTarget, drawEditingText } from '#core/canvas/overlays/feedback'import { drawGradientHandles } from '#core/canvas/overlays/gradient-handles'import { drawLayoutOutlines } from '#core/canvas/overlays/layout-outlines'import { drawMeasurementSegment } from '#core/canvas/overlays/measurement'import { drawPixelGrid } from '#core/canvas/overlays/pixel-grid'import { drawCodeFocus } from '#core/canvas/overlays/selection'+import { drawShapeHandles } from '#core/canvas/overlays/shape-handles'import { drawSlotOutlines } from '#core/canvas/overlays/slots'import type { RenderOverlays, SkiaRenderer } from '#core/canvas/renderer'import { RULER_SIZE } from '#core/constants'@@ -122,12 +122,12 @@ export function drawOverlayPass(else {r.drawSelection(canvas, graph, selectedIds, overlays)if (!overlays.transforming)- drawCornerRadiusHandles(+ drawShapeHandles(r,canvas,graph,selectedIds,- overlays.cornerRadiusHover,+ overlays.shapeHandleHover,overlays.rotationPreview)}diff --git a/packages/core/src/canvas/renderer/pipeline.ts b/packages/core/src/canvas/renderer/pipeline.tsindex daa43715e..31c16b64a 100644--- a/packages/core/src/canvas/renderer/pipeline.ts+++ b/packages/core/src/canvas/renderer/pipeline.ts@@ -111,7 +111,7 @@ export function renderFromEditorState(designIssues: state.designIssues,codeFocusNodeId: state.codeFocusNodeId,autoLayoutHover: state.autoLayoutHover,- cornerRadiusHover: state.cornerRadiusHover+ shapeHandleHover: state.shapeHandleHover},// Recorded pictures follow what the canvas draws, not every document change.state.canvasVersion,diff --git a/packages/core/src/canvas/renderer/types.ts b/packages/core/src/canvas/renderer/types.tsindex 245609242..48c7d9565 100644--- a/packages/core/src/canvas/renderer/types.ts+++ b/packages/core/src/canvas/renderer/types.ts@@ -4,7 +4,7 @@ import type { SnapGuide } from '@open-pencil/scene-graph/snap'import type { GuideOverlayState } from '#core/canvas/guides/types'import type { DesignIssueOverlay } from '#core/canvas/issues/types'-import type { CornerRadiusHover, GradientEdit } from '#core/editor/types'+import type { ShapeHandleHover, GradientEdit } from '#core/editor/types'import type { RotationPreview } from '#core/geometry'import type { TextEditor } from '#core/text/editor'@@ -70,8 +70,8 @@ export interface RenderOverlays {index?: numberside?: 'top' | 'right' | 'bottom' | 'left'} | null- /** The selected rectangle's corner radius handles and the label of the one in use. */- cornerRadiusHover?: CornerRadiusHover | null+ /** The selected shape's handles and the label of the one in use. */+ shapeHandleHover?: ShapeHandleHover | nullpenState?: {vertices: Vector[]segments: Array<{diff --git a/packages/core/src/canvas/shapes.ts b/packages/core/src/canvas/shapes.tsindex c5987a38c..a9d8ef593 100644--- a/packages/core/src/canvas/shapes.ts+++ b/packages/core/src/canvas/shapes.ts@@ -1,7 +1,7 @@import type { Canvas, Path, PathBuilder } from 'canvaskit-wasm'import type { SceneNode } from '@open-pencil/scene-graph'-import { polygonVertices } from '@open-pencil/scene-graph/geometry'+import { polygonOutline } from '@open-pencil/scene-graph/polygon'import { vectorNetworkToPath, geometryBlobToPath } from '#core/vector'@@ -404,13 +404,16 @@ export function makeNodeShapePath(return path.detachAndDelete()}+/** The polygon or star with its corner radius and smoothing, as Figma draws it. */export function makePolygonPath(r: SkiaRenderer, node: SceneNode): Path {const path = new r.ck.PathBuilder()- polygonVertices(node).forEach((point, index) => {- if (index === 0) path.moveTo(point.x, point.y)- else path.lineTo(point.x, point.y)- })- path.close()+ for (const command of polygonOutline(node)) {+ if (command.type === 'M') path.moveTo(command.x, command.y)+ else if (command.type === 'L') path.lineTo(command.x, command.y)+ else if (command.type === 'C')+ path.cubicTo(command.x1, command.y1, command.x2, command.y2, command.x, command.y)+ else path.close()+ }return path.detachAndDelete()}diff --git a/packages/core/src/editor/index.ts b/packages/core/src/editor/index.tsindex 467b2eaa1..f7df0b556 100644--- a/packages/core/src/editor/index.ts+++ b/packages/core/src/editor/index.ts@@ -57,7 +57,7 @@ export type {EditorSharedState,EditorViewState,FigmaClipboardImageResolver,- CornerRadiusHover,+ ShapeHandleHover,GradientEdit,Tool} from './types'diff --git a/packages/core/src/editor/selection/overlays.ts b/packages/core/src/editor/selection/overlays.tsindex 39a70fbe9..0623aeb8f 100644--- a/packages/core/src/editor/selection/overlays.ts+++ b/packages/core/src/editor/selection/overlays.ts@@ -4,7 +4,7 @@ import type { Rect } from '@open-pencil/scene-graph/primitives'import type { SnapGuide } from '@open-pencil/scene-graph/snap'import type { GuidePreview } from '#core/canvas/guides/types'-import type { CornerRadiusHover, EditorContext } from '#core/editor/types'+import type { ShapeHandleHover, EditorContext } from '#core/editor/types'export function createSelectionOverlayActions(ctx: EditorContext) {function setMarquee(rect: Rect | null) {@@ -98,9 +98,9 @@ export function createSelectionOverlayActions(ctx: EditorContext) {ctx.requestRepaint()}- function setCornerRadiusHover(hover: CornerRadiusHover | null) {- if (isEqual(ctx.state.cornerRadiusHover, hover)) return- ctx.state.cornerRadiusHover = hover+ function setShapeHandleHover(hover: ShapeHandleHover | null) {+ if (isEqual(ctx.state.shapeHandleHover, hover)) return+ ctx.state.shapeHandleHover = hoverctx.requestRepaint()}@@ -119,6 +119,6 @@ export function createSelectionOverlayActions(ctx: EditorContext) {setDropTarget,setLayoutInsertIndicator,setAutoLayoutHover,- setCornerRadiusHover+ setShapeHandleHover}}diff --git a/packages/core/src/editor/state/view.ts b/packages/core/src/editor/state/view.tsindex 12b1b65c7..dc61aea95 100644--- a/packages/core/src/editor/state/view.ts+++ b/packages/core/src/editor/state/view.ts@@ -20,7 +20,7 @@ export function createDefaultEditorViewState(pageId: string): EditorViewState {penCursorX: null,penCursorY: null,autoLayoutHover: null,- cornerRadiusHover: null,+ shapeHandleHover: null,panX: 0,pageColor: { ...CANVAS_BG_COLOR },panY: 0,@@ -46,7 +46,7 @@ export function copyEditorViewState(source: EditorViewState): EditorViewState {layoutInsertIndicator: structuredClone(source.layoutInsertIndicator),penState: structuredClone(source.penState),autoLayoutHover: structuredClone(source.autoLayoutHover),- cornerRadiusHover: structuredClone(source.cornerRadiusHover),+ shapeHandleHover: structuredClone(source.shapeHandleHover),pageColor: { ...source.pageColor },navigation: { ...source.navigation },nodeEditState: structuredClone(source.nodeEditState)diff --git a/packages/core/src/editor/types.ts b/packages/core/src/editor/types.tsindex 38c3cee5e..b92017193 100644--- a/packages/core/src/editor/types.ts+++ b/packages/core/src/editor/types.ts@@ -25,7 +25,7 @@ import type {import type { InterfaceTheme } from '#core/constants'import type { PlayState } from '#core/editor/play/actions'import type { SnappingPreferences } from '#core/editor/preferences'-import type { RadiusCorner, RotationPreview } from '#core/geometry'+import type { RotationPreview, ShapeHandleKind } from '#core/geometry'import type { IconProvider } from '#core/icons/provider'import type { TextEditor } from '#core/text/editor'import type { FontResolutionEvent, FontResolutionSnapshot } from '#core/text/resolver'@@ -52,14 +52,14 @@ export interface GradientEdit {stop: number}-/** The selected rectangle's corner radius handles, shown while the pointer is over it. */-export interface CornerRadiusHover {+/** The selected shape's radius, point count, and ratio handles, shown while the pointer is over it. */+export interface ShapeHandleHover {nodeId: string/** Whether a drag changes only the corner it holds; each handle then shows a dot. */single: boolean- /** The handle under the pointer or being dragged, whose radius the label shows. */- corner: RadiusCorner | null- /** The word before the radius in the label, in the interface language. */+ /** The handle under the pointer or being dragged, whose value the label shows. */+ handle: ShapeHandleKind | null+ /** The handle's name in the label, in the interface language. */label: string/** The pointer in screen coordinates, which the label follows. */pointer: Vector@@ -132,7 +132,7 @@ export interface EditorViewState {index?: numberside?: 'top' | 'right' | 'bottom' | 'left'} | null- cornerRadiusHover: CornerRadiusHover | null+ shapeHandleHover: ShapeHandleHover | nullpanX: numberpageColor: ColorpanY: numberdiff --git a/packages/core/src/geometry/corner-radius.ts b/packages/core/src/geometry/corner-radius.tsdeleted file mode 100644index 45a223e81..000000000--- a/packages/core/src/geometry/corner-radius.ts+++ /dev/null@@ -1,163 +0,0 @@-import type { SceneNode, Vector } from '@open-pencil/scene-graph'--import type { SceneGeometry } from './scene'-import type { ViewportTransform } from './types'--/**- * On-canvas corner radius handles, as Figma desktop draws and drags them on a selected rectangle.- * Each handle sits at the centre of its corner's arc, kept a little inside small corners, and- * dragging one sets the radius whose arc centre is under the pointer.- */-export const CORNER_RADIUS_HANDLE = {- /** The shortest on-screen side, in pixels, at which a rectangle shows its handles. */- minShapeSize: 108,- /** The closest a handle comes to its corner along each edge, in screen pixels. */- minInset: 12.5,- /** The dot that marks a drag of one corner only. */- dotRadius: 1,- /** How far from its centre a handle, drawn the size of a resize handle, takes the pointer. */- hitRadius: 7,- /** Shift rounds radii to this step. */- snapStep: 10,- /** Where the radius label sits relative to the pointer: its left edge and vertical centre. */- labelOffset: { x: 10, y: -20 }-} as const--export type RadiusCorner = 'topLeft' | 'topRight' | 'bottomRight' | 'bottomLeft'--export const RADIUS_CORNERS: readonly RadiusCorner[] = [- 'topLeft',- 'topRight',- 'bottomRight',- 'bottomLeft'-]--/** The direction from each corner into the rectangle, along both edges. */-const INWARD: Record<RadiusCorner, Vector> = {- topLeft: { x: 1, y: 1 },- topRight: { x: -1, y: 1 },- bottomRight: { x: -1, y: -1 },- bottomLeft: { x: 1, y: -1 }-}--export interface CornerRadiusHandle {- corner: RadiusCorner- /** The handle's centre in screen coordinates. */- point: Vector-}--/** Figma shows radius handles on rectangles only; frames, ellipses, and vectors have none. */-export function hasCornerRadiusHandles(node: SceneNode): boolean {- return node.type === 'RECTANGLE'-}--export function cornerRadii(node: SceneNode): Record<RadiusCorner, number> {- if (!node.independentCorners) {- const radius = node.cornerRadius- return { topLeft: radius, topRight: radius, bottomRight: radius, bottomLeft: radius }- }- return {- topLeft: node.topLeftRadius,- topRight: node.topRightRadius,- bottomRight: node.bottomRightRadius,- bottomLeft: node.bottomLeftRadius- }-}--/**- * Whether a drag changes only the corner it holds. Corners that differ are dragged one at a time- * and equal ones all together; Alt reverses either, as in Figma.- */-export function dragsSingleCorner(node: SceneNode, altKey: boolean): boolean {- const radii = Object.values(cornerRadii(node))- return radii.some((radius) => radius !== radii[0]) !== altKey-}--function maxRadius(node: SceneNode): number {- return Math.min(node.width, node.height) / 2-}--function cornerPoint(node: SceneNode, corner: RadiusCorner): Vector {- return {- x: corner === 'topLeft' || corner === 'bottomLeft' ? 0 : node.width,- y: corner === 'topLeft' || corner === 'topRight' ? 0 : node.height- }-}--/** The rectangle's handles on screen, or null when it is too small on screen to show them. */-export function cornerRadiusHandleLayout(- node: SceneNode,- geometry: SceneGeometry,- viewport: ViewportTransform-): CornerRadiusHandle[] | null {- if (!hasCornerRadiusHandles(node)) return null- if (Math.min(node.width, node.height) * viewport.zoom < CORNER_RADIUS_HANDLE.minShapeSize)- return null- const radii = cornerRadii(node)- const minInset = CORNER_RADIUS_HANDLE.minInset / viewport.zoom- return RADIUS_CORNERS.map((corner) => {- const origin = cornerPoint(node, corner)- const inset = Math.max(Math.min(radii[corner], maxRadius(node)), minInset)- const local = {- x: origin.x + INWARD[corner].x * inset,- y: origin.y + INWARD[corner].y * inset- }- return { corner, point: geometry.toScreen(node, local, viewport) }- })-}--export function hitTestCornerRadiusHandles(- handles: readonly CornerRadiusHandle[],- screen: Vector-): RadiusCorner | null {- const hit = handles.find(- (handle) =>- Math.hypot(screen.x - handle.point.x, screen.y - handle.point.y) <=- CORNER_RADIUS_HANDLE.hitRadius- )- return hit?.corner ?? null-}--/**- * The radius whose arc centre lies under a node-local point: its distance from the corner along- * the diagonal, in whole pixels, or in steps of 10 with Shift.- */-export function cornerRadiusAtPoint(- node: SceneNode,- corner: RadiusCorner,- local: Vector,- snap: boolean-): number {- const origin = cornerPoint(node, corner)- const inward = INWARD[corner]- const distance = ((local.x - origin.x) * inward.x + (local.y - origin.y) * inward.y) / 2- const step = snap ? CORNER_RADIUS_HANDLE.snapStep : 1- return Math.min(Math.max(Math.round(distance / step) * step, 0), maxRadius(node))-}--/** The fields that set one corner, or all four, to a radius. */-export function cornerRadiusChanges(- node: SceneNode,- corner: RadiusCorner,- radius: number,- single: boolean-): Partial<SceneNode> {- if (!single) {- return {- cornerRadius: radius,- independentCorners: false,- topLeftRadius: radius,- topRightRadius: radius,- bottomRightRadius: radius,- bottomLeftRadius: radius- }- }- const radii = { ...cornerRadii(node), [corner]: radius }- return {- independentCorners: true,- topLeftRadius: radii.topLeft,- topRightRadius: radii.topRight,- bottomRightRadius: radii.bottomRight,- bottomLeftRadius: radii.bottomLeft- }-}diff --git a/packages/core/src/geometry/index.ts b/packages/core/src/geometry/index.tsindex a5fe34cab..fd2995175 100644--- a/packages/core/src/geometry/index.ts+++ b/packages/core/src/geometry/index.ts@@ -6,17 +6,21 @@ export {panelRotationChange} from './figma'export {- CORNER_RADIUS_HANDLE,- RADIUS_CORNERS,+ SHAPE_HANDLE,cornerRadiusAtPoint,cornerRadiusChanges,- cornerRadiusHandleLayout,+ shapeHandleLayout,cornerRadii,+ cornerRadiusOf,dragsSingleCorner,- hasCornerRadiusHandles,- hitTestCornerRadiusHandles-} from './corner-radius'-export type { CornerRadiusHandle, RadiusCorner } from './corner-radius'+ hasShapeHandles,+ isRadiusHandle,+ pointCountAtPoint,+ shapeHandleValue,+ starRatioAtPoint,+ hitTestShapeHandles+} from './shape-handles'+export type { RadiusCorner, ShapeHandle, ShapeHandleKind } from './shape-handles'export {GRADIENT_HANDLE,gradientHandleLayout,diff --git a/packages/core/src/geometry/shape-handles.ts b/packages/core/src/geometry/shape-handles.tsnew file mode 100644index 000000000..93ca68c43--- /dev/null+++ b/packages/core/src/geometry/shape-handles.ts@@ -0,0 +1,274 @@+import { clamp } from 'es-toolkit'++import type { SceneNode, Vector } from '@open-pencil/scene-graph'+import { POINT_COUNT_RANGE, polygonCorners } from '@open-pencil/scene-graph/polygon'++import type { SceneGeometry } from './scene'+import type { ViewportTransform } from './types'++/**+ * On-canvas shape handles, as Figma desktop draws and drags them on a selected rectangle, polygon,+ * or star. A radius handle sits at the centre of its corner's arc, kept a little inside small+ * corners, and dragging one sets the radius whose arc centre is under the pointer. A polygon's or+ * star's next outer point sets its point count, and a star's first inner point its inner ratio.+ */+export const SHAPE_HANDLE = {+ /** The shortest on-screen side, in pixels, at which a shape shows its handles. */+ minShapeSize: 108,+ /** The closest a handle comes to its corner along each edge, in screen pixels. */+ minInset: 12.5,+ /** The dot that marks a drag of one corner only. */+ dotRadius: 1,+ /** How far from its centre a handle, drawn the size of a resize handle, takes the pointer. */+ hitRadius: 7,+ /** Shift rounds radii to this step. */+ snapStep: 10,+ /** Where a handle's label sits relative to the pointer: its left edge and vertical centre. */+ labelOffset: { x: 10, y: -20 }+} as const++/** A rectangle's four corners, or the top point of a polygon or star. */+export type RadiusCorner = 'topLeft' | 'topRight' | 'bottomRight' | 'bottomLeft' | 'point'++const RECTANGLE_CORNERS = ['topLeft', 'topRight', 'bottomRight', 'bottomLeft'] as const++type RectangleCorner = (typeof RECTANGLE_CORNERS)[number]++/** A radius handle, or a polygon's or star's point count or a star's inner ratio. */+export type ShapeHandleKind = RadiusCorner | 'count' | 'ratio'++export interface ShapeHandle {+ handle: ShapeHandleKind+ /** The handle's centre in screen coordinates. */+ point: Vector+}++/** A corner as its handle sees it, in the layer's own pixels. */+interface RadiusCornerShape {+ corner: RadiusCorner+ vertex: Vector+ /** The unit direction from the vertex along the corner's bisector, into the shape. */+ inward: Vector+ /** cos(α/2) for a corner turning by α: the arc's centre is radius / factor from the vertex. */+ factor: number+ /** The radius the corner is drawn with. */+ radius: number+ /** The largest radius the corner can be drawn with. */+ max: number+}++/**+ * Figma shows radius handles on rectangles, polygons, and stars; a polygon or star has one, at its+ * top point, since its corners share one radius. Frames, ellipses, and vectors have none.+ */+export function hasShapeHandles(node: SceneNode): boolean {+ return node.type === 'RECTANGLE' || node.type === 'POLYGON' || node.type === 'STAR'+}++export function cornerRadii(node: SceneNode): Record<RectangleCorner, number> {+ if (!node.independentCorners) {+ const radius = node.cornerRadius+ return { topLeft: radius, topRight: radius, bottomRight: radius, bottomLeft: radius }+ }+ return {+ topLeft: node.topLeftRadius,+ topRight: node.topRightRadius,+ bottomRight: node.bottomRightRadius,+ bottomLeft: node.bottomLeftRadius+ }+}++/** The radius a handle's label shows. */+export function cornerRadiusOf(node: SceneNode, corner: RadiusCorner): number {+ return corner === 'point' ? node.cornerRadius : cornerRadii(node)[corner]+}++/**+ * Whether a drag changes only the corner it holds. Corners that differ are dragged one at a time+ * and equal ones all together; Alt reverses either, as in Figma. A polygon's corners always move+ * together.+ */+export function dragsSingleCorner(node: SceneNode, altKey: boolean): boolean {+ if (node.type !== 'RECTANGLE') return false+ const radii = Object.values(cornerRadii(node))+ return radii.some((radius) => radius !== radii[0]) !== altKey+}++const HALF_DIAGONAL = Math.SQRT1_2++function rectangleCorners(node: SceneNode): RadiusCornerShape[] {+ const max = Math.min(node.width, node.height) / 2+ const radii = cornerRadii(node)+ return RECTANGLE_CORNERS.map((corner) => {+ const left = corner === 'topLeft' || corner === 'bottomLeft'+ const top = corner === 'topLeft' || corner === 'topRight'+ return {+ corner,+ vertex: { x: left ? 0 : node.width, y: top ? 0 : node.height },+ inward: { x: (left ? 1 : -1) * HALF_DIAGONAL, y: (top ? 1 : -1) * HALF_DIAGONAL },+ factor: HALF_DIAGONAL,+ radius: Math.min(radii[corner], max),+ max+ }+ })+}++function polygonPoint(node: SceneNode): RadiusCornerShape[] {+ const [top] = polygonCorners(node)+ const [widest] = polygonCorners({ ...node, cornerRadius: Number.POSITIVE_INFINITY })+ const bisector = { x: top.outgoing.x - top.incoming.x, y: top.outgoing.y - top.incoming.y }+ const length = Math.hypot(bisector.x, bisector.y)+ return [+ {+ corner: 'point',+ vertex: top.vertex,+ inward: { x: bisector.x / length, y: bisector.y / length },+ factor: Math.cos(top.turn / 2),+ radius: top.radius,+ max: widest.radius+ }+ ]+}++function radiusCorners(node: SceneNode): RadiusCornerShape[] {+ return node.type === 'RECTANGLE' ? rectangleCorners(node) : polygonPoint(node)+}++/**+ * Where a polygon's count handle and a star's ratio handle sit: on the next outer point and the+ * first inner point, or at the middle of their rounding.+ */+function pointHandles(node: SceneNode): Array<{ handle: 'count' | 'ratio'; local: Vector }> {+ if (node.type !== 'POLYGON' && node.type !== 'STAR') return []+ const corners = polygonCorners(node)+ const onOutline = (index: number) => {+ const { vertex, incoming, outgoing, turn, radius } = corners[index]+ const bisector = { x: outgoing.x - incoming.x, y: outgoing.y - incoming.y }+ const length = Math.hypot(bisector.x, bisector.y)+ const inset = length > 0 ? radius / Math.cos(turn / 2) - radius : 0+ return {+ x: vertex.x + (length > 0 ? (bisector.x / length) * inset : 0),+ y: vertex.y + (length > 0 ? (bisector.y / length) * inset : 0)+ }+ }+ if (node.type === 'POLYGON') return [{ handle: 'count', local: onOutline(1) }]+ return [+ { handle: 'ratio', local: onOutline(1) },+ { handle: 'count', local: onOutline(2) }+ ]+}++/** The shape's handles on screen, or null when it is too small on screen to show them. */+export function shapeHandleLayout(+ node: SceneNode,+ geometry: SceneGeometry,+ viewport: ViewportTransform+): ShapeHandle[] | null {+ if (!hasShapeHandles(node)) return null+ if (Math.min(node.width, node.height) * viewport.zoom < SHAPE_HANDLE.minShapeSize) return null+ const minDistance = SHAPE_HANDLE.minInset / HALF_DIAGONAL / viewport.zoom+ const radii = radiusCorners(node).map(({ corner, vertex, inward, factor, radius }) => {+ const distance = Math.max(radius / factor, minDistance)+ const local = { x: vertex.x + inward.x * distance, y: vertex.y + inward.y * distance }+ return { handle: corner, point: geometry.toScreen(node, local, viewport) }+ })+ const points = pointHandles(node).map(({ handle, local }) => ({+ handle,+ point: geometry.toScreen(node, local, viewport)+ }))+ return [...radii, ...points]+}++export function hitTestShapeHandles(+ handles: readonly ShapeHandle[],+ screen: Vector+): ShapeHandleKind | null {+ const hit = handles.find(+ (handle) =>+ Math.hypot(screen.x - handle.point.x, screen.y - handle.point.y) <= SHAPE_HANDLE.hitRadius+ )+ return hit?.handle ?? null+}++export function isRadiusHandle(handle: ShapeHandleKind): handle is RadiusCorner {+ return handle !== 'count' && handle !== 'ratio'+}++/** What a handle's label shows after its name: the radius, the point count, or the ratio. */+export function shapeHandleValue(node: SceneNode, handle: ShapeHandleKind): string {+ if (handle === 'count') return String(node.pointCount)+ if (handle === 'ratio') return `${Math.round(node.starInnerRadius * 100)}%`+ return String(Math.round(cornerRadiusOf(node, handle)))+}++/** A node-local point relative to the shape's centre, with its ellipse scaled to a unit circle. */+function unitOffset(node: SceneNode, local: Vector): Vector {+ return {+ x: (local.x - node.width / 2) / (node.width / 2),+ y: (local.y - node.height / 2) / (node.height / 2)+ }+}++/**+ * The point count whose next outer point lies in the direction of a node-local point: a full turn+ * over the angle from the top point, clockwise, within Figma's range.+ */+export function pointCountAtPoint(node: SceneNode, local: Vector): number {+ const { x, y } = unitOffset(node, local)+ let angle = Math.atan2(x, -y)+ if (angle <= 0) angle += 2 * Math.PI+ const count = Math.round((2 * Math.PI) / angle)+ return clamp(count, POINT_COUNT_RANGE.min, POINT_COUNT_RANGE.max)+}++/** The inner ratio of a star whose inner point lies as far from the centre as a node-local point. */+export function starRatioAtPoint(node: SceneNode, local: Vector): number {+ const { x, y } = unitOffset(node, local)+ return Math.min(Math.round(Math.hypot(x, y) * 100) / 100, 1)+}++/**+ * The radius whose arc centre lies under a node-local point, from its distance along the corner's+ * bisector, in whole pixels, or in steps of 10 with Shift.+ */+export function cornerRadiusAtPoint(+ node: SceneNode,+ corner: RadiusCorner,+ local: Vector,+ snap: boolean+): number {+ const shape = radiusCorners(node).find((candidate) => candidate.corner === corner)+ if (!shape) return 0+ const { vertex, inward, factor, max } = shape+ const distance = (local.x - vertex.x) * inward.x + (local.y - vertex.y) * inward.y+ const step = snap ? SHAPE_HANDLE.snapStep : 1+ return Math.min(Math.max(Math.round((distance * factor) / step) * step, 0), max)+}++/** The fields that set one corner, or all of them, to a radius. */+export function cornerRadiusChanges(+ node: SceneNode,+ corner: RadiusCorner,+ radius: number,+ single: boolean+): Partial<SceneNode> {+ if (corner === 'point') return { cornerRadius: radius }+ if (!single) {+ return {+ cornerRadius: radius,+ independentCorners: false,+ topLeftRadius: radius,+ topRightRadius: radius,+ bottomRightRadius: radius,+ bottomLeftRadius: radius+ }+ }+ const radii = { ...cornerRadii(node), [corner]: radius }+ return {+ independentCorners: true,+ topLeftRadius: radii.topLeft,+ topRightRadius: radii.topRight,+ bottomRightRadius: radii.bottomRight,+ bottomLeftRadius: radii.bottomLeft+ }+}diff --git a/packages/core/src/io/formats/svg/export.ts b/packages/core/src/io/formats/svg/export.tsindex 88a59ecbc..3a786a955 100644--- a/packages/core/src/io/formats/svg/export.ts+++ b/packages/core/src/io/formats/svg/export.ts@@ -17,6 +17,7 @@ import {geometryBlobToSVGPath,vectorNetworkToSVGPaths,makePolygonPoints,+ roundedPolygonPath,hasRadius,roundedRectPath,arcPath@@ -144,7 +145,9 @@ function nodeShapeElements(case 'STAR':case 'POLYGON':- return [svg('polygon', { points: makePolygonPoints(node), ...common })]+ return node.cornerRadius > 0+ ? [svg('path', { d: roundedPolygonPath(node), ...common })]+ : [svg('polygon', { points: makePolygonPoints(node), ...common })]case 'VECTOR':return vectorShapeElements(node, common, strokeAttrs, ctx)diff --git a/packages/core/src/io/formats/svg/paths.ts b/packages/core/src/io/formats/svg/paths.tsindex d90ef3707..e4d7431ba 100644--- a/packages/core/src/io/formats/svg/paths.ts+++ b/packages/core/src/io/formats/svg/paths.ts@@ -7,6 +7,7 @@ import type {VectorVertex} from '@open-pencil/scene-graph'import { polygonVertices } from '@open-pencil/scene-graph/geometry'+import { polygonOutline } from '@open-pencil/scene-graph/polygon'import { nodeHasRadius } from '#core/canvas/shapes'@@ -227,6 +228,18 @@ export function vectorNetworkToSVGPaths(return path ? [path] : []}+/** The outline of a polygon or star whose corners are rounded, as path data. */+export function roundedPolygonPath(node: SceneNode): string {+ return polygonOutline(node)+ .map((command) => {+ if (command.type === 'Z') return 'Z'+ if (command.type === 'C')+ return `C${[command.x1, command.y1, command.x2, command.y2, command.x, command.y].map(round).join(' ')}`+ return `${command.type}${round(command.x)} ${round(command.y)}`+ })+ .join('')+}+export function makePolygonPoints(node: SceneNode): string {return polygonVertices(node).map((point) => `${round(point.x)},${round(point.y)}`)diff --git a/packages/core/tests/geometry/corner-radius.test.ts b/packages/core/tests/geometry/shape-handles.test.tssimilarity index 51%rename from packages/core/tests/geometry/corner-radius.test.tsrename to packages/core/tests/geometry/shape-handles.test.tsindex 53928aca5..1668d08ae 100644--- a/packages/core/tests/geometry/corner-radius.test.ts+++ b/packages/core/tests/geometry/shape-handles.test.ts@@ -3,10 +3,12 @@ import { describe, expect, test } from 'bun:test'import {cornerRadiusAtPoint,cornerRadiusChanges,- cornerRadiusHandleLayout,+ shapeHandleLayout,createSceneGeometry,dragsSingleCorner,- hitTestCornerRadiusHandles+ hitTestShapeHandles,+ pointCountAtPoint,+ starRatioAtPoint} from '#core/geometry'import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'@@ -26,15 +28,17 @@ function rectangle(props: Partial<SceneNode> = {}, type: SceneNode['type'] = 'REfunction layout(props: Partial<SceneNode> = {}, zoom = 1, type: SceneNode['type'] = 'RECTANGLE') {const { graph, node } = rectangle(props, type)- const handles = cornerRadiusHandleLayout(node, createSceneGeometry(graph), {+ const handles = shapeHandleLayout(node, createSceneGeometry(graph), {panX: 0,panY: 0,zoom})- return handles?.map(({ corner, point }) => [corner, point.x, point.y])+ // Positions come from the corner's bisector, so they carry floating-point noise.+ const exact = (value: number) => Math.round(value * 1e6) / 1e6+ return handles?.map(({ handle, point }) => [handle, exact(point.x), exact(point.y)])}-describe('corner radius handles', () => {+describe('shape handles', () => {test('sit 12.5 screen pixels inside corners whose radius is smaller', () => {expect(layout()).toEqual([['topLeft', 12.5, 12.5],@@ -71,10 +75,68 @@ describe('corner radius handles', () => {expect(layout({}, 1, 'ELLIPSE')).toBeUndefined()})+ // Figma desktop, 2026-10-10: a 160 × 160 triangle's one handle sits below its top point, at the+ // centre of the arc, or 12.5√2 px down while that is closer; dragging it to 48 px sets 24.+ test('sit below the top point of a polygon or star', () => {+ const triangle = { width: 160, height: 160, pointCount: 3 }+ const [handle] = layout({ ...triangle, cornerRadius: 24 }, 1, 'POLYGON') ?? []+ expect(handle?.[0]).toBe('point')+ expect(handle).toEqual(['point', 80, 48])+ expect(layout(triangle, 1, 'POLYGON')?.[0][2]).toBeCloseTo(12.5 * Math.SQRT2, 5)+ expect(layout({ ...triangle, pointCount: 5 }, 1, 'STAR')).toHaveLength(3)+ })++ test('set a polygon radius from the distance below its top point, up to what fits', () => {+ const { node } = rectangle({ width: 160, height: 160, pointCount: 3 }, 'POLYGON')+ expect(cornerRadiusAtPoint(node, 'point', { x: 80, y: 48 }, false)).toBe(24)+ expect(cornerRadiusAtPoint(node, 'point', { x: 80, y: 400 }, false)).toBeCloseTo(40, 6)+ expect(cornerRadiusChanges(node, 'point', 24, false)).toEqual({ cornerRadius: 24 })+ expect(dragsSingleCorner(node, true)).toBe(false)+ })++ // Figma desktop, 2026-10-10: a star's ratio handle sits on its first inner point and its count+ // handle on its next outer point, a polygon's count handle on its second point; rounded corners+ // move them to the middle of the rounding.+ test('put the count and ratio on the points they change', () => {+ const star = { width: 160, height: 160, pointCount: 5, starInnerRadius: 0.382 }+ const at = (props: Partial<SceneNode>, type: SceneNode['type']) =>+ Object.fromEntries(+ (layout(props, 1, type) ?? []).map(([handle, x, y]) => [+ handle,+ [Math.round(Number(x) * 10) / 10, Math.round(Number(y) * 10) / 10]+ ])+ )+ expect(at(star, 'STAR')).toMatchObject({ ratio: [98, 55.3], count: [156.1, 55.3] })+ expect(at({ ...star, cornerRadius: 12 }, 'STAR')).toMatchObject({+ ratio: [99.6, 53],+ count: [130.6, 63.6]+ })+ expect(at({ width: 160, height: 160, pointCount: 3 }, 'POLYGON')).toMatchObject({+ count: [149.3, 120]+ })+ })++ // Figma desktop, 2026-10-10, dragging a 160 × 160 star's handles to points 80 px from its centre+ // at angles clockwise from its top point, and along its inner points' rays.+ test('set the point count from the angle and the ratio from the distance', () => {+ const { node } = rectangle({ width: 160, height: 160, pointCount: 5 }, 'STAR')+ const at = (degrees: number, distance: number) => ({+ x: 80 + distance * Math.sin((degrees * Math.PI) / 180),+ y: 80 - distance * Math.cos((degrees * Math.PI) / 180)+ })+ const counts = [140, 100, 60, 50, 40, 30, 20, 5].map((angle) =>+ pointCountAtPoint(node, at(angle, 80))+ )+ expect(counts).toEqual([3, 4, 6, 7, 9, 12, 18, 60])+ const ratios = [5, 40, 60, 100].map((distance) => starRatioAtPoint(node, at(36, distance)))+ expect(ratios).toEqual([0.06, 0.5, 0.75, 1])+ expect(starRatioAtPoint(node, at(20, 40))).toBe(0.5)+ })+test('take the pointer within their ring and a little beyond', () => {- const handles = [{ corner: 'topLeft' as const, point: { x: 12.5, y: 12.5 } }]- expect(hitTestCornerRadiusHandles(handles, { x: 18, y: 16 })).toBe('topLeft')- expect(hitTestCornerRadiusHandles(handles, { x: 22, y: 12.5 })).toBeNull()+ const handles = [{ handle: 'topLeft' as const, point: { x: 12.5, y: 12.5 } }]+ expect(hitTestShapeHandles(handles, { x: 18, y: 16 })).toBe('topLeft')+ expect(hitTestShapeHandles(handles, { x: 22, y: 12.5 })).toBeNull()})test('set the radius whose arc centre is under the pointer', () => {diff --git a/packages/docs/reference/figma-compatibility.md b/packages/docs/reference/figma-compatibility.mdindex 277de4da0..e803bb13a 100644--- a/packages/docs/reference/figma-compatibility.md+++ b/packages/docs/reference/figma-compatibility.md@@ -132,7 +132,7 @@ Feature-by-feature comparison of Figma Design capabilities with Open Pencil's cu| Dash patterns | ✅ | Dash-on/dash-off stroke pattern || Stroke alignment | ✅ | Inside/Center/Outside with clip-based rendering matching Figma behavior || Individual stroke weights per side | ✅ | Top/Right/Bottom/Left with side selector dropdown |-| Corner radius | ✅ | Uniform and per-corner radius with independent toggle in properties panel; canvas handles on rectangles |+| Corner radius | ✅ | Uniform and per-corner radius with independent toggle in properties panel; canvas handles on rectangles, polygons, and stars || Corner smoothing (iOS-style) | 🔲 | Figma's continuous corner rounding || Multiple fills/strokes per layer | 🔲 | Figma allows stacking fills and strokes |diff --git a/packages/docs/user-guide/drawing-shapes.md b/packages/docs/user-guide/drawing-shapes.mdindex 95ae5b8ef..6c56a5df1 100644--- a/packages/docs/user-guide/drawing-shapes.md+++ b/packages/docs/user-guide/drawing-shapes.md@@ -58,9 +58,9 @@ Add an outline to any shape. Stroke properties include:### Corner Radius-Available for rectangles, frames, components, and instances. Click the independent corners toggle to set each corner (top-left, top-right, bottom-left, bottom-right) separately.+Available for rectangles, frames, components, instances, polygons, and stars. Click the independent corners toggle to set each corner (top-left, top-right, bottom-left, bottom-right) separately; a polygon's or star's corners share one radius, which rounds its inner corners too.-On the canvas, hover a selected rectangle to show a handle inside each corner and drag one to round the corners. Equal corners change together and differing ones one at a time; hold <kbd>⌥</kbd> to swap the two and <kbd>⇧</kbd> to round to tens. The handles hide while the rectangle is under 108 pixels across on screen; zoom in to reach them.+On the canvas, hover a selected rectangle to show a handle inside each corner and drag one to round the corners. Equal corners change together and differing ones one at a time; hold <kbd>⌥</kbd> to swap the two and <kbd>⇧</kbd> to round to tens. A polygon or star has one radius handle, below its top point, which rounds all of its corners; drag the handle on its next point around the centre to change the point count, and a star's handle on its first inner point towards or away from the centre to change its ratio. The handles hide while the shape is under 108 pixels across on screen; zoom in to reach them.### Effectsdiff --git a/packages/fig/src/node-change/convert.ts b/packages/fig/src/node-change/convert.tsindex 7d96d4cae..b1c3954ce 100644--- a/packages/fig/src/node-change/convert.ts+++ b/packages/fig/src/node-change/convert.ts@@ -1,3 +1,5 @@+import { clamp } from 'es-toolkit'+import { guidToString, isUnsetGuid } from '@open-pencil/kiwi/fig/guid'import {DEFAULT_FONT_FAMILY,@@ -7,6 +9,7 @@ import {styleToWeight} from '@open-pencil/scene-graph'import { createDefaultSourceMetadata } from '@open-pencil/scene-graph/node-defaults'+import { POINT_COUNT_RANGE } from '@open-pencil/scene-graph/polygon'import { parseVariantName } from '@open-pencil/scene-graph/variant-name'/* eslint-disable max-lines -- kiwi↔scene conversion helpers are tightly coupled */@@ -290,6 +293,22 @@ function convertCornerProps(}}+/**+ * A polygon's sides or a star's points and inner ratio, which Figma writes for both kinds. The+ * wire format allows far more points than Figma keeps, and any inner scale, so both are held to+ * Figma's ranges before the outline is built from them.+ */+function convertPolygonProps(+ nc: NodeChange+): Partial<Pick<SceneNode, 'pointCount' | 'starInnerRadius'>> {+ const props: Partial<Pick<SceneNode, 'pointCount' | 'starInnerRadius'>> = {}+ if (nc.count !== undefined)+ props.pointCount = clamp(nc.count, POINT_COUNT_RANGE.min, POINT_COUNT_RANGE.max)+ if (nc.starInnerScale !== undefined && Number.isFinite(nc.starInnerScale))+ props.starInnerRadius = clamp(nc.starInnerScale, 0, 1)+ return props+}+function importedTextLineHeight(nc: NodeChange): number | null {const derivedLineHeight = nc.derivedTextData?.baselines?.[0]?.lineHeightif (derivedLineHeight !== undefined && Number.isFinite(derivedLineHeight))@@ -648,6 +667,7 @@ export function nodeChangeToProps(gridStyleId: styleRefId(nc.styleIdForGrid),sharedStyleType: sharedStyleType(nc.styleType),...convertCornerProps(nc),+ ...convertPolygonProps(nc),...convertTextProps(nc, blobs),horizontalConstraint: mapConstraint(nc.horizontalConstraint as string),verticalConstraint: mapConstraint(nc.verticalConstraint as string),diff --git a/packages/fig/src/node-change/export/context.ts b/packages/fig/src/node-change/export/context.tsindex 0f3e10346..89c5523ec 100644--- a/packages/fig/src/node-change/export/context.ts+++ b/packages/fig/src/node-change/export/context.ts@@ -111,8 +111,14 @@ export interface SceneNodeToKiwiContext {) => KiwiNodeChange[]}+/** Figma reads both parts of a GUID as signed 32-bit integers and drops a paste beyond them. */+const MAX_FIGMA_GUID_PART = 0x7fffffff++/** The GUID an ID spells, or null when it spells none Figma can read. */export function parseGuidOrNull(value: string) {- return /^\d+:\d+$/.test(value) ? stringToGuid(value) : null+ if (!/^\d+:\d+$/.test(value)) return null+ const guid = stringToGuid(value)+ return guid.sessionID <= MAX_FIGMA_GUID_PART && guid.localID <= MAX_FIGMA_GUID_PART ? guid : null}export function resolveInstanceComponentId(diff --git a/packages/fig/src/node-change/export/node.ts b/packages/fig/src/node-change/export/node.tsindex 9b1e8a438..8ffd49775 100644--- a/packages/fig/src/node-change/export/node.ts+++ b/packages/fig/src/node-change/export/node.ts@@ -830,6 +830,9 @@ function applyNodeVisualProps(if (node.fills.length > 0) nc.fillPaints = createFillPaints(context, node)context.serializeCornerRadii(node, nc)+ // Figma draws a polygon or star from its count and inner scale; its clipboard has no geometry.+ if (node.type === 'POLYGON' || node.type === 'STAR') nc.count = node.pointCount+ if (node.type === 'STAR') nc.starInnerScale = node.starInnerRadiusif (node.effects.length > 0 && !hasRawUnsupportedEffects(node)) {nc.effects = node.effects.map((effect) => ({diff --git a/packages/fig/tests/node-change/polygon.test.ts b/packages/fig/tests/node-change/polygon.test.tsnew file mode 100644index 000000000..e2da2186c--- /dev/null+++ b/packages/fig/tests/node-change/polygon.test.ts@@ -0,0 +1,68 @@+import { describe, expect, test } from 'bun:test'++import { nodeChangeToProps, sceneNodeToKiwi } from '#fig/node-change/index'++import type { NodeChange } from '@open-pencil/kiwi/fig/codec'+import { SceneGraph } from '@open-pencil/scene-graph'++// Figma desktop, 2026-10-10: a copied polygon or star carries its point count and a star its inner+// scale, and no geometry; Figma draws it from those fields.++describe('polygon and star records', () => {+ test('write their point count and inner scale', () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const star = graph.createNode('STAR', page.id, { pointCount: 6, starInnerRadius: 0.5 })+ const polygon = graph.createNode('POLYGON', page.id, { pointCount: 5 })+ const write = (id: string) => {+ const node = graph.getNode(id)+ if (!node) throw new Error('Expected the node')+ return sceneNodeToKiwi(node, { sessionID: 1, localID: 1 }, 0, { value: 2 }, graph, [])[0]+ }+ expect(write(star.id)).toMatchObject({ type: 'STAR', count: 6, starInnerScale: 0.5 })+ const written = write(polygon.id)+ expect(written).toMatchObject({ type: 'REGULAR_POLYGON', count: 5 })+ expect(written.starInnerScale).toBeUndefined()+ })++ test('read the point count and inner scale Figma copies', () => {+ const star = nodeChangeToProps(+ { type: 'STAR', size: { x: 207, y: 168 }, count: 6, starInnerScale: 0.5 } as NodeChange,+ []+ )+ expect(star).toMatchObject({ nodeType: 'STAR', pointCount: 6, starInnerRadius: 0.5 })+ const polygon = nodeChangeToProps(+ { type: 'REGULAR_POLYGON', size: { x: 100, y: 100 }, count: 3 } as NodeChange,+ []+ )+ expect(polygon).toMatchObject({ nodeType: 'POLYGON', pointCount: 3 })+ })++ // Figma's plugin API clamps a point count to 3–60 and rejects an inner ratio outside 0–1; the+ // wire format allows far more, which would otherwise size the outline.+ test('hold an imported count and inner scale to Figma ranges', () => {+ const read = (change: Partial<NodeChange>) =>+ nodeChangeToProps({ type: 'STAR', size: { x: 100, y: 100 }, ...change } as NodeChange, [])+ expect(read({ count: 4_000_000_000, starInnerScale: 1.5 })).toMatchObject({+ pointCount: 60,+ starInnerRadius: 1+ })+ expect(read({ count: 1, starInnerScale: -0.5 })).toMatchObject({+ pointCount: 3,+ starInnerRadius: 0+ })+ expect(read({ starInnerScale: Number.NaN }).starInnerRadius).toBeUndefined()+ })++ // Figma desktop, 2026-10-10: a paste with a GUID part of 2³¹ or more is dropped whole. Layers+ // made in a session past that keep its IDs as their source through autosave.+ test('do not carry an ID Figma cannot read as their GUID', () => {+ const graph = new SceneGraph()+ const star = graph.createNode('STAR', graph.getPages()[0].id)+ graph.updateNode(star.id, { source: { ...star.source, id: '2496617298:3' } })+ const node = graph.getNode(star.id)+ if (!node) throw new Error('Expected the star')+ const [record] = sceneNodeToKiwi(node, { sessionID: 1, localID: 1 }, 0, { value: 2 }, graph, [])+ expect(record.guid).toEqual({ sessionID: 1, localID: 2 })+ })+})diff --git a/packages/kiwi/src/fig/codec.ts b/packages/kiwi/src/fig/codec.tsindex 6dfbadb38..b20deca85 100644--- a/packages/kiwi/src/fig/codec.ts+++ b/packages/kiwi/src/fig/codec.ts@@ -370,6 +370,10 @@ export interface NodeChange {rectangleBottomRightCornerRadius?: numberrectangleCornerRadiiIndependent?: booleancornerSmoothing?: number+ /** A polygon's sides or a star's points. */+ count?: number+ /** A star's inner radius as a share of its outer one. */+ starInnerScale?: number// ConstraintshorizontalConstraint?: stringverticalConstraint?: stringdiff --git a/packages/scene-graph/package.json b/packages/scene-graph/package.jsonindex 377690827..1ab1dbedf 100644--- a/packages/scene-graph/package.json+++ b/packages/scene-graph/package.json@@ -161,6 +161,12 @@"import": "./dist/geometry.js","default": "./dist/geometry.js"},+ "./polygon": {+ "types": "./dist/polygon.d.ts",+ "bun": "./src/polygon.ts",+ "import": "./dist/polygon.js",+ "default": "./dist/polygon.js"+ },"./resize": {"types": "./dist/resize.d.ts","bun": "./src/resize.ts",diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.tsindex ae2161879..9fcdb247d 100644--- a/packages/scene-graph/src/index.ts+++ b/packages/scene-graph/src/index.ts@@ -123,7 +123,8 @@ export {vectorNetworksEqual} from './vector-network'-const MAX_ID_SESSION = 0xffffffff+/** Figma reads both parts of a GUID as signed 32-bit integers and drops records beyond them. */+const MAX_ID_SESSION = 0x7ffffffflet idSession = 0let nextLocalID = 1@@ -136,7 +137,7 @@ let nextLocalID = 1*/export function setIdSession(sessionId: number): void {if (!Number.isInteger(sessionId) || sessionId < 0 || sessionId > MAX_ID_SESSION) {- throw new RangeError('sessionId must be an unsigned 32-bit integer')+ throw new RangeError('sessionId must be a non-negative 31-bit integer')}idSession = sessionId}diff --git a/packages/scene-graph/src/polygon.ts b/packages/scene-graph/src/polygon.tsnew file mode 100644index 000000000..6a148b258--- /dev/null+++ b/packages/scene-graph/src/polygon.ts@@ -0,0 +1,211 @@+import { polygonVertices } from './geometry'+import type { Vector } from './primitives'+import type { SceneNode } from './types'++/**+ * Rounded polygon and star outlines, as Figma draws them. Each corner, convex or not, is rounded by+ * a circular arc tangent to both edges, capped so that it and its neighbours fit along every edge;+ * corner smoothing replaces the arc's ends with curves that ease into the edges, as on rectangles.+ */++/** Figma keeps a polygon's sides or a star's points within this range, and its plugin API clamps to it. */+export const POINT_COUNT_RANGE = { min: 3, max: 60 } as const++export type PolygonOutlineCommand =+ | { type: 'M' | 'L'; x: number; y: number }+ | { type: 'C'; x1: number; y1: number; x2: number; y2: number; x: number; y: number }+ | { type: 'Z' }++type PolygonNode = Pick<+ SceneNode,+ | 'type'+ | 'width'+ | 'height'+ | 'pointCount'+ | 'starInnerRadius'+ | 'cornerRadius'+ | 'cornerSmoothing'+>++export interface PolygonCorner {+ vertex: Vector+ /** The unit direction of the edge arriving at the vertex. */+ incoming: Vector+ /** The unit direction of the edge leaving the vertex. */+ outgoing: Vector+ /** How far the outline turns at the vertex, in radians: 0 for a straight line. */+ turn: number+ /** The radius the corner is drawn with, after fitting it along its edges. */+ radius: number+ /** How far along each edge from the vertex the rounding starts. */+ extent: number+}++const sub = (a: Vector, b: Vector): Vector => ({ x: a.x - b.x, y: a.y - b.y })+const along = (point: Vector, direction: Vector, distance: number): Vector => ({+ x: point.x + direction.x * distance,+ y: point.y + direction.y * distance+})++function unit(vector: Vector): Vector {+ const length = Math.hypot(vector.x, vector.y)+ return length > 0 ? { x: vector.x / length, y: vector.y / length } : { x: 0, y: 0 }+}++/** The perpendicular of `direction` on the side the outline turns towards. */+function inward(direction: Vector, towards: Vector): Vector {+ const normal = { x: -direction.y, y: direction.x }+ return normal.x * towards.x + normal.y * towards.y < 0+ ? { x: direction.y, y: -direction.x }+ : normal+}++/**+ * The polygon's or star's corners with the radius each is drawn with. A corner turning by α keeps+ * r·tan(α/2) of each edge, so on an edge of length L between corners turning by α and β the radius+ * is at most L / (tan(α/2) + tan(β/2)); each corner takes the least of its two edges' limits.+ */+export function polygonCorners(node: PolygonNode): PolygonCorner[] {+ const vertices = polygonVertices(node)+ const count = vertices.length+ const at = (index: number) => vertices[(index + count) % count]+ const shape = vertices.map((vertex, index) => {+ const incoming = unit(sub(vertex, at(index - 1)))+ const outgoing = unit(sub(at(index + 1), vertex))+ const cos = Math.min(1, Math.max(-1, incoming.x * outgoing.x + incoming.y * outgoing.y))+ const turn = Math.acos(cos)+ return { vertex, incoming, outgoing, turn, factor: Math.tan(turn / 2) }+ })+ const edgeLimit = (index: number) => {+ const from = shape[(index + count) % count]+ const to = shape[(index + 1 + count) % count]+ const length = Math.hypot(to.vertex.x - from.vertex.x, to.vertex.y - from.vertex.y)+ const factors = from.factor + to.factor+ return factors > 0 ? length / factors : Number.POSITIVE_INFINITY+ }+ const requested = Math.max(0, node.cornerRadius)+ return shape.map(({ factor, ...corner }, index) => {+ const radius = Math.min(requested, edgeLimit(index - 1), edgeLimit(index))+ return { ...corner, radius, extent: radius * factor }+ })+}++interface SmoothCorner {+ /** Where the rounding starts, along each edge from the vertex. */+ p: number+ a: number+ b: number+ c: number+ d: number+ /** The angle each eased end takes from the arc, in radians. */+ ease: number+}++/**+ * Figma's smoothing for a corner turning by any angle: the rectangle construction with the+ * tangent length r·tan(α/2) in place of r and α/2 in place of 45°. Smoothing grows the rounded+ * part of each edge by up to its tangent length again.+ */+function smoothCorner(corner: PolygonCorner, smoothing: number): SmoothCorner {+ const { radius, extent } = corner+ const p = (1 + smoothing) * extent+ const ease = (corner.turn * smoothing) / 2+ const toEase = radius * Math.tan(ease / 2)+ const c = toEase * Math.cos(ease)+ const d = toEase * Math.sin(ease)+ const arcStart = extent - radius * Math.sin(ease) - d+ const b = (p - arcStart - c - d) / 3+ return { p, a: 2 * b, b, c, d, ease }+}++function rotate(direction: Vector, towards: Vector, angle: number): Vector {+ const normal = inward(direction, towards)+ return {+ x: direction.x * Math.cos(angle) + normal.x * Math.sin(angle),+ y: direction.y * Math.cos(angle) + normal.y * Math.sin(angle)+ }+}++function cubic(c1: Vector, c2: Vector, to: Vector): PolygonOutlineCommand {+ return { type: 'C', x1: c1.x, y1: c1.y, x2: c2.x, y2: c2.y, x: to.x, y: to.y }+}++/** The rounded corner from where it leaves the incoming edge to where it joins the outgoing one. */+function cornerCommands(corner: PolygonCorner, smooth: SmoothCorner): PolygonOutlineCommand[] {+ const { vertex, incoming, outgoing, radius, turn } = corner+ const { p, a, b, c, d, ease } = smooth+ const back = { x: -incoming.x, y: -incoming.y }+ const start = along(vertex, back, p)+ const end = along(vertex, outgoing, p)+ const normalIn = inward(incoming, outgoing)+ const normalOut = inward(outgoing, back)+ const arcFrom = along(along(start, incoming, a + b + c), normalIn, d)+ const arcTo = along(along(end, outgoing, -(a + b + c)), normalOut, d)+ const commands: PolygonOutlineCommand[] = []+ if (ease > 0)+ commands.push(cubic(along(start, incoming, a), along(start, incoming, a + b), arcFrom))+ const sweep = turn - 2 * ease+ if (sweep > 0) {+ const handle = (4 / 3) * Math.tan(sweep / 4) * radius+ const leaving = rotate(incoming, outgoing, ease)+ const arriving = rotate(outgoing, incoming, ease)+ commands.push(cubic(along(arcFrom, leaving, handle), along(arcTo, arriving, -handle), arcTo))+ }+ if (ease > 0) commands.push(cubic(along(end, outgoing, -(a + b)), along(end, outgoing, -a), end))+ return commands+}++/**+ * The smoothing every corner can take: on each edge a corner may use the part its tangent length+ * takes of both corners' tangent lengths, and Figma lowers smoothing for the whole shape to what+ * its tightest corner allows rather than corner by corner.+ */+function fittedSmoothing(corners: readonly PolygonCorner[], smoothing: number): number {+ const count = corners.length+ const share = (corner: PolygonCorner, neighbour: PolygonCorner) => {+ const length = Math.hypot(+ neighbour.vertex.x - corner.vertex.x,+ neighbour.vertex.y - corner.vertex.y+ )+ return (length * corner.extent) / (corner.extent + neighbour.extent)+ }+ return corners.reduce(+ (fitted, corner, index) => {+ if (!(corner.extent > 0)) return fitted+ const budget = Math.min(+ share(corner, corners[(index - 1 + count) % count]),+ share(corner, corners[(index + 1) % count])+ )+ return Math.min(fitted, budget / corner.extent - 1)+ },+ Math.min(Math.max(smoothing, 0), 1)+ )+}++/** The outline of a polygon or star with its corner radius and smoothing, in its own pixels. */+export function polygonOutline(node: PolygonNode): PolygonOutlineCommand[] {+ const corners = polygonCorners(node)+ const smoothing = Math.max(0, fittedSmoothing(corners, node.cornerSmoothing))+ const commands: PolygonOutlineCommand[] = []+ let current: Vector | null = null+ // Corners whose rounding meets along an edge leave no line between them.+ const lineTo = ({ x, y }: Vector) => {+ if (current && Math.hypot(x - current.x, y - current.y) < 1e-6) return+ commands.push({ type: current ? 'L' : 'M', x, y })+ current = { x, y }+ }+ for (const corner of corners) {+ if (!(corner.radius > 0) || !(corner.turn > 0)) {+ lineTo(corner.vertex)+ continue+ }+ const smooth = smoothCorner(corner, smoothing)+ lineTo(along(corner.vertex, { x: -corner.incoming.x, y: -corner.incoming.y }, smooth.p))+ for (const command of cornerCommands(corner, smooth)) {+ commands.push(command)+ if (command.type === 'C') current = { x: command.x, y: command.y }+ }+ }+ commands.push({ type: 'Z' })+ return commands+}diff --git a/packages/scene-graph/tests/basic/id-generator.test.ts b/packages/scene-graph/tests/basic/id-generator.test.tsindex ee2097ad2..83752d21c 100644--- a/packages/scene-graph/tests/basic/id-generator.test.ts+++ b/packages/scene-graph/tests/basic/id-generator.test.ts@@ -66,18 +66,19 @@ describe('SceneGraph ID generator', () => {test('the ID session prefixes every ID minted afterwards', () => {try {- setIdSession(4_000_000_000)+ setIdSession(2_000_000_000)const graph = new SceneGraph()const ids = [graph.rootId, pageId(graph), graph.createCollection('Colors').id]- for (const id of ids) expect(id).toMatch(/^4000000000:\d+$/)+ for (const id of ids) expect(id).toMatch(/^2000000000:\d+$/)} finally {setIdSession(0)}expect(new SceneGraph().rootId).toMatch(/^0:\d+$/)})- test('rejects an ID session that is not an unsigned 32-bit integer', () => {- for (const value of [-1, 1.5, 2 ** 32, Number.NaN]) {+ // Figma reads GUID parts as signed 32-bit integers and drops a paste with larger ones.+ test('rejects an ID session that is not a non-negative 31-bit integer', () => {+ for (const value of [-1, 1.5, 2 ** 31, 2 ** 32, Number.NaN]) {expect(() => setIdSession(value)).toThrow(RangeError)}})diff --git a/packages/scene-graph/tests/fixtures/figma-polygon-corners.json b/packages/scene-graph/tests/fixtures/figma-polygon-corners.jsonnew file mode 100644index 000000000..78224344b--- /dev/null+++ b/packages/scene-graph/tests/fixtures/figma-polygon-corners.json@@ -0,0 +1,243 @@+{+ "source": {+ "tool": "Figma desktop plugin API over CDP",+ "property": "fillGeometry",+ "captured": "2026-10-10"+ },+ "cases": [+ {+ "name": "triangle",+ "type": "POLYGON",+ "pointCount": 3,+ "width": 160,+ "height": 160,+ "cornerRadius": 24,+ "cornerSmoothing": 0,+ "starInnerRadius": null,+ "fillGeometry": [+ "M59.2154 36 C68.453 20 91.547 20 100.785 36 L128.497 84 C137.735 100 126.188 120 107.713 120 L52.2872 120 C33.812 120 22.265 100 31.5026 84 L59.2154 36 Z"+ ]+ },+ {+ "name": "triangle clamped",+ "type": "POLYGON",+ "pointCount": 3,+ "width": 160,+ "height": 160,+ "cornerRadius": 100,+ "cornerSmoothing": 0,+ "starInnerRadius": null,+ "fillGeometry": [+ "M45.359 60 C60.755 33.3333 99.245 33.3333 114.641 60 L114.641 60 C130.037 86.6666 110.792 120 80 120 L80 120 C49.208 120 29.963 86.6667 45.359 60 L45.359 60 Z"+ ]+ },+ {+ "name": "wide triangle",+ "type": "POLYGON",+ "pointCount": 3,+ "width": 300,+ "height": 100,+ "cornerRadius": 15,+ "cornerSmoothing": 0,+ "starInnerRadius": null,+ "fillGeometry": [+ "M142.5 4.33012 C147.141 1.65063 152.859 1.65064 157.5 4.33013 L231.423 47.0096 C244.714 54.6829 239.27 75 223.923 75 L76.0769 75 C60.7304 75 55.2865 54.6829 68.577 47.0096 L142.5 4.33012 Z"+ ]+ },+ {+ "name": "wide triangle clamped",+ "type": "POLYGON",+ "pointCount": 3,+ "width": 300,+ "height": 100,+ "cornerRadius": 100,+ "cornerSmoothing": 0,+ "starInnerRadius": null,+ "fillGeometry": [+ "M132.596 10.0481 C143.366 3.83031 156.634 3.83031 167.404 10.0481 L167.404 10.0481 C198.245 27.854 185.612 75 150 75 L150 75 C114.388 75 101.755 27.854 132.596 10.0481 L132.596 10.0481 Z"+ ]+ },+ {+ "name": "diamond clamped",+ "type": "POLYGON",+ "pointCount": 4,+ "width": 200,+ "height": 100,+ "cornerRadius": 100,+ "cornerSmoothing": 0,+ "starInnerRadius": null,+ "fillGeometry": [+ "M80 10 C92.5903 3.70486 107.41 3.70485 120 10 L120 10 C152.962 26.4809 152.962 73.5191 120 90 L120 90 C107.41 96.2951 92.5903 96.2952 80 90 L80 90 C47.0382 73.5191 47.0382 26.4809 80 10 L80 10 Z"+ ]+ },+ {+ "name": "pentagon",+ "type": "POLYGON",+ "pointCount": 5,+ "width": 160,+ "height": 160,+ "cornerRadius": 16,+ "cornerSmoothing": 0,+ "starInnerRadius": null,+ "fillGeometry": [+ "M70.5954 6.83281 C76.2032 2.75851 83.7968 2.75851 89.4046 6.83282 L146.68 48.4458 C152.288 52.5201 154.634 59.742 152.492 66.3344 L130.615 133.666 C128.473 140.258 122.33 144.721 115.398 144.721 L44.6019 144.721 C37.6702 144.721 31.5269 140.258 29.385 133.666 L7.5077 66.3344 C5.36572 59.742 7.71225 52.5201 13.32 48.4458 L70.5954 6.83281 Z"+ ]+ },+ {+ "name": "wide hexagon",+ "type": "POLYGON",+ "pointCount": 6,+ "width": 200,+ "height": 100,+ "cornerRadius": 20,+ "cornerSmoothing": 0,+ "starInnerRadius": null,+ "fillGeometry": [+ "M94.453 1.60128 C98.077 0.555123 101.923 0.55512 105.547 1.60128 L172.15 20.8278 C180.709 23.2988 186.603 31.1338 186.603 40.0432 L186.603 59.9568 C186.603 68.8662 180.709 76.7012 172.15 79.1722 L105.547 98.3987 C101.923 99.4449 98.077 99.4449 94.453 98.3987 L27.8505 79.1722 C19.2907 76.7012 13.3975 68.8662 13.3975 59.9568 L13.3975 40.0432 C13.3975 31.1338 19.2906 23.2988 27.8505 20.8278 L94.453 1.60128 Z"+ ]+ },+ {+ "name": "flat hexagon clamped",+ "type": "POLYGON",+ "pointCount": 6,+ "width": 200,+ "height": 60,+ "cornerRadius": 100,+ "cornerSmoothing": 0,+ "starInnerRadius": null,+ "fillGeometry": [+ "M85.2201 2.55996 C95.0006 0.865929 104.999 0.865932 114.78 2.55996 L171.823 12.44 C180.364 13.9195 186.603 21.331 186.603 30 L186.603 30 C186.603 38.669 180.364 46.0805 171.823 47.56 L114.78 57.44 C104.999 59.1341 95.0005 59.1341 85.2201 57.44 L28.1774 47.56 C19.6356 46.0805 13.3975 38.669 13.3975 30 L13.3975 30 C13.3975 21.331 19.6356 13.9195 28.1774 12.44 L85.2201 2.55996 Z"+ ]+ },+ {+ "name": "star",+ "type": "STAR",+ "pointCount": 5,+ "width": 160,+ "height": 160,+ "cornerRadius": 10,+ "cornerSmoothing": 0,+ "starInnerRadius": 0.3819660246372223,+ "fillGeometry": [+ "M70.4894 29.2705 C73.483 20.0574 86.517 20.0574 89.5106 29.2705 L95.716 48.3688 C97.0547 52.489 100.894 55.2786 105.227 55.2786 L125.308 55.2786 C134.995 55.2786 139.023 67.6748 131.186 73.3688 L114.94 85.1722 C111.435 87.7187 109.968 92.2323 111.307 96.3525 L117.512 115.451 C120.506 124.664 109.961 132.325 102.124 126.631 L85.8779 114.828 C82.373 112.281 77.627 112.281 74.1221 114.828 L57.8762 126.631 C50.039 132.325 39.4942 124.664 42.4877 115.451 L48.6932 96.3525 C50.0319 92.2323 48.5653 87.7187 45.0604 85.1722 L28.8145 73.3688 C20.9773 67.6748 25.0051 55.2786 34.6923 55.2786 L54.7735 55.2786 C59.1057 55.2786 62.9453 52.489 64.284 48.3688 L70.4894 29.2705 Z"+ ]+ },+ {+ "name": "star clamped",+ "type": "STAR",+ "pointCount": 5,+ "width": 160,+ "height": 160,+ "cornerRadius": 100,+ "cornerSmoothing": 0,+ "starInnerRadius": 0.3819660246372223,+ "fillGeometry": [+ "M65.4691 44.7214 C70.0428 30.645 89.9572 30.645 94.5309 44.7214 L94.5309 44.7214 C96.5763 51.0165 102.443 55.2786 109.062 55.2786 L109.062 55.2786 C123.862 55.2786 130.016 74.2183 118.042 82.918 L118.042 82.918 C112.687 86.8086 110.447 93.7048 112.492 100 L112.492 100 C117.066 114.076 100.955 125.782 88.9806 117.082 L88.9806 117.082 C83.6256 113.191 76.3744 113.191 71.0194 117.082 L71.0194 117.082 C59.0454 125.782 42.9343 114.076 47.508 100 L47.508 100 C49.5534 93.7048 47.3127 86.8086 41.9577 82.918 L41.9577 82.918 C29.9837 74.2183 36.1375 55.2786 50.9383 55.2786 L50.9383 55.2786 C57.5574 55.2786 63.4237 51.0165 65.4691 44.7214 L65.4691 44.7214 Z"+ ]+ },+ {+ "name": "wide star clamped",+ "type": "STAR",+ "pointCount": 5,+ "width": 300,+ "height": 100,+ "cornerRadius": 100,+ "cornerSmoothing": 0,+ "starInnerRadius": 0.3819660246372223,+ "fillGeometry": [+ "M126.134 24.4843 C139.215 11.0644 160.785 11.0644 173.866 24.4843 L180.031 30.809 C182.362 33.2004 185.561 34.5491 188.9 34.5491 L217.655 34.5491 C228.252 34.5491 230.062 49.7089 219.762 52.2032 L219.762 52.2032 C213.02 53.8361 210.727 62.2992 215.569 67.267 L215.569 67.267 C222.033 73.8984 216.016 85.0861 207.015 82.9063 L155.746 70.4899 C151.97 69.5754 148.03 69.5754 144.254 70.4899 L92.9846 82.9063 C83.9842 85.0861 77.9669 73.8984 84.4309 67.267 L84.4309 67.267 C89.2733 62.2992 86.9801 53.8361 80.2377 52.2032 L80.2377 52.2032 C69.9385 49.7089 71.7481 34.5491 82.345 34.5491 L111.1 34.5491 C114.439 34.5491 117.638 33.2004 119.969 30.809 L126.134 24.4843 Z"+ ]+ },+ {+ "name": "six-point star clamped",+ "type": "STAR",+ "pointCount": 6,+ "width": 160,+ "height": 160,+ "cornerRadius": 100,+ "cornerSmoothing": 0,+ "starInnerRadius": 0.6000000238418579,+ "fillGeometry": [+ "M61.9856 28.8462 C70.3028 15.5279 89.6972 15.5279 98.0144 28.8462 L98.0144 28.8462 C101.756 34.8383 108.233 38.5775 115.293 38.8221 L115.293 38.8221 C130.986 39.366 140.683 56.162 133.308 70.024 L133.308 70.024 C129.989 76.2608 129.989 83.7392 133.308 89.976 L133.308 89.976 C140.683 103.838 130.986 120.634 115.293 121.178 L115.293 121.178 C108.233 121.423 101.756 125.162 98.0144 131.154 L98.0144 131.154 C89.6972 144.472 70.3028 144.472 61.9856 131.154 L61.9856 131.154 C58.2435 125.162 51.767 121.423 44.7067 121.178 L44.7067 121.178 C29.0141 120.634 19.317 103.838 26.6923 89.976 L26.6923 89.976 C30.0105 83.7392 30.0105 76.2608 26.6923 70.024 L26.6923 70.024 C19.317 56.162 29.0141 39.366 44.7067 38.8221 L44.7067 38.8221 C51.767 38.5775 58.2435 34.8382 61.9856 28.8462 L61.9856 28.8462 Z"+ ]+ },+ {+ "name": "smooth triangle",+ "type": "POLYGON",+ "pointCount": 3,+ "width": 160,+ "height": 160,+ "cornerRadius": 24,+ "cornerSmoothing": 0.6,+ "starInnerRadius": null,+ "fillGeometry": [+ "M46.7446 57.6 C57.6578 38.6978 63.1144 29.2467 70.2383 26.0749 C76.4521 23.3084 83.5479 23.3084 89.7617 26.0749 C96.8856 29.2467 102.342 38.6978 113.255 57.6 L116.027 62.4 C126.94 81.3022 132.396 90.7533 131.581 98.5087 C130.87 105.273 127.322 111.418 121.82 115.416 C115.511 120 104.598 120 82.7713 120 L77.2288 120 C55.4023 120 44.4891 120 38.1803 115.416 C32.6776 111.418 29.1296 105.273 28.4187 98.5087 C27.6035 90.7533 33.0601 81.3022 43.9733 62.4 L46.7446 57.6 Z"+ ]+ },+ {+ "name": "fully smooth triangle",+ "type": "POLYGON",+ "pointCount": 3,+ "width": 160,+ "height": 160,+ "cornerRadius": 35,+ "cornerSmoothing": 1,+ "starInnerRadius": null,+ "fillGeometry": [+ "M45.359 60 C49.12 53.4857 51.0006 50.2285 52.6359 48.1779 C66.6479 30.6074 93.3521 30.6074 107.364 48.1779 C108.999 50.2285 110.88 53.4857 114.641 60 L114.641 60 C118.402 66.5143 120.283 69.7715 121.241 72.2131 C129.451 93.133 116.099 116.26 93.8767 119.609 C91.2831 120 87.5221 120 80 120 L80 120 C72.4779 120 68.7169 120 66.1233 119.609 C43.9008 116.26 30.5487 93.133 38.7592 72.2131 C39.7174 69.7715 41.5979 66.5143 45.359 60 L45.359 60 Z"+ ]+ },+ {+ "name": "smooth pentagon",+ "type": "POLYGON",+ "pointCount": 5,+ "width": 160,+ "height": 160,+ "cornerRadius": 16,+ "cornerSmoothing": 1,+ "starInnerRadius": null,+ "fillGeometry": [+ "M61.1909 13.6656 C70.2645 7.07327 74.8013 3.77709 80 3.77709 C85.1987 3.77709 89.7355 7.07327 98.8091 13.6656 L137.275 41.613 C146.349 48.2054 150.886 51.5016 152.492 56.4458 C154.099 61.3901 152.366 66.7234 148.9 77.3901 L134.207 122.61 C130.741 133.277 129.009 138.61 124.803 141.666 C120.597 144.721 114.989 144.721 103.773 144.721 L56.2265 144.721 C45.0109 144.721 39.4031 144.721 35.1973 141.666 C30.9914 138.61 29.2585 133.277 25.7927 122.61 L11.0999 77.3901 C7.63412 66.7234 5.90121 61.3901 7.50771 56.4458 C9.1142 51.5016 13.651 48.2054 22.7246 41.613 L61.1909 13.6656 Z"+ ]+ },+ {+ "name": "smooth flat hexagon clamped",+ "type": "POLYGON",+ "pointCount": 6,+ "width": 200,+ "height": 60,+ "cornerRadius": 100,+ "cornerSmoothing": 0.5,+ "starInnerRadius": null,+ "fillGeometry": [+ "M85.2201 2.55996 C95.0006 0.865929 104.999 0.865932 114.78 2.55996 L171.823 12.44 C180.364 13.9195 186.603 21.331 186.603 30 L186.603 30 C186.603 38.669 180.364 46.0805 171.823 47.56 L114.78 57.44 C104.999 59.1341 95.0005 59.1341 85.2201 57.44 L28.1774 47.56 C19.6356 46.0805 13.3975 38.669 13.3975 30 L13.3975 30 C13.3975 21.331 19.6356 13.9195 28.1774 12.44 L85.2201 2.55996 Z"+ ]+ },+ {+ "name": "smooth star",+ "type": "STAR",+ "pointCount": 5,+ "width": 160,+ "height": 160,+ "cornerRadius": 10,+ "cornerSmoothing": 0.6,+ "starInnerRadius": 0.3819660246372223,+ "fillGeometry": [+ "M65.4691 44.7214 C69.5255 32.2372 71.5537 25.9952 74.409 24.0697 C77.7881 21.791 82.2119 21.791 85.591 24.0697 C88.4463 25.9952 90.4745 32.2372 94.5309 44.7214 L94.5309 44.7214 C95.6657 48.2142 96.2332 49.9606 97.2405 51.2972 C98.4396 52.8883 100.087 54.0849 101.97 54.7337 C103.553 55.2786 105.389 55.2786 109.062 55.2786 L109.062 55.2786 C122.188 55.2786 128.752 55.2786 131.465 57.3992 C134.677 59.9088 136.044 64.1161 134.921 68.034 C133.972 71.3445 128.662 75.2024 118.042 82.918 L118.042 82.918 C115.071 85.0766 113.586 86.156 112.626 87.5271 C111.483 89.1591 110.854 91.0953 110.819 93.0873 C110.79 94.7608 111.357 96.5072 112.492 100 L112.492 100 C116.548 112.484 118.576 118.726 117.398 121.962 C116.004 125.792 112.425 128.392 108.352 128.535 C104.91 128.655 99.6002 124.798 88.9806 117.082 L88.9806 117.082 C86.0094 114.923 84.5238 113.844 82.9232 113.355 C81.0179 112.772 78.9821 112.772 77.0768 113.355 C75.4762 113.844 73.9906 114.923 71.0194 117.082 L71.0194 117.082 C60.3998 124.798 55.09 128.655 51.6482 128.535 C47.5751 128.392 43.9961 125.792 42.6018 121.962 C41.4235 118.726 43.4517 112.484 47.508 100 L47.508 100 C48.6429 96.5072 49.2104 94.7608 49.1811 93.0873 C49.1462 91.0953 48.5171 89.1591 47.3744 87.5271 C46.4145 86.156 44.9289 85.0766 41.9577 82.918 L41.9577 82.918 C31.3381 75.2024 26.0283 71.3445 25.0794 68.034 C23.9564 64.1161 25.3235 59.9088 28.5348 57.3992 C31.2484 55.2786 37.8117 55.2786 50.9383 55.2786 L50.9383 55.2786 C54.6109 55.2786 56.4472 55.2786 58.0296 54.7337 C59.9134 54.0849 61.5604 52.8883 62.7595 51.2972 C63.7668 49.9606 64.3343 48.2142 65.4691 44.7214 L65.4691 44.7214 Z"+ ]+ },+ {+ "name": "smooth star clamped",+ "type": "STAR",+ "pointCount": 5,+ "width": 160,+ "height": 160,+ "cornerRadius": 100,+ "cornerSmoothing": 0.8,+ "starInnerRadius": 0.3819660246372223,+ "fillGeometry": [+ "M65.4691 44.7214 C70.0428 30.645 89.9572 30.645 94.5309 44.7214 L94.5309 44.7214 C96.5763 51.0165 102.443 55.2786 109.062 55.2786 L109.062 55.2786 C123.862 55.2786 130.016 74.2183 118.042 82.918 L118.042 82.918 C112.687 86.8086 110.447 93.7048 112.492 100 L112.492 100 C117.066 114.076 100.955 125.782 88.9806 117.082 L88.9806 117.082 C83.6256 113.191 76.3744 113.191 71.0194 117.082 L71.0194 117.082 C59.0454 125.782 42.9343 114.076 47.508 100 L47.508 100 C49.5534 93.7048 47.3127 86.8086 41.9577 82.918 L41.9577 82.918 C29.9837 74.2183 36.1375 55.2786 50.9383 55.2786 L50.9383 55.2786 C57.5574 55.2786 63.4237 51.0165 65.4691 44.7214 L65.4691 44.7214 Z"+ ]+ }+ ]+}diff --git a/packages/scene-graph/tests/polygon.test.ts b/packages/scene-graph/tests/polygon.test.tsnew file mode 100644index 000000000..a6a3e0669--- /dev/null+++ b/packages/scene-graph/tests/polygon.test.ts@@ -0,0 +1,113 @@+import { describe, expect, test } from 'bun:test'+import { readFileSync } from 'node:fs'++import { compact } from 'es-toolkit'+import * as v from 'valibot'++import { polygonCorners, polygonOutline, type PolygonOutlineCommand } from '@open-pencil/scene-graph/polygon'++// Outlines Figma desktop gives as `fillGeometry` for polygons and stars, recorded on 2026-10-10.+const Oracle = v.object({+ cases: v.array(+ v.object({+ name: v.string(),+ type: v.picklist(['POLYGON', 'STAR']),+ pointCount: v.number(),+ width: v.number(),+ height: v.number(),+ cornerRadius: v.number(),+ cornerSmoothing: v.number(),+ starInnerRadius: v.nullable(v.number()),+ fillGeometry: v.array(v.string())+ })+ )+})++const oracle = v.parse(+ v.pipe(v.string(), v.parseJson(), Oracle),+ readFileSync(new URL('fixtures/figma-polygon-corners.json', import.meta.url), 'utf8')+)++type Point = [number, number]++/** Figma's commands as end points and controls, without the zero-length lines it leaves between arcs that meet. */+function figmaCommands(data: string): Array<{ type: string; points: Point[] }> {+ const commands: Array<{ type: string; points: Point[] }> = []+ let last: Point = [0, 0]+ for (const [, type, args] of data.matchAll(/([MLCZ])([^MLCZ]*)/g)) {+ const numbers = compact(args.trim().split(/\s+/)).map(Number)+ const points: Point[] = []+ for (let index = 0; index < numbers.length; index += 2) points.push([numbers[index], numbers[index + 1]])+ const end = points.at(-1)+ if (type === 'L' && end && Math.hypot(end[0] - last[0], end[1] - last[1]) < 1e-3) continue+ if (end) last = end+ commands.push({ type, points })+ }+ return commands+}++function ourCommands(commands: PolygonOutlineCommand[]) {+ return commands.map((command) => {+ if (command.type === 'Z') return { type: 'Z', points: [] as Point[] }+ if (command.type === 'C')+ return {+ type: 'C',+ points: [+ [command.x1, command.y1],+ [command.x2, command.y2],+ [command.x, command.y]+ ] as Point[]+ }+ return { type: command.type, points: [[command.x, command.y]] as Point[] }+ })+}++// Where two clamped corners almost fill an edge, Figma stretches both along it to use the rest of+// the edge, leaving them slightly lopsided; ours stay circular with a short line between them.+const LOPSIDED = new Set(['wide star clamped'])++describe('polygon outlines', () => {+ for (const sample of oracle.cases) {+ const node = { ...sample, starInnerRadius: sample.starInnerRadius ?? 0 }+ const ours = ourCommands(polygonOutline(node))+ const figma = figmaCommands(sample.fillGeometry.join(' '))+ // Figma closes with a line back to the start, which Z already draws.+ if (figma.at(-2)?.type === 'L') figma.splice(-2, 1)++ if (LOPSIDED.has(sample.name)) {+ test(`${sample.name} stays within a third of a pixel of Figma`, () => {+ const theirs = figma.flatMap((command) => command.points)+ for (const [x, y] of ours.flatMap((command) => command.points)) {+ const nearest = Math.min(...theirs.map(([fx, fy]) => Math.hypot(x - fx, y - fy)))+ expect(nearest).toBeLessThan(0.35)+ }+ })+ continue+ }++ test(`${sample.name} matches Figma`, () => {+ expect(ours.map((command) => command.type)).toEqual(figma.map((command) => command.type))+ ours.forEach((command, index) =>+ command.points.forEach(([x, y], point) => {+ const [fx, fy] = figma[index].points[point]+ expect(Math.hypot(x - fx, y - fy)).toBeLessThan(0.01)+ })+ )+ })+ }++ test('a corner keeps its radius until it no longer fits along its edges', () => {+ const corners = (cornerRadius: number) =>+ polygonCorners({+ type: 'POLYGON',+ pointCount: 3,+ width: 160,+ height: 160,+ starInnerRadius: 0,+ cornerRadius,+ cornerSmoothing: 0+ }).map((corner) => corner.radius)+ expect(corners(24)).toEqual([24, 24, 24])+ corners(100).forEach((radius) => expect(radius).toBeCloseTo(40, 6))+ })+})diff --git a/packages/scene-graph/tsdown.config.ts b/packages/scene-graph/tsdown.config.tsindex 183f24190..a66b9532b 100644--- a/packages/scene-graph/tsdown.config.ts+++ b/packages/scene-graph/tsdown.config.ts@@ -25,6 +25,7 @@ export default defineConfig({matrix: './src/matrix.ts',geometry: './src/geometry.ts',gradient: './src/gradient.ts',+ polygon: './src/polygon.ts',guides: './src/guides.ts',layout: './src/layout/index.ts',resize: './src/resize.ts',diff --git a/packages/vue/src/canvas/useCanvasInput.ts b/packages/vue/src/canvas/useCanvasInput.tsindex 8d8702d74..d61903f57 100644--- a/packages/vue/src/canvas/useCanvasInput.ts+++ b/packages/vue/src/canvas/useCanvasInput.ts@@ -18,12 +18,12 @@ import {} from '#vue/canvas/vector-input/input'import { resolveAutoLayoutHover } from '#vue/shared/input/auto-layout-hover'import { createClickCounter } from '#vue/shared/input/click-count'-import { resolveCornerRadiusHover } from '#vue/shared/input/corner-radius'import { handleDrawMove } from '#vue/shared/input/draw'import { handleMoveMove, handleMoveUp } from '#vue/shared/input/move'import { setupPanZoom } from '#vue/shared/input/pan-zoom'import { applyResize, commitResizePreview } from '#vue/shared/input/resize'import { updateHoverCursor } from '#vue/shared/input/select'+import { resolveShapeHandleHover } from '#vue/shared/input/shape-handles'import { useSpaceHeld } from '#vue/shared/input/space-key'import type { DragState } from '#vue/shared/input/types'import { handleNodeEditMove } from '#vue/shared/input/vector'@@ -111,7 +111,7 @@ export function useCanvasInput(editor.setAutoLayoutHover(mode === 'off' ? resolveAutoLayoutHover(pointer.cx, pointer.cy, editor) : null)- editor.setCornerRadiusHover(resolveCornerRadiusHover(editor, pointer.sx, pointer.sy, altHeld))+ editor.setShapeHandleHover(resolveShapeHandleHover(editor, pointer.sx, pointer.sy, altHeld))}function updateModifier(code: string, held: boolean) {@@ -297,7 +297,7 @@ export function useCanvasInput(if (!drag.value) {const { cx, cy, sx, sy } = coordsupdateNodeEditHover(editor, cx, cy)- editor.setCornerRadiusHover(resolveCornerRadiusHover(editor, sx, sy, e.altKey))+ editor.setShapeHandleHover(resolveShapeHandleHover(editor, sx, sy, e.altKey))}if (!drag.value && editor.state.activeTool === 'SELECT') {@@ -327,7 +327,7 @@ export function useCanvasInput(const { sx, sy, cx, cy } = getCoords(e)- if (d.type === 'gradient' || d.type === 'corner-radius') {+ if (d.type === 'gradient' || d.type === 'shape-handle') {d.update(sx, sy, e.shiftKey)return}@@ -416,7 +416,7 @@ export function useCanvasInput(editor.commitRotation(d.nodeId, d.origRotation)}if (editor.state.rotationPreview === preview) editor.setRotationPreview(null)- } else if (d.type === 'draw' || d.type === 'gradient' || d.type === 'corner-radius') d.commit()+ } else if (d.type === 'draw' || d.type === 'gradient' || d.type === 'shape-handle') d.commit()else if (d.type === 'marquee') editor.setMarquee(null)drag.value = null@@ -428,7 +428,7 @@ export function useCanvasInput(editor.setSnapGuides([])editor.setLayoutInsertIndicator(null)editor.setDropTarget(null)- editor.setCornerRadiusHover(null)+ editor.setShapeHandleHover(null)guideInput.clearHoverAndPreview()}@@ -441,7 +441,7 @@ export function useCanvasInput(if (drag.value?.type === 'draw' ||drag.value?.type === 'gradient' ||- drag.value?.type === 'corner-radius'+ drag.value?.type === 'shape-handle') {const drawing = drag.valuedrag.value = null@@ -532,7 +532,7 @@ export function useCanvasInput(if (!drag.value) {editor.setHoveredNode(null)editor.setHoveredGuide(null)- editor.setCornerRadiusHover(null)+ editor.setShapeHandleHover(null)}})useEventListener(@@ -556,7 +556,9 @@ export function useCanvasInput(const stopPlayListeners = (['selection:changed', 'page:changed', 'graph:replaced'] as const).map((event) =>editor.onEditorEvent(event, () => {- if (drag.value?.type === 'draw' || drag.value?.type === 'rotate') cancelPointerInteraction()+ const type = drag.value?.type+ if (type === 'draw' || type === 'rotate' || type === 'shape-handle')+ cancelPointerInteraction()}))onScopeDispose(() => {diff --git a/packages/vue/src/controls/appearance/helpers.ts b/packages/vue/src/controls/appearance/helpers.tsindex 2daab6cbd..2d9bc037c 100644--- a/packages/vue/src/controls/appearance/helpers.ts+++ b/packages/vue/src/controls/appearance/helpers.ts@@ -1,3 +1,4 @@+import { compact } from 'es-toolkit'import { computed } from 'vue'import type { ComputedRef, Ref } from 'vue'@@ -12,9 +13,14 @@ const CORNER_RADIUS_TYPES = new Set(['ROUNDED_RECTANGLE','FRAME','COMPONENT',- 'INSTANCE'+ 'INSTANCE',+ 'POLYGON',+ 'STAR'])+/** A polygon's or star's corners share one radius, so Figma offers no per-corner radii for them. */+const SHARED_RADIUS_TYPES = new Set(['POLYGON', 'STAR'])+const CORNER_PATHS: CornerRadiusKey[] = ['topLeftRadius','topRightRadius',@@ -78,6 +84,10 @@ export function createAppearanceState({return node.value ? supportsCornerRadius(node.value) : false})const cornerRadiusDisabled = computed(() => isMulti.value && cornerNodes.value.length === 0)+ const splitsCorners = computed(() => {+ const targets = isMulti.value ? cornerNodes.value : compact([node.value])+ return targets.every((target) => !SHARED_RADIUS_TYPES.has(target.type))+ })const independentCorners = computed(() => {if (isMulti.value)@@ -89,7 +99,7 @@ export function createAppearanceState({})const showIndependentCorners = computed(() => {- if (isMulti.value) return false+ if (isMulti.value || !splitsCorners.value) return falseconst selected = node.valuereturn selected? expandedCornerNodeId?.value === selected.id ||@@ -105,18 +115,50 @@ export function createAppearanceState({0)const selected = node.value- return selected && cornersHaveEquivalentBindings(selected) && !hasUnequalCorners(selected)+ return selected &&+ splitsCorners.value &&+ cornersHaveEquivalentBindings(selected) &&+ !hasUnequalCorners(selected)? selected.topLeftRadius: (selected?.cornerRadius ?? 0)})const cornerRadiusBindingPaths = computed<Array<CornerRadiusKey | 'cornerRadius'>>(() => {const selected = node.value- return selected && cornersHaveEquivalentBindings(selected) && !hasUnequalCorners(selected)+ return selected &&+ splitsCorners.value &&+ cornersHaveEquivalentBindings(selected) &&+ !hasUnequalCorners(selected)? CORNER_PATHS: ['cornerRadius']})+ // Figma shows a polygon's or star's point count, and a star's inner ratio, while every selected+ // layer has one.+ const selectedNodes = computed(() => (isMulti.value ? nodes.value : compact([node.value])))+ const hasPointCount = computed(+ () =>+ selectedNodes.value.length > 0 &&+ selectedNodes.value.every((target) => SHARED_RADIUS_TYPES.has(target.type))+ )+ const hasStarRatio = computed(+ () =>+ selectedNodes.value.length > 0 &&+ selectedNodes.value.every((target) => target.type === 'STAR')+ )+ const pointCount = computed(() =>+ sharedValue(+ selectedNodes.value.map((target) => target.pointCount),+ 0+ )+ )+ const starRatioPercent = computed(() =>+ sharedValue(+ selectedNodes.value.map((target) => Math.round(target.starInnerRadius * 1000) / 10),+ 0+ )+ )+const cornerSmoothingPercent = computed(() => {const value = isMulti.value? sharedValue(@@ -146,6 +188,11 @@ export function createAppearanceState({return {hasCornerRadius,cornerRadiusDisabled,+ splitsCorners,+ hasPointCount,+ hasStarRatio,+ pointCount,+ starRatioPercent,independentCorners,showIndependentCorners,cornerRadiusValue,diff --git a/packages/vue/src/i18n/locales/de/editor.json b/packages/vue/src/i18n/locales/de/editor.jsonindex 9005e9449..fe92a82da 100644--- a/packages/vue/src/i18n/locales/de/editor.json+++ b/packages/vue/src/i18n/locales/de/editor.json@@ -2,6 +2,8 @@"toolOptions": "Optionen für {tool}","removeGradientStop": "Farbverlaufspunkt entfernen","cornerRadius": "Radius",+ "pointCount": "Anzahl",+ "starRatio": "Verhältnis","showUI": "UI anzeigen ({shortcut})","previewing": "Vorschau","resetPreview": "Zurücksetzen",diff --git a/packages/vue/src/i18n/locales/de/panels.json b/packages/vue/src/i18n/locales/de/panels.jsonindex 7264588ac..e870d5b0f 100644--- a/packages/vue/src/i18n/locales/de/panels.json+++ b/packages/vue/src/i18n/locales/de/panels.json@@ -380,6 +380,8 @@"opacity": "Deckkraft","radius": "Radius","cornerSmoothing": "Eckenglättung",+ "pointCount": "Anzahl",+ "starRatio": "Verhältnis","spread": "Ausbreitung","foregroundBlur": "Vordergrund-Weichzeichnung","strokeType": "Linientyp",diff --git a/packages/vue/src/i18n/locales/es/editor.json b/packages/vue/src/i18n/locales/es/editor.jsonindex e00623c09..b5628a962 100644--- a/packages/vue/src/i18n/locales/es/editor.json+++ b/packages/vue/src/i18n/locales/es/editor.json@@ -2,6 +2,8 @@"toolOptions": "Opciones de {tool}","removeGradientStop": "Eliminar parada de degradado","cornerRadius": "Redondeado",+ "pointCount": "Cantidad",+ "starRatio": "Proporción","showUI": "Mostrar interfaz ({shortcut})","previewing": "Vista previa","resetPreview": "Restablecer",diff --git a/packages/vue/src/i18n/locales/es/panels.json b/packages/vue/src/i18n/locales/es/panels.jsonindex ca07aeb1b..8b570d153 100644--- a/packages/vue/src/i18n/locales/es/panels.json+++ b/packages/vue/src/i18n/locales/es/panels.json@@ -33,6 +33,8 @@"opacity": "Opacidad","radius": "Redondeado","cornerSmoothing": "Suavizado de esquinas",+ "pointCount": "Cantidad",+ "starRatio": "Proporción","spread": "Esparcimiento","fill": "Relleno","stroke": "Trazo",diff --git a/packages/vue/src/i18n/locales/fr/editor.json b/packages/vue/src/i18n/locales/fr/editor.jsonindex 274a2adbb..6ec64aad5 100644--- a/packages/vue/src/i18n/locales/fr/editor.json+++ b/packages/vue/src/i18n/locales/fr/editor.json@@ -2,6 +2,8 @@"toolOptions": "Options de {tool}","removeGradientStop": "Supprimer le point de dégradé","cornerRadius": "Rayon",+ "pointCount": "Nombre",+ "starRatio": "Rapport","showUI": "Afficher l’interface ({shortcut})","previewing": "Aperçu","resetPreview": "Réinitialiser",diff --git a/packages/vue/src/i18n/locales/fr/panels.json b/packages/vue/src/i18n/locales/fr/panels.jsonindex 55bca6350..14458614f 100644--- a/packages/vue/src/i18n/locales/fr/panels.json+++ b/packages/vue/src/i18n/locales/fr/panels.json@@ -380,6 +380,8 @@"opacity": "Opacité","radius": "Rayon","cornerSmoothing": "Lissage des coins",+ "pointCount": "Nombre",+ "starRatio": "Rapport","spread": "Diffusion","foregroundBlur": "Flou de premier plan","strokeType": "Type de contour",diff --git a/packages/vue/src/i18n/locales/it/editor.json b/packages/vue/src/i18n/locales/it/editor.jsonindex 374b6be83..d01d28792 100644--- a/packages/vue/src/i18n/locales/it/editor.json+++ b/packages/vue/src/i18n/locales/it/editor.json@@ -2,6 +2,8 @@"toolOptions": "Opzioni di {tool}","removeGradientStop": "Rimuovi punto sfumatura","cornerRadius": "Raggio",+ "pointCount": "Numero",+ "starRatio": "Rapporto","showUI": "Mostra interfaccia ({shortcut})","previewing": "Anteprima","resetPreview": "Ripristina",diff --git a/packages/vue/src/i18n/locales/it/panels.json b/packages/vue/src/i18n/locales/it/panels.jsonindex e16abed6d..ea96ce543 100644--- a/packages/vue/src/i18n/locales/it/panels.json+++ b/packages/vue/src/i18n/locales/it/panels.json@@ -380,6 +380,8 @@"opacity": "Opacità","radius": "Raggio","cornerSmoothing": "Smussatura degli angoli",+ "pointCount": "Numero",+ "starRatio": "Rapporto","spread": "Diffusione","foregroundBlur": "Sfocatura primo piano","strokeType": "Tipo tratto",diff --git a/packages/vue/src/i18n/locales/ja/editor.json b/packages/vue/src/i18n/locales/ja/editor.jsonindex 737bd642e..5d121dd69 100644--- a/packages/vue/src/i18n/locales/ja/editor.json+++ b/packages/vue/src/i18n/locales/ja/editor.json@@ -2,6 +2,8 @@"toolOptions": "{tool}のオプション","removeGradientStop": "グラデーション停止点を削除","cornerRadius": "角丸",+ "pointCount": "数",+ "starRatio": "比率","showUI": "UIを表示 ({shortcut})","previewing": "プレビュー中","resetPreview": "リセット",diff --git a/packages/vue/src/i18n/locales/ja/panels.json b/packages/vue/src/i18n/locales/ja/panels.jsonindex d1b32031b..5ea5b6b25 100644--- a/packages/vue/src/i18n/locales/ja/panels.json+++ b/packages/vue/src/i18n/locales/ja/panels.json@@ -33,6 +33,8 @@"opacity": "不透明度","radius": "角丸","cornerSmoothing": "コーナーの滑らかさ",+ "pointCount": "数",+ "starRatio": "比率","spread": "スプレッド","fill": "塗り","stroke": "線",diff --git a/packages/vue/src/i18n/locales/pl/editor.json b/packages/vue/src/i18n/locales/pl/editor.jsonindex 3ef129542..7798daabd 100644--- a/packages/vue/src/i18n/locales/pl/editor.json+++ b/packages/vue/src/i18n/locales/pl/editor.json@@ -2,6 +2,8 @@"toolOptions": "Opcje narzędzia {tool}","removeGradientStop": "Usuń punkt gradientu","cornerRadius": "Promień",+ "pointCount": "Liczba",+ "starRatio": "Proporcja","showUI": "Pokaż interfejs ({shortcut})","previewing": "Podgląd","resetPreview": "Resetuj",diff --git a/packages/vue/src/i18n/locales/pl/panels.json b/packages/vue/src/i18n/locales/pl/panels.jsonindex 18aed632c..7ffb13c48 100644--- a/packages/vue/src/i18n/locales/pl/panels.json+++ b/packages/vue/src/i18n/locales/pl/panels.json@@ -386,6 +386,8 @@"opacity": "Krycie","radius": "Promień","cornerSmoothing": "Wygładzanie narożników",+ "pointCount": "Liczba",+ "starRatio": "Proporcja","spread": "Rozproszenie","foregroundBlur": "Rozmycie pierwszego planu","strokeType": "Typ obrysu",diff --git a/packages/vue/src/i18n/locales/ru/editor.json b/packages/vue/src/i18n/locales/ru/editor.jsonindex c5b4685d6..b77178bc6 100644--- a/packages/vue/src/i18n/locales/ru/editor.json+++ b/packages/vue/src/i18n/locales/ru/editor.json@@ -2,6 +2,8 @@"toolOptions": "Параметры инструмента «{tool}»","removeGradientStop": "Удалить точку градиента","cornerRadius": "Радиус",+ "pointCount": "Количество",+ "starRatio": "Соотношение","showUI": "Показать интерфейс ({shortcut})","previewing": "Просмотр","resetPreview": "Сбросить",diff --git a/packages/vue/src/i18n/locales/ru/panels.json b/packages/vue/src/i18n/locales/ru/panels.jsonindex a3cc95e6c..0026018a0 100644--- a/packages/vue/src/i18n/locales/ru/panels.json+++ b/packages/vue/src/i18n/locales/ru/panels.json@@ -386,6 +386,8 @@"opacity": "Непрозрачность","radius": "Радиус","cornerSmoothing": "Сглаживание углов",+ "pointCount": "Количество",+ "starRatio": "Соотношение","spread": "Размах","foregroundBlur": "Размытие переднего плана","strokeType": "Тип обводки",diff --git a/packages/vue/src/i18n/locales/zh-cn/editor.json b/packages/vue/src/i18n/locales/zh-cn/editor.jsonindex 74bd3c519..712baa3be 100644--- a/packages/vue/src/i18n/locales/zh-cn/editor.json+++ b/packages/vue/src/i18n/locales/zh-cn/editor.json@@ -2,6 +2,8 @@"toolOptions": "{tool}选项","removeGradientStop": "删除渐变色标","cornerRadius": "圆角",+ "pointCount": "数量",+ "starRatio": "比例","showUI": "显示界面({shortcut})","previewing": "预览中","resetPreview": "重置",diff --git a/packages/vue/src/i18n/locales/zh-cn/panels.json b/packages/vue/src/i18n/locales/zh-cn/panels.jsonindex b4cc0480a..73791b3b6 100644--- a/packages/vue/src/i18n/locales/zh-cn/panels.json+++ b/packages/vue/src/i18n/locales/zh-cn/panels.json@@ -374,6 +374,8 @@"opacity": "不透明度","radius": "圆角","cornerSmoothing": "圆角平滑度",+ "pointCount": "数量",+ "starRatio": "比例","spread": "扩展","foregroundBlur": "前景模糊","strokeType": "描边类型",diff --git a/packages/vue/src/i18n/messages/editor.ts b/packages/vue/src/i18n/messages/editor.tsindex 71543c84e..0ec164af3 100644--- a/packages/vue/src/i18n/messages/editor.ts+++ b/packages/vue/src/i18n/messages/editor.ts@@ -7,6 +7,10 @@ export const editorMessageDefaults = {removeGradientStop: 'Remove gradient stop',/** The word before a corner's radius in the label beside a dragged radius handle. */cornerRadius: 'Radius',+ /** The word before a polygon's or star's point count beside its dragged handle. */+ pointCount: 'Count',+ /** The word before a star's inner ratio beside its dragged handle. */+ starRatio: 'Ratio',showUI: params('Show UI ({shortcut})'),previewing: 'Previewing',startPreview: params('Preview ({shortcut})'),diff --git a/packages/vue/src/i18n/messages/panels.ts b/packages/vue/src/i18n/messages/panels.tsindex 00d89b82f..3d195a563 100644--- a/packages/vue/src/i18n/messages/panels.ts+++ b/packages/vue/src/i18n/messages/panels.ts@@ -128,6 +128,10 @@ export const panelMessageDefaults = {blendMode: 'Blend mode',radius: 'Radius',cornerSmoothing: 'Corner smoothing',+ /** A polygon's sides or a star's points. */+ pointCount: 'Count',+ /** A star's inner radius as a share of its outer one. */+ starRatio: 'Ratio',spread: 'Spread',page: 'Page',diff --git a/packages/vue/src/primitives/AppearanceControls/AppearanceControlsRoot.vue b/packages/vue/src/primitives/AppearanceControls/AppearanceControlsRoot.vueindex 78703f64e..610f34691 100644--- a/packages/vue/src/primitives/AppearanceControls/AppearanceControlsRoot.vue+++ b/packages/vue/src/primitives/AppearanceControls/AppearanceControlsRoot.vue@@ -24,6 +24,11 @@ const actions = {:active="ctx.active.value":has-corner-radius="ctx.hasCornerRadius.value":corner-radius-disabled="ctx.cornerRadiusDisabled.value"+ :splits-corners="ctx.splitsCorners.value"+ :has-point-count="ctx.hasPointCount.value"+ :has-star-ratio="ctx.hasStarRatio.value"+ :point-count="ctx.pointCount.value"+ :star-ratio-percent="ctx.starRatioPercent.value":independent-corners="ctx.independentCorners.value":show-independent-corners="ctx.showIndependentCorners.value":corner-radius-value="ctx.cornerRadiusValue.value"diff --git a/packages/vue/src/primitives/AppearanceControls/types.ts b/packages/vue/src/primitives/AppearanceControls/types.tsindex 26ceb3395..74f59b4a0 100644--- a/packages/vue/src/primitives/AppearanceControls/types.ts+++ b/packages/vue/src/primitives/AppearanceControls/types.ts@@ -24,6 +24,15 @@ export interface AppearanceControlsRootSlotProps {hasCornerRadius: boolean/** A multi-selection with no layer that has corners shows the radius disabled, as Figma does. */cornerRadiusDisabled: boolean+ /** Whether the corners can take separate radii; a polygon's or star's share one. */+ splitsCorners: boolean+ /** Whether every selected layer is a polygon or star, which has a point count. */+ hasPointCount: boolean+ /** Whether every selected layer is a star, which has an inner ratio. */+ hasStarRatio: boolean+ pointCount: MixedValue<number>+ /** A star's inner radius as a percentage of its outer radius, to one decimal. */+ starRatioPercent: MixedValue<number>independentCorners: MixedValue<boolean>showIndependentCorners: booleancornerRadiusValue: MixedValue<number>diff --git a/packages/vue/src/shared/input/corner-radius.ts b/packages/vue/src/shared/input/corner-radius.tsdeleted file mode 100644index d74d2ad68..000000000--- a/packages/vue/src/shared/input/corner-radius.ts+++ /dev/null@@ -1,101 +0,0 @@-import type { CornerRadiusHover, Editor } from '@open-pencil/core/editor'-import {- cornerRadiusAtPoint,- cornerRadiusChanges,- cornerRadiusHandleLayout,- createSceneGeometry,- dragsSingleCorner,- hitTestCornerRadiusHandles-} from '@open-pencil/core/geometry'--import { editorMessages } from '#vue/i18n/messages/editor'-import { isPastPointerDragThreshold } from '#vue/shared/input/drag-threshold'-import type { DragCornerRadius, DragState } from '#vue/shared/input/types'--/** Figma leaves the radius alone until the pointer has moved this far from the handle. */-const RADIUS_DRAG_THRESHOLD_PX = 5--/**- * The corner radius handles to show for the pointer at a screen point: those of the only selected- * rectangle while the pointer is over it or one of its handles, with the handle under the pointer.- */-export function resolveCornerRadiusHover(- editor: Editor,- sx: number,- sy: number,- altKey: boolean-): CornerRadiusHover | null {- const { state } = editor- if (- state.activeTool !== 'SELECT' ||- state.selectedIds.size !== 1 ||- state.editingTextId ||- state.nodeEditState ||- state.penState ||- state.gradientEdit- )- return null- const [id] = state.selectedIds- const node = editor.graph.getNode(id)- if (!node || node.locked) return null- const geometry = createSceneGeometry(editor.graph, state.rotationPreview)- const handles = cornerRadiusHandleLayout(node, geometry, state)- if (!handles) return null- const pointer = { x: sx, y: sy }- const corner = hitTestCornerRadiusHandles(handles, pointer)- if (!corner) {- const local = geometry.screenToLocal(node, pointer, state)- const inside =- local && local.x >= 0 && local.y >= 0 && local.x <= node.width && local.y <= node.height- if (!inside) return null- }- return {- nodeId: node.id,- single: dragsSingleCorner(node, altKey),- corner,- label: editorMessages.get().cornerRadius,- pointer- }-}--/**- * Starts dragging the corner radius handle under the pointer, if any. The radius follows the- * pointer rather than the distance dragged, Shift rounds it to tens, and each drag is one undo- * step, as in Figma desktop.- */-export function tryStartCornerRadiusDrag(- editor: Editor,- sx: number,- sy: number,- altKey: boolean,- setDrag: (drag: DragState) => void-): boolean {- const found = resolveCornerRadiusHover(editor, sx, sy, altKey)- if (!found?.corner) return false- const hover: CornerRadiusHover = found- const corner = found.corner- const preview = editor.beginNodePreview('Change corner radius')- let moved = false-- function update(screenX: number, screenY: number, shiftKey: boolean) {- moved ||= isPastPointerDragThreshold(sx, sy, screenX, screenY, RADIUS_DRAG_THRESHOLD_PX)- const node = editor.graph.getNode(hover.nodeId)- if (!moved || !node) return- const pointer = { x: screenX, y: screenY }- const local = createSceneGeometry(editor.graph).screenToLocal(node, pointer, editor.state)- if (!local) return- const radius = cornerRadiusAtPoint(node, corner, local, shiftKey)- preview.update(node.id, cornerRadiusChanges(node, corner, radius, hover.single))- editor.setCornerRadiusHover({ ...hover, pointer })- }-- const drag: DragCornerRadius = {- type: 'corner-radius',- update,- commit: () => preview.commit(),- cancel: () => preview.cancel()- }- editor.setCornerRadiusHover(hover)- setDrag(drag)- return true-}diff --git a/packages/vue/src/shared/input/select.ts b/packages/vue/src/shared/input/select.tsindex 24d90b64c..727373347 100644--- a/packages/vue/src/shared/input/select.ts+++ b/packages/vue/src/shared/input/select.ts@@ -5,7 +5,6 @@ export { updateHoverCursor } from '#vue/shared/input/select/hover'import { editedGradient, type Editor } from '@open-pencil/core/editor'import type { SceneNode } from '@open-pencil/scene-graph'-import { tryStartCornerRadiusDrag } from '#vue/shared/input/corner-radius'import { tryStartGradientDrag } from '#vue/shared/input/gradient'import { tryStartResize } from '#vue/shared/input/resize'import {@@ -14,6 +13,7 @@ import {pressesSelection,selectionIsLocked} from '#vue/shared/input/select/move'+import { tryStartShapeHandleDrag } from '#vue/shared/input/shape-handles'import type { DragState } from '#vue/shared/input/types'export interface HitTestFns {@@ -48,7 +48,7 @@ function tryStartHandleDrag(if (tryStartGradientDrag(editor, sx, sy, setDrag)) return true// An open gradient's handles replace the layer's selection handles, which then do not respond.if (editedGradient(editor.graph, editor.state.gradientEdit)) return false- if (tryStartCornerRadiusDrag(editor, sx, sy, altKey, setDrag)) return true+ if (tryStartShapeHandleDrag(editor, sx, sy, altKey, setDrag)) return trueif (tryStartRotation(cx, cy)) return trueconst resizeDrag = tryStartResize(cx, cy, editor)if (resizeDrag) setDrag(resizeDrag)diff --git a/packages/vue/src/shared/input/shape-handles.ts b/packages/vue/src/shared/input/shape-handles.tsnew file mode 100644index 000000000..3360b38fe--- /dev/null+++ b/packages/vue/src/shared/input/shape-handles.ts@@ -0,0 +1,147 @@+import type { Editor, ShapeHandleHover } from '@open-pencil/core/editor'+import {+ cornerRadiusAtPoint,+ cornerRadiusChanges,+ createSceneGeometry,+ dragsSingleCorner,+ hitTestShapeHandles,+ isRadiusHandle,+ pointCountAtPoint,+ shapeHandleLayout,+ starRatioAtPoint,+ type ShapeHandleKind+} from '@open-pencil/core/geometry'+import type { SceneNode, Vector } from '@open-pencil/scene-graph'++import { editorMessages } from '#vue/i18n/messages/editor'+import { isPastPointerDragThreshold } from '#vue/shared/input/drag-threshold'+import type { DragShapeHandle, DragState } from '#vue/shared/input/types'++/** Figma leaves the shape alone until the pointer has moved this far from the handle. */+const HANDLE_DRAG_THRESHOLD_PX = 5++function handleLabel(handle: ShapeHandleKind | null): string {+ const messages = editorMessages.get()+ if (handle === 'count') return messages.pointCount+ if (handle === 'ratio') return messages.starRatio+ return messages.cornerRadius+}++function undoLabel(handle: ShapeHandleKind): string {+ if (handle === 'count') return 'Change point count'+ if (handle === 'ratio') return 'Change star ratio'+ return 'Change corner radius'+}++/**+ * The handles to show for the pointer at a screen point: those of the only selected shape while+ * the pointer is over it or one of its handles, with the handle under the pointer.+ */+export function resolveShapeHandleHover(+ editor: Editor,+ sx: number,+ sy: number,+ altKey: boolean+): ShapeHandleHover | null {+ const { state } = editor+ if (+ state.activeTool !== 'SELECT' ||+ state.selectedIds.size !== 1 ||+ state.editingTextId ||+ state.nodeEditState ||+ state.penState ||+ state.gradientEdit+ )+ return null+ const [id] = state.selectedIds+ const node = editor.graph.getNode(id)+ if (!node || node.locked) return null+ const geometry = createSceneGeometry(editor.graph, state.rotationPreview)+ const handles = shapeHandleLayout(node, geometry, state)+ if (!handles) return null+ const pointer = { x: sx, y: sy }+ const handle = hitTestShapeHandles(handles, pointer)+ if (!handle) {+ const local = geometry.screenToLocal(node, pointer, state)+ const inside =+ local && local.x >= 0 && local.y >= 0 && local.x <= node.width && local.y <= node.height+ if (!inside) return null+ }+ return {+ nodeId: node.id,+ single: dragsSingleCorner(node, altKey),+ handle,+ label: handleLabel(handle),+ pointer+ }+}++/** The fields a handle sets for the node-local point it is dragged to. */+function handleChanges(+ node: SceneNode,+ handle: ShapeHandleKind,+ local: Vector,+ single: boolean,+ shiftKey: boolean+): Partial<SceneNode> {+ if (handle === 'count') return { pointCount: pointCountAtPoint(node, local) }+ if (handle === 'ratio') return { starInnerRadius: starRatioAtPoint(node, local) }+ const radius = cornerRadiusAtPoint(node, handle, local, shiftKey)+ return cornerRadiusChanges(node, handle, radius, single)+}++/** How far a count or ratio handle's centre lies from where it was grabbed, in the node's pixels. */+function grabOffset(editor: Editor, node: SceneNode, handle: ShapeHandleKind, screen: Vector) {+ if (isRadiusHandle(handle)) return { x: 0, y: 0 }+ const geometry = createSceneGeometry(editor.graph, editor.state.rotationPreview)+ const centre = shapeHandleLayout(node, geometry, editor.state)?.find(+ (candidate) => candidate.handle === handle+ )+ const grabbed = geometry.screenToLocal(node, screen, editor.state)+ const held = centre && geometry.screenToLocal(node, centre.point, editor.state)+ return grabbed && held ? { x: held.x - grabbed.x, y: held.y - grabbed.y } : { x: 0, y: 0 }+}++/**+ * Starts dragging the shape handle under the pointer, if any, as in Figma desktop. A radius+ * follows the pointer rather than the distance dragged and Shift rounds it to tens; the count and+ * ratio handles keep where they were grabbed. Each drag is one undo step.+ */+export function tryStartShapeHandleDrag(+ editor: Editor,+ sx: number,+ sy: number,+ altKey: boolean,+ setDrag: (drag: DragState) => void+): boolean {+ const found = resolveShapeHandleHover(editor, sx, sy, altKey)+ const start = found && editor.graph.getNode(found.nodeId)+ if (!found?.handle || !start) return false+ const hover: ShapeHandleHover = found+ const handle = found.handle+ const offset = grabOffset(editor, start, handle, { x: sx, y: sy })+ const preview = editor.beginNodePreview(undoLabel(handle))+ let moved = false++ function update(screenX: number, screenY: number, shiftKey: boolean) {+ moved ||= isPastPointerDragThreshold(sx, sy, screenX, screenY, HANDLE_DRAG_THRESHOLD_PX)+ const node = editor.graph.getNode(hover.nodeId)+ if (!moved || !node) return+ const pointer = { x: screenX, y: screenY }+ const local = createSceneGeometry(editor.graph).screenToLocal(node, pointer, editor.state)+ if (!local) return+ const target = { x: local.x + offset.x, y: local.y + offset.y }+ preview.update(node.id, handleChanges(node, handle, target, hover.single, shiftKey))+ editor.setShapeHandleHover({ ...hover, pointer })+ }++ const drag: DragShapeHandle = {+ type: 'shape-handle',+ update,+ commit: () => preview.commit(),+ cancel: () => preview.cancel()+ }+ editor.setShapeHandleHover(hover)+ setDrag(drag)+ return true+}diff --git a/packages/vue/src/shared/input/types.ts b/packages/vue/src/shared/input/types.tsindex 7c0ac074b..76b41caff 100644--- a/packages/vue/src/shared/input/types.ts+++ b/packages/vue/src/shared/input/types.ts@@ -175,17 +175,17 @@ export interface DragGradient {cancel: () => void}-/** Dragging a corner radius handle of the selected rectangle. */-export interface DragCornerRadius {- type: 'corner-radius'- /** Sets the radius under a screen point; Shift rounds it to tens. */+/** Dragging a radius, point count, or ratio handle of the selected rectangle, polygon, or star. */+export interface DragShapeHandle {+ type: 'shape-handle'+ /** Sets the value under a screen point; Shift rounds a radius to tens. */update: (screenX: number, screenY: number, shiftKey: boolean) => voidcommit: () => voidcancel: () => void}export type DragState =- | DragCornerRadius+ | DragShapeHandle| DragDraw| DragGradient| DragMovediff --git a/src/app/editor/panes/state.ts b/src/app/editor/panes/state.tsindex 4f0fa8ebc..d3da3d613 100644--- a/src/app/editor/panes/state.ts+++ b/src/app/editor/panes/state.ts@@ -39,7 +39,7 @@ export function cloneCanvasPaneState(id: string, source: CanvasPaneState): CanvadropTargetId: null,layoutInsertIndicator: null,autoLayoutHover: null,- cornerRadiusHover: null,+ shapeHandleHover: null,penState: null,penCursorX: null,penCursorY: null,diff --git a/src/boot.ts b/src/boot.tsindex cbb1ce5fd..d051ef9d7 100644--- a/src/boot.ts+++ b/src/boot.ts@@ -22,7 +22,7 @@ import router from './router'*/export async function boot(): Promise<void> {// A session of its own, so layers this window creates never share IDs with a collaborator's.- setIdSession(randomInt() >>> 0)+ setIdSession(randomInt() >>> 1)preloadFonts()const head = createHead()const app = createApp(App)diff --git a/src/components/properties/AppearanceSection.vue b/src/components/properties/AppearanceSection.vueindex 6c04b44fe..045d75d3d 100644--- a/src/components/properties/AppearanceSection.vue+++ b/src/components/properties/AppearanceSection.vue@@ -1,5 +1,6 @@<script setup lang="ts">import type { BlendMode } from '@open-pencil/scene-graph'+import { POINT_COUNT_RANGE } from '@open-pencil/scene-graph/polygon'import { AppearanceControlsRoot, MIXED, useI18n } from '@open-pencil/vue'import NumberField from '@/components/inputs/NumberField.vue'@@ -37,6 +38,11 @@ function blendModeGroups(value: BlendMode | typeof MIXED) {active,hasCornerRadius,cornerRadiusDisabled,+ splitsCorners,+ hasPointCount,+ hasStarRatio,+ pointCount,+ starRatioPercent,showIndependentCorners,cornerRadiusValue,cornerRadiusBindingPaths,@@ -142,7 +148,7 @@ function blendModeGroups(value: BlendMode | typeof MIXED) {</template></NumberField></PanelFieldGroup>- <div class="flex h-6 items-center justify-end">+ <div v-if="splitsCorners" class="flex h-6 items-center justify-end"><IconButton:label="panels.independentCornerRadii"size="xs"@@ -209,6 +215,43 @@ function blendModeGroups(value: BlendMode | typeof MIXED) {</template></PanelGrid>+ <PanelGrid v-if="hasPointCount" :columns="2" class="mt-1.5">+ <PanelFieldGroup :label="panels.pointCount">+ <NumberField+ :model-value="pointCount"+ :min="POINT_COUNT_RANGE.min"+ :max="POINT_COUNT_RANGE.max"+ :aria-label="panels.pointCount"+ data-property="pointCount"+ @update:model-value="actions.updateProp('pointCount', Math.round($event))"+ @commit="(v: number, p: number) => actions.commitProp('pointCount', Math.round(v), p)"+ >+ <template #icon>+ <icon-lucide-asterisk class="size-3" />+ </template>+ </NumberField>+ </PanelFieldGroup>+ <PanelFieldGroup v-if="hasStarRatio" :label="panels.starRatio">+ <NumberField+ suffix="%"+ :model-value="starRatioPercent"+ :min="0"+ :max="100"+ :step="0.1"+ :aria-label="panels.starRatio"+ data-property="starInnerRadius"+ @update:model-value="actions.updateProp('starInnerRadius', $event / 100)"+ @commit="+ (v: number, p: number) => actions.commitProp('starInnerRadius', v / 100, p / 100)+ "+ >+ <template #icon>+ <icon-lucide-star class="size-3" />+ </template>+ </NumberField>+ </PanelFieldGroup>+ </PanelGrid>+<PanelGrid v-if="hasCornerRadius && !cornerRadiusDisabled" :columns="2" class="mt-1.5"><PanelFieldGroup :label="panels.cornerSmoothing"><NumberFielddiff --git a/tests/e2e/canvas/corner-radius/handles-visual.spec.ts b/tests/e2e/canvas/shape-handles/handles-visual.spec.tssimilarity index 61%rename from tests/e2e/canvas/corner-radius/handles-visual.spec.tsrename to tests/e2e/canvas/shape-handles/handles-visual.spec.tsindex 8bd057b53..35323b297 100644--- a/tests/e2e/canvas/corner-radius/handles-visual.spec.ts+++ b/tests/e2e/canvas/shape-handles/handles-visual.spec.ts@@ -1,5 +1,5 @@import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'-import { cornerRadiusDriver } from '#tests/helpers/canvas/corner-radius-driver'+import { shapeHandlesDriver } from '#tests/helpers/canvas/shape-handles-driver'// Figma desktop: white handles ringed in the selection colour, at each arc's centre but at least// 12.5 px inside the corner; a dot marks a drag of one corner, and the handle under the pointer@@ -7,7 +7,7 @@ import { cornerRadiusDriver } from '#tests/helpers/canvas/corner-radius-driver'const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')-const corners = cornerRadiusDriver(() => editor.page)+const corners = shapeHandlesDriver(() => editor.page)test('equal corners', async () => {await corners.show({ cornerRadius: 20 })@@ -30,3 +30,14 @@ test('differing corners, the top-right one hovered', async () => {expect(await editor.canvas.screenshotCanvasRegion(360, 440)).toMatchSnapshot('differing.png')editor.canvas.assertNoErrors()})++test('a star under the pointer, its count handle hovered', async () => {+ await corners.show({ pointCount: 5, starInnerRadius: 0.38, cornerRadius: 8 }, 'STAR')+ const centre = corners.point(80, 90)+ await editor.canvas.hover(centre.x, centre.y)+ // The middle of the rounded point to the right of the top one, where its count handle sits.+ const count = corners.point(139, 61)+ await editor.canvas.hover(count.x, count.y)+ expect(await editor.canvas.screenshotCanvasRegion(360, 360)).toMatchSnapshot('star.png')+ editor.canvas.assertNoErrors()+})diff --git a/tests/e2e/canvas/corner-radius/handles-visual.spec.ts-snapshots/differing-openpencil-darwin.png b/tests/e2e/canvas/shape-handles/handles-visual.spec.ts-snapshots/differing-openpencil-darwin.pngsimilarity index 100%rename from tests/e2e/canvas/corner-radius/handles-visual.spec.ts-snapshots/differing-openpencil-darwin.pngrename to tests/e2e/canvas/shape-handles/handles-visual.spec.ts-snapshots/differing-openpencil-darwin.pngdiff --git a/tests/e2e/canvas/corner-radius/handles-visual.spec.ts-snapshots/equal-openpencil-darwin.png b/tests/e2e/canvas/shape-handles/handles-visual.spec.ts-snapshots/equal-openpencil-darwin.pngsimilarity index 100%rename from tests/e2e/canvas/corner-radius/handles-visual.spec.ts-snapshots/equal-openpencil-darwin.pngrename to tests/e2e/canvas/shape-handles/handles-visual.spec.ts-snapshots/equal-openpencil-darwin.pngdiff --git a/tests/e2e/canvas/shape-handles/handles-visual.spec.ts-snapshots/star-openpencil-darwin.png b/tests/e2e/canvas/shape-handles/handles-visual.spec.ts-snapshots/star-openpencil-darwin.pngnew file mode 100644index 000000000..ef059ca6eBinary files /dev/null and b/tests/e2e/canvas/shape-handles/handles-visual.spec.ts-snapshots/star-openpencil-darwin.png differdiff --git a/tests/e2e/canvas/corner-radius/handles.spec.ts b/tests/e2e/canvas/shape-handles/handles.spec.tssimilarity index 51%rename from tests/e2e/canvas/corner-radius/handles.spec.tsrename to tests/e2e/canvas/shape-handles/handles.spec.tsindex 7baafe9e9..8333ecd23 100644--- a/tests/e2e/canvas/corner-radius/handles.spec.ts+++ b/tests/e2e/canvas/shape-handles/handles.spec.ts@@ -1,5 +1,5 @@import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'-import { cornerRadiusDriver } from '#tests/helpers/canvas/corner-radius-driver'+import { shapeHandlesDriver } from '#tests/helpers/canvas/shape-handles-driver'// Figma desktop: a selected rectangle under the pointer shows a handle inside each corner.// Dragging one sets the radius whose arc centre is under the pointer, on every corner while they@@ -7,7 +7,7 @@ import { cornerRadiusDriver } from '#tests/helpers/canvas/corner-radius-driver'const editor = useEditorSetupWithClear('/?test&no-rulers')-const corners = cornerRadiusDriver(() => editor.page)+const corners = shapeHandlesDriver(() => editor.page)/*** Drags the top-left handle, which sits `inset` px inside the corner, to (at, at) of the rectangle.@@ -54,3 +54,41 @@ test('differing corners drag alone, and Alt sets them all', async () => {await dragTopLeft(24, 50, 'Alt')expect(await corners.radii(nodeId)).toEqual([50, 50, 50, 50])})++// Figma desktop: a polygon or star has one handle, below its top point, and its corners share+// the radius the handle sets, up to what fits along its edges.+test('a polygon rounds every corner from the handle below its top point', async () => {+ const nodeId = await corners.show({ pointCount: 3 }, 'POLYGON')+ const from = corners.point(80, 18)+ const to = corners.point(80, 48)+ await editor.canvas.drag(from.x, from.y, to.x, to.y)+ await editor.canvas.waitForRender()+ expect(await corners.radii(nodeId)).toEqual([24, 24, 24, 24])++ const far = corners.point(80, 400)+ await editor.canvas.drag(to.x, to.y, far.x, far.y)+ await editor.canvas.waitForRender()+ expect((await corners.radii(nodeId))?.[0]).toBeCloseTo(40, 6)+})++// Figma desktop: a star's next outer point sets its point count from the angle around its centre,+// and its first inner point its inner ratio from the distance to the centre.+test('a star changes its point count and ratio from the handles on its points', async () => {+ const nodeId = await corners.show({ pointCount: 5, starInnerRadius: 0.38 }, 'STAR')+ const angle = (degrees: number, distance: number) =>+ corners.point(+ 80 + distance * Math.sin((degrees * Math.PI) / 180),+ 80 - distance * Math.cos((degrees * Math.PI) / 180)+ )+ const count = angle(72, 80)+ const to = angle(30, 80)+ await editor.canvas.drag(count.x, count.y, to.x, to.y)+ await editor.canvas.waitForRender()+ expect((await corners.points(nodeId))?.count).toBe(12)++ const ratio = angle(15, 80 * 0.38)+ const out = angle(15, 40)+ await editor.canvas.drag(ratio.x, ratio.y, out.x, out.y)+ await editor.canvas.waitForRender()+ expect((await corners.points(nodeId))?.ratio).toBe(0.5)+})diff --git a/tests/e2e/canvas/shape-handles/polygons-visual.spec.ts b/tests/e2e/canvas/shape-handles/polygons-visual.spec.tsnew file mode 100644index 000000000..adaab9eba--- /dev/null+++ b/tests/e2e/canvas/shape-handles/polygons-visual.spec.ts@@ -0,0 +1,47 @@+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'++// Figma desktop: a polygon's or star's corners, inner ones included, round with circular arcs+// that shrink to fit along short edges, and corner smoothing eases them into the edges.++const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')++test('rounded and smoothed polygons and stars', async () => {+ await editor.page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const shapes: Array<{+ type: 'POLYGON' | 'STAR'+ pointCount: number+ cornerRadius: number+ cornerSmoothing: number+ height?: number+ }> = [+ { type: 'POLYGON', pointCount: 3, cornerRadius: 24, cornerSmoothing: 0 },+ { type: 'POLYGON', pointCount: 6, cornerRadius: 100, cornerSmoothing: 0, height: 60 },+ { type: 'STAR', pointCount: 5, cornerRadius: 10, cornerSmoothing: 0 },+ { type: 'STAR', pointCount: 5, cornerRadius: 30, cornerSmoothing: 0 },+ { type: 'POLYGON', pointCount: 3, cornerRadius: 24, cornerSmoothing: 0.6 },+ { type: 'STAR', pointCount: 5, cornerRadius: 10, cornerSmoothing: 0.6 }+ ]+ shapes.forEach(({ type, height = 160, ...corners }, index) =>+ store.graph.createNode(type, store.state.currentPageId, {+ x: (index % 3) * 180,+ y: Math.floor(index / 3) * 180,+ width: 160,+ height,+ starInnerRadius: 0.382,+ fills: [+ { type: 'SOLID', visible: true, opacity: 1, color: { r: 0.8, g: 0.6, b: 0.6, a: 1 } }+ ],+ ...corners+ })+ )+ store.state.zoom = 1+ store.state.panX = 40+ store.state.panY = 40+ store.requestRender()+ })+ await editor.canvas.waitForRender()+ expect(await editor.canvas.screenshotCanvasRegion(620, 420)).toMatchSnapshot('polygons.png')+ editor.canvas.assertNoErrors()+})diff --git a/tests/e2e/canvas/shape-handles/polygons-visual.spec.ts-snapshots/polygons-openpencil-darwin.png b/tests/e2e/canvas/shape-handles/polygons-visual.spec.ts-snapshots/polygons-openpencil-darwin.pngnew file mode 100644index 000000000..6f17f8fa4Binary files /dev/null and b/tests/e2e/canvas/shape-handles/polygons-visual.spec.ts-snapshots/polygons-openpencil-darwin.png differdiff --git a/tests/e2e/properties/corner/polygon.spec.ts b/tests/e2e/properties/corner/polygon.spec.tsnew file mode 100644index 000000000..071ab3910--- /dev/null+++ b/tests/e2e/properties/corner/polygon.spec.ts@@ -0,0 +1,62 @@+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'+import { shapeHandlesDriver } from '#tests/helpers/canvas/shape-handles-driver'+import { propertySection } from '#tests/helpers/properties'++// Figma desktop: a polygon's or star's corners share one radius, shown and edited in the panel+// with smoothing but without independent corners.++const editor = useEditorSetupWithClear('/?test&no-rulers')++const corners = shapeHandlesDriver(() => editor.page)++for (const type of ['POLYGON', 'STAR'] as const) {+ test(`a ${type.toLowerCase()} edits its one radius in the panel`, async () => {+ const nodeId = await corners.show({ pointCount: 5, cornerRadius: 12 }, type)+ await editor.canvas.waitForRender()+ const section = propertySection(editor.page, 'Appearance')+ const radius = section.getByRole('spinbutton', { name: 'Radius', exact: true })+ await expect(radius).toHaveText('12')+ await expect(section.getByRole('button', { name: 'Independent corner radii' })).toHaveCount(0)+ await expect(editor.page.locator('[data-property="corner-smoothing"]')).toBeVisible()++ await radius.focus()+ await radius.fill('20')+ await radius.press('Enter')+ await editor.canvas.waitForRender()+ expect((await corners.radii(nodeId))?.[0]).toBe(20)+ })+}++async function fill(name: string, value: string) {+ const field = propertySection(editor.page, 'Appearance').getByRole('spinbutton', {+ name,+ exact: true+ })+ await field.focus()+ await field.fill(value)+ await field.press('Enter')+ await editor.canvas.waitForRender()+}++test('a star edits its point count and inner ratio, which Figma keeps between 3 and 60', async () => {+ const nodeId = await corners.show({ pointCount: 5, starInnerRadius: 0.382 }, 'STAR')+ await editor.canvas.waitForRender()+ const section = propertySection(editor.page, 'Appearance')+ await expect(section.getByRole('spinbutton', { name: 'Count', exact: true })).toHaveText('5')+ await expect(section.getByRole('spinbutton', { name: 'Ratio', exact: true })).toHaveText(/38\.2/)++ await fill('Count', '7')+ await fill('Ratio', '50')+ expect(await corners.points(nodeId)).toEqual({ count: 7, ratio: 0.5 })++ await fill('Count', '100')+ expect((await corners.points(nodeId))?.count).toBe(60)+})++test('a polygon has a point count but no inner ratio', async () => {+ await corners.show({ pointCount: 3 }, 'POLYGON')+ await editor.canvas.waitForRender()+ const section = propertySection(editor.page, 'Appearance')+ await expect(section.getByRole('spinbutton', { name: 'Count', exact: true })).toHaveText('3')+ await expect(section.getByRole('spinbutton', { name: 'Ratio', exact: true })).toHaveCount(0)+})diff --git a/tests/engine/io/fig/import/schema-coverage.test.ts b/tests/engine/io/fig/import/schema-coverage.test.tsindex 1c7bf0a62..389f7bb33 100644--- a/tests/engine/io/fig/import/schema-coverage.test.ts+++ b/tests/engine/io/fig/import/schema-coverage.test.ts@@ -373,15 +373,15 @@ describe('Figma Kiwi schema coverage', () => {expect(Object.fromEntries([...buckets].map(([bucket, items]) => [bucket, items.length]))).toEqual({- modeled: 121,+ modeled: 123,schemaTag: 60,- internalBookkeeping: 17,+ internalBookkeeping: 16,rawPreserved: 46,styleLibraryMetadata: 38,componentInstanceMetadata: 32,textMetadata: 23,slideFigjamMetadata: 39,- visualGeometryMetadata: 38,+ visualGeometryMetadata: 37,layoutMetadata: 29,prototypeConnectorMetadata: 32,variableDevMetadata: 14,diff --git a/tests/helpers/canvas/corner-radius-driver.ts b/tests/helpers/canvas/corner-radius-driver.tsdeleted file mode 100644index 732cc0372..000000000--- a/tests/helpers/canvas/corner-radius-driver.ts+++ /dev/null@@ -1,62 +0,0 @@-import type { Page } from '@playwright/test'--import type { SceneNode } from '@open-pencil/scene-graph'--type CornerProps = Partial<- Pick<- SceneNode,- | 'cornerRadius'- | 'independentCorners'- | 'topLeftRadius'- | 'topRightRadius'- | 'bottomRightRadius'- | 'bottomLeftRadius'- >->--/** Shows a selected rectangle at 100% with its top-left 100 px into the canvas, and reads its radii. */-export function cornerRadiusDriver(page: () => Page) {- return {- /** A 160 × 232 rectangle, selected. */- show(props: CornerProps = {}) {- return page().evaluate((props) => {- const store = window.openPencil?.getStore?.()- if (!store) throw new Error('OpenPencil store not initialized')- const node = store.graph.createNode('RECTANGLE', store.state.currentPageId, {- name: 'Card',- x: 0,- y: 0,- width: 160,- height: 232,- fills: [- { type: 'SOLID', visible: true, opacity: 1, color: { r: 0.8, g: 0.6, b: 0.6, a: 1 } }- ],- ...props- })- store.select([node.id])- store.state.zoom = 1- store.state.panX = 100- store.state.panY = 100- store.requestRender()- return node.id- }, props)- },-- /** Canvas coordinates of a point in the rectangle's own pixels. */- point(x: number, y: number) {- return { x: 100 + x, y: 100 + y }- },-- /** Top-left, top-right, bottom-right, and bottom-left radii as drawn. */- radii(nodeId: string) {- return page().evaluate((id) => {- const node = window.openPencil?.getStore?.().graph.getNode(id)- if (!node) return null- const { cornerRadius: radius } = node- return node.independentCorners- ? [node.topLeftRadius, node.topRightRadius, node.bottomRightRadius, node.bottomLeftRadius]- : [radius, radius, radius, radius]- }, nodeId)- }- }-}diff --git a/tests/helpers/canvas/shape-handles-driver.ts b/tests/helpers/canvas/shape-handles-driver.tsnew file mode 100644index 000000000..3ac5a54a0--- /dev/null+++ b/tests/helpers/canvas/shape-handles-driver.ts@@ -0,0 +1,78 @@+import type { Page } from '@playwright/test'++import type { SceneNode } from '@open-pencil/scene-graph'++type CornerProps = Partial<+ Pick<+ SceneNode,+ | 'cornerRadius'+ | 'independentCorners'+ | 'topLeftRadius'+ | 'topRightRadius'+ | 'bottomRightRadius'+ | 'bottomLeftRadius'+ | 'cornerSmoothing'+ | 'pointCount'+ | 'starInnerRadius'+ >+>++type CornerShape = 'RECTANGLE' | 'POLYGON' | 'STAR'++/** Shows a selected shape at 100% with its top-left 100 px into the canvas, and reads its radii. */+export function shapeHandlesDriver(page: () => Page) {+ return {+ /** A 160 × 232 rectangle, or a 160 × 160 polygon or star, selected. */+ show(props: CornerProps = {}, type: CornerShape = 'RECTANGLE') {+ return page().evaluate(+ ({ props, type }) => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const node = store.graph.createNode(type, store.state.currentPageId, {+ name: 'Card',+ x: 0,+ y: 0,+ width: 160,+ height: type === 'RECTANGLE' ? 232 : 160,+ fills: [+ { type: 'SOLID', visible: true, opacity: 1, color: { r: 0.8, g: 0.6, b: 0.6, a: 1 } }+ ],+ ...props+ })+ store.select([node.id])+ store.state.zoom = 1+ store.state.panX = 100+ store.state.panY = 100+ store.requestRender()+ return node.id+ },+ { props, type }+ )+ },++ /** Canvas coordinates of a point in the rectangle's own pixels. */+ point(x: number, y: number) {+ return { x: 100 + x, y: 100 + y }+ },++ /** Top-left, top-right, bottom-right, and bottom-left radii as drawn. */+ radii(nodeId: string) {+ return page().evaluate((id) => {+ const node = window.openPencil?.getStore?.().graph.getNode(id)+ if (!node) return null+ const { cornerRadius: radius } = node+ return node.independentCorners+ ? [node.topLeftRadius, node.topRightRadius, node.bottomRightRadius, node.bottomLeftRadius]+ : [radius, radius, radius, radius]+ }, nodeId)+ },++ /** A polygon's or star's point count and a star's inner ratio. */+ points(nodeId: string) {+ return page().evaluate((id) => {+ const node = window.openPencil?.getStore?.().graph.getNode(id)+ return node ? { count: node.pointCount, ratio: node.starInnerRadius } : null+ }, nodeId)+ }+ }+}