AI-native design editor. Open-source Figma alternative.
feat(canvas): edit gradients on the canvas as Figma does (#1031)
Danila Poyarkov1d15d455f2f5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 203a65924..3a3eb2b78 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -41,6 +41,7 @@### Added+- 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.- Show the pixel grid when zoomed in, as in Figma: from 800% on a standard display and 400% on a Retina one, toggled with **View → Pixel Grid** or <kbd>⇧</kbd><kbd>'</kbd>. <kbd>⇧</kbd><kbd>⌘</kbd><kbd>'</kbd> toggles **Snap to Pixel Grid**. The zoom menu in the properties panel lists both, with Figma's shortcuts, and labels its shortcuts for zoom to fit (<kbd>⇧</kbd><kbd>1</kbd>) and 100% (<kbd>⌘</kbd><kbd>0</kbd>); <kbd>⇧</kbd><kbd>R</kbd> toggles rulers and <kbd>⌥</kbd><kbd>⌘</kbd><kbd>\\</kbd> multiplayer cursors.- Set a component's text, boolean, and swap properties on a design JSX `<Instance>` by name, as variants are set, such as `<Instance of="Card" Title="Hello" Badge={false} />`; `properties` accepts names too. An instance written this way still works after the document is saved to `.fig` and reopened, which gives each property a new ID ([#750](https://github.com/open-pencil/open-pencil/issues/750)).@@ -143,6 +144,7 @@### Fixed+- Gradient stops in the fill picker show their full position and opacity, such as 100%, instead of cutting them off; each stop's colour, hex, and opacity share one field as in the properties panel.- Keep design variable bindings and honor `replace_id` and `insert_index` when `render` runs through the stdio MCP server (`openpencil-mcp`) against the desktop or web app, as it already did through the HTTP endpoint (#830).- Draw layers masked by a group, such as Figma's clip path groups, instead of hiding them; a group used as a mask masks with what its layers draw.- Import SVG files that start with an XML declaration or doctype, such as Illustrator and Inkscape exports, instead of reporting no supported elements.diff --git a/packages/core/src/canvas/overlays/gradient-handles.ts b/packages/core/src/canvas/overlays/gradient-handles.tsnew file mode 100644index 000000000..734219196--- /dev/null+++ b/packages/core/src/canvas/overlays/gradient-handles.ts@@ -0,0 +1,142 @@+import type { Canvas, Path } from 'canvaskit-wasm'++import type { Color, SceneGraph, Vector } from '@open-pencil/scene-graph'++import { getCachedMaskBlur } from '#core/canvas/effects'+import type { SkiaRenderer } from '#core/canvas/renderer'+import { editedGradient, editedGradientLayout } from '#core/editor/gradient-edit'+import type { GradientEdit } from '#core/editor/types'+import { GRADIENT_HANDLE, type GradientHandleLayout, type RotationPreview } from '#core/geometry'++/** Colours measured on Figma desktop 126's gradient handles. */+const SELECTED_BORDER = { r: 0x4b / 255, g: 0x9e / 255, b: 0xf4 / 255 }+const STOP_BORDER = { r: 0xd0 / 255, g: 0xd0 / 255, b: 0xd0 / 255 }+const SHADOW_ALPHA = 0.35+const SHADOW_BLUR = 1+const POINTER_HALF_WIDTH = 3++function polyline(r: SkiaRenderer, points: readonly Vector[], close: boolean) {+ const path = new r.ck.PathBuilder()+ points.forEach((point, index) =>+ index === 0 ? path.moveTo(point.x, point.y) : path.lineTo(point.x, point.y)+ )+ if (close) path.close()+ return path.detachAndDelete()+}++/** The angular gradient's ellipse: a unit circle mapped onto its two axes. */+function ellipsePath(r: SkiaRenderer, ellipse: NonNullable<GradientHandleLayout['ellipse']>) {+ const { center, radiusX, radiusY } = ellipse+ const path = new r.ck.PathBuilder()+ path.addOval(r.ck.LTRBRect(-1, -1, 1, 1))+ path.transform([+ radiusX.x - center.x,+ radiusY.x - center.x,+ center.x,+ radiusX.y - center.y,+ radiusY.y - center.y,+ center.y,+ 0,+ 0,+ 1+ ])+ return path.detachAndDelete()+}++/** A white 1 px line over a soft shadow, as Figma draws the gradient's axis and ellipse. */+function strokeWithShadow(r: SkiaRenderer, canvas: Canvas, path: Path) {+ const paint = r.auxStroke+ paint.setPathEffect(null)+ paint.setStrokeWidth(1)+ paint.setMaskFilter(getCachedMaskBlur(r, SHADOW_BLUR))+ paint.setColor(r.ck.Color4f(0, 0, 0, SHADOW_ALPHA))+ canvas.drawPath(path, paint)+ paint.setMaskFilter(null)+ paint.setColor(r.ck.Color4f(1, 1, 1, 1))+ canvas.drawPath(path, paint)+ path.delete()+}++function drawDot(r: SkiaRenderer, canvas: Canvas, point: Vector) {+ const paint = r.auxFill+ paint.setMaskFilter(getCachedMaskBlur(r, SHADOW_BLUR))+ paint.setColor(r.ck.Color4f(0, 0, 0, SHADOW_ALPHA))+ canvas.drawCircle(point.x, point.y + 0.5, GRADIENT_HANDLE.dotRadius, paint)+ paint.setMaskFilter(null)+ paint.setColor(r.ck.Color4f(1, 1, 1, 1))+ canvas.drawCircle(point.x, point.y, GRADIENT_HANDLE.dotRadius, paint)+}++/** The stop's square: a 2 px border, a 1 px white ring, its colour, and a pointer to its spot. */+function drawStop(+ r: SkiaRenderer,+ canvas: Canvas,+ stop: GradientHandleLayout['stops'][number],+ color: Color,+ selected: boolean+) {+ const half = GRADIENT_HANDLE.stopSize / 2+ const border = selected ? SELECTED_BORDER : STOP_BORDER+ const paint = r.auxFill+ paint.setMaskFilter(null)+ paint.setColor(r.ck.Color4f(border.r, border.g, border.b, 1))+ // The pointer leaves the square's edge facing the spot it marks.+ const { center, pointing } = stop+ const edge = {+ x: center.x + pointing.x * half,+ y: center.y + pointing.y * half+ }+ const across = { x: -pointing.y, y: pointing.x }+ const tip = {+ x: edge.x + pointing.x * POINTER_HALF_WIDTH,+ y: edge.y + pointing.y * POINTER_HALF_WIDTH+ }+ const pointer = polyline(+ r,+ [+ { x: edge.x + across.x * POINTER_HALF_WIDTH, y: edge.y + across.y * POINTER_HALF_WIDTH },+ tip,+ { x: edge.x - across.x * POINTER_HALF_WIDTH, y: edge.y - across.y * POINTER_HALF_WIDTH }+ ],+ true+ )+ canvas.drawPath(pointer, paint)+ pointer.delete()+ const rect = (inset: number) =>+ r.ck.LTRBRect(+ center.x - half + inset,+ center.y - half + inset,+ center.x + half - inset,+ center.y + half - inset+ )+ canvas.drawRect(rect(0), paint)+ paint.setColor(r.ck.Color4f(1, 1, 1, 1))+ canvas.drawRect(rect(2), paint)+ paint.setColor(r.ck.Color4f(color.r, color.g, color.b, color.a))+ canvas.drawRect(rect(3), paint)+}++/** Figma's on-canvas gradient handles, for the paint whose picker is open. */+export function drawGradientHandles(+ r: SkiaRenderer,+ canvas: Canvas,+ graph: SceneGraph,+ edit: GradientEdit | null | undefined,+ preview?: RotationPreview | null+): void {+ const layout = editedGradientLayout(graph, edit, r, preview)+ const edited = editedGradient(graph, edit)+ if (!layout || !edited || !edit) return+ if (layout.ellipse) strokeWithShadow(r, canvas, ellipsePath(r, layout.ellipse))+ strokeWithShadow(r, canvas, polyline(r, [layout.line.from, layout.line.to], false))+ for (const dot of layout.dots) drawDot(r, canvas, dot.point)+ const stops = edited.paint.gradientStops ?? []+ // The selected stop draws last, over any square it overlaps.+ const order = [...layout.stops].sort(+ (a, b) => Number(a.index === edit.stop) - Number(b.index === edit.stop)+ )+ for (const stop of order) {+ const color = stops.at(stop.index)?.color+ if (color) drawStop(r, canvas, stop, color, stop.index === edit.stop)+ }+}diff --git a/packages/core/src/canvas/renderer/overlay-pass.ts b/packages/core/src/canvas/renderer/overlay-pass.tsindex c77e5f3f6..ce9b59ee2 100644--- a/packages/core/src/canvas/renderer/overlay-pass.ts+++ b/packages/core/src/canvas/renderer/overlay-pass.ts@@ -7,6 +7,7 @@ import { drawIssueHighlight, drawIssueMarkers } from '#core/canvas/issues/draw'import { layoutIssueMarkers } from '#core/canvas/issues/layout'import { drawComponentSetBorders } from '#core/canvas/overlays/component-sets'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'@@ -14,6 +15,7 @@ import { drawCodeFocus } from '#core/canvas/overlays/selection'import { drawSlotOutlines } from '#core/canvas/overlays/slots'import type { RenderOverlays, SkiaRenderer } from '#core/canvas/renderer'import { RULER_SIZE } from '#core/constants'+import { editedGradient } from '#core/editor/gradient-edit'function measurementVisible(overlays: RenderOverlays): boolean {return (@@ -112,7 +114,11 @@ export function drawOverlayPass(drawDropTarget(r, canvas, graph, overlays.dropTargetId, overlays.rotationPreview)drawEditingText(r, canvas, graph, overlays)r.profiler.beginPhase('render:selection')- r.drawSelection(canvas, graph, selectedIds, overlays)+ // While a gradient is edited, Figma shows its handles instead of the layer's selection; a+ // previewing canvas shows neither.+ if (!overlays.playing && editedGradient(graph, overlays.gradientEdit))+ drawGradientHandles(r, canvas, graph, overlays.gradientEdit, overlays.rotationPreview)+ else r.drawSelection(canvas, graph, selectedIds, overlays)if (measuring) r.drawMeasurements(canvas, graph, selectedIds, overlays.hoveredNodeId)r.profiler.endPhase('render:selection')diff --git a/packages/core/src/canvas/renderer/pipeline.ts b/packages/core/src/canvas/renderer/pipeline.tsindex 45d572ba2..931e5536d 100644--- a/packages/core/src/canvas/renderer/pipeline.ts+++ b/packages/core/src/canvas/renderer/pipeline.ts@@ -86,6 +86,7 @@ export function renderFromEditorState(playIslands: previewing ? new Set(playIslandRoots(graph, state.currentPageId)) : undefined,hoveredNodeId: previewing ? null : state.hoveredNodeId,showPixelGrid: !previewing && state.showPixelGrid !== false,+ gradientEdit: state.gradientEdit,transforming: state.transforming,measurementMode: state.measurementMode,enteredContainerId: state.enteredContainerId,diff --git a/packages/core/src/canvas/renderer/types.ts b/packages/core/src/canvas/renderer/types.tsindex c360a109b..142a0d713 100644--- a/packages/core/src/canvas/renderer/types.ts+++ b/packages/core/src/canvas/renderer/types.ts@@ -4,6 +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 { GradientEdit } from '#core/editor/types'import type { RotationPreview } from '#core/geometry'import type { TextEditor } from '#core/text/editor'@@ -40,6 +41,8 @@ export interface RenderOverlays {hoveredNodeId?: string | null/** Draw the pixel grid when zoomed in far enough. */showPixelGrid?: boolean+ /** The gradient whose handles to draw in place of the selection. */+ gradientEdit?: GradientEdit | nulltransforming?: booleanmeasurementMode?: MeasurementModeenteredContainerId?: string | nulldiff --git a/packages/core/src/editor/gradient-edit.ts b/packages/core/src/editor/gradient-edit.tsnew file mode 100644index 000000000..29c29c271--- /dev/null+++ b/packages/core/src/editor/gradient-edit.ts@@ -0,0 +1,42 @@+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'++import {+ createSceneGeometry,+ gradientHandleLayout,+ isGradientFill,+ type GradientHandleLayout,+ type RotationPreview,+ type ViewportTransform+} from '#core/geometry'++import type { GradientEdit } from './types'++/** The gradient paint being edited and the layer it belongs to, if it is still a gradient. */+export function editedGradient(graph: SceneGraph, edit: GradientEdit | null | undefined) {+ if (!edit) return null+ const node = graph.getNode(edit.nodeId)+ const paint = node?.[edit.paint][edit.index]+ if (!node || !paint || !isGradientFill(paint.type) || !paint.gradientTransform) return null+ return { node, paint, type: paint.type, transform: paint.gradientTransform }+}++/** Where the edited gradient's handles sit on screen. */+export function editedGradientLayout(+ graph: SceneGraph,+ edit: GradientEdit | null | undefined,+ viewport: ViewportTransform,+ preview?: RotationPreview | null+): GradientHandleLayout | null {+ const edited = editedGradient(graph, edit)+ if (!edited) return null+ const geometry = createSceneGeometry(graph, preview)+ const node: SceneNode = edited.node+ return gradientHandleLayout(+ edited.type,+ edited.transform,+ edited.paint.gradientStops ?? [],+ node.width,+ node.height,+ (local) => geometry.toScreen(node, local, viewport)+ )+}diff --git a/packages/core/src/editor/index.ts b/packages/core/src/editor/index.tsindex 3747a1280..ec4a3475a 100644--- a/packages/core/src/editor/index.ts+++ b/packages/core/src/editor/index.ts@@ -7,6 +7,7 @@ export type { NodeEditCapability } from './capabilities'export { DEFAULT_SNAPPING_PREFERENCES } from './preferences'export type { SnappingPreferences } from './preferences'export { createDefaultEditorSharedState } from './state/shared'+export { editedGradient, editedGradientLayout } from './gradient-edit'export {copyEditorViewState,createDefaultEditorViewState,@@ -49,5 +50,6 @@ export type {EditorSharedState,EditorViewState,FigmaClipboardImageResolver,+ GradientEdit,Tool} from './types'diff --git a/packages/core/src/editor/state/shared.ts b/packages/core/src/editor/state/shared.tsindex 1571f590f..4993861a9 100644--- a/packages/core/src/editor/state/shared.ts+++ b/packages/core/src/editor/state/shared.ts@@ -6,6 +6,7 @@ export function createDefaultEditorSharedState(): EditorSharedState {activeTool: 'SELECT',snappingPreferences: { ...DEFAULT_SNAPPING_PREFERENCES },showPixelGrid: true,+ gradientEdit: null,presenceCursors: [],documentName: 'Untitled',designIssues: null,diff --git a/packages/core/src/editor/types.ts b/packages/core/src/editor/types.tsindex c3b888161..c376a9f59 100644--- a/packages/core/src/editor/types.ts+++ b/packages/core/src/editor/types.ts@@ -38,11 +38,22 @@ export type Tool =| 'PEN'| 'HAND'+/** The gradient whose handles the canvas shows while its paint picker is open. */+export interface GradientEdit {+ nodeId: string+ paint: 'fills' | 'strokes'+ index: number+ /** The selected stop, shared by the canvas handles and the picker. */+ stop: number+}+export interface EditorSharedState {activeTool: ToolsnappingPreferences: SnappingPreferences/** Draw the pixel grid once zoomed in far enough, as Figma's View › Pixel grid; shown unless false. */showPixelGrid?: boolean+ /** The gradient being edited, whose handles the canvas draws and drags. */+ gradientEdit?: GradientEdit | nullpresenceCursors: PresenceCursor[]documentName: string/** Design check markers and highlight, shared by every canvas pane. */diff --git a/packages/core/src/geometry/gradient.ts b/packages/core/src/geometry/gradient.tsnew file mode 100644index 000000000..2c1161fc0--- /dev/null+++ b/packages/core/src/geometry/gradient.ts@@ -0,0 +1,299 @@+import type { Fill, GradientStop, GradientTransform, Vector } from '@open-pencil/scene-graph'++/**+ * On-canvas gradient handles, as Figma desktop 126 draws and drags them. A gradient's transform+ * maps gradient space into the layer's unit square; a linear gradient runs from (1, 0) to (0, 0)+ * of gradient space, the others are centred on (0.5, 0.5) with radius 0.5.+ */++export type GradientHandle = 'start' | 'end' | 'center' | 'radius-x' | 'radius-y'+export type GradientFillType = Extract<+ Fill['type'],+ 'GRADIENT_LINEAR' | 'GRADIENT_RADIAL' | 'GRADIENT_ANGULAR' | 'GRADIENT_DIAMOND'+>++export interface GradientHandles {+ start: Vector+ end: Vector+ center: Vector+ /** The second axis of a radial, angular, or diamond gradient. */+ radiusY?: Vector+}++/** Figma's 15° steps while Shift is held. */+const SNAP_ANGLE = Math.PI / 12++export function isGradientFill(type: Fill['type']): type is GradientFillType {+ return (+ type === 'GRADIENT_LINEAR' ||+ type === 'GRADIENT_RADIAL' ||+ type === 'GRADIENT_ANGULAR' ||+ type === 'GRADIENT_DIAMOND'+ )+}++function point(t: GradientTransform, width: number, height: number, x: number, y: number) {+ return {+ x: (t.m00 * x + t.m01 * y + t.m02) * width,+ y: (t.m10 * x + t.m11 * y + t.m12) * height+ }+}++/** The handles in the layer's own pixels. */+export function gradientHandles(+ type: GradientFillType,+ t: GradientTransform,+ width: number,+ height: number+): GradientHandles {+ if (type === 'GRADIENT_LINEAR') {+ const start = point(t, width, height, 1, 0)+ const end = point(t, width, height, 0, 0)+ return { start, end, center: { x: (start.x + end.x) / 2, y: (start.y + end.y) / 2 } }+ }+ const center = point(t, width, height, 0.5, 0.5)+ return {+ start: center,+ end: point(t, width, height, 1, 0.5),+ center,+ radiusY: point(t, width, height, 0.5, 1)+ }+}++/** Where a stop sits in the layer's pixels: on the line, or on the ellipse for an angular one. */+export function gradientStopPoint(+ type: GradientFillType,+ t: GradientTransform,+ width: number,+ height: number,+ position: number+): Vector {+ if (type === 'GRADIENT_ANGULAR') {+ const angle = position * 2 * Math.PI+ return point(t, width, height, 0.5 + 0.5 * Math.cos(angle), 0.5 + 0.5 * Math.sin(angle))+ }+ const { start, end } = gradientHandles(type, t, width, height)+ return { x: start.x + (end.x - start.x) * position, y: start.y + (end.y - start.y) * position }+}++/** The stop position nearest a point in the layer's pixels, from 0 to 1. */+export function gradientStopPosition(+ type: GradientFillType,+ t: GradientTransform,+ width: number,+ height: number,+ local: Vector+): number {+ if (type === 'GRADIENT_ANGULAR') {+ const det = t.m00 * t.m11 - t.m01 * t.m10+ if (Math.abs(det) < 1e-12 || width <= 0 || height <= 0) return 0+ const ux = local.x / width - t.m02+ const uy = local.y / height - t.m12+ const gx = (t.m11 * ux - t.m01 * uy) / det+ const gy = (-t.m10 * ux + t.m00 * uy) / det+ const turn = Math.atan2(gy - 0.5, gx - 0.5) / (2 * Math.PI)+ return turn < 0 ? turn + 1 : turn+ }+ const { start, end } = gradientHandles(type, t, width, height)+ const dx = end.x - start.x+ const dy = end.y - start.y+ const length = dx * dx + dy * dy+ if (length < 1e-12) return 0+ const along = ((local.x - start.x) * dx + (local.y - start.y) * dy) / length+ return Math.min(1, Math.max(0, along))+}++function snapDirection(origin: Vector, position: Vector, snap: boolean): Vector {+ if (!snap) return position+ const dx = position.x - origin.x+ const dy = position.y - origin.y+ const angle = Math.round(Math.atan2(dy, dx) / SNAP_ANGLE) * SNAP_ANGLE+ const length = Math.hypot(dx, dy)+ return { x: origin.x + Math.cos(angle) * length, y: origin.y + Math.sin(angle) * length }+}++/**+ * The transform after dragging one handle to a point in the layer's pixels. Only that handle+ * moves, exactly with the pointer; Shift turns its direction in 15° steps and keeps its length.+ */+export function moveGradientHandle(+ type: GradientFillType,+ original: GradientTransform,+ width: number,+ height: number,+ handle: GradientHandle,+ position: Vector,+ snap = false+): GradientTransform {+ if (width <= 0 || height <= 0) return original+ const handles = gradientHandles(type, original, width, height)+ if (handle === 'center') {+ return {+ ...original,+ m02: original.m02 + (position.x - handles.center.x) / width,+ m12: original.m12 + (position.y - handles.center.y) / height+ }+ }+ if (type === 'GRADIENT_LINEAR') {+ const start = handle === 'start' ? snapDirection(handles.end, position, snap) : handles.start+ const end = handle === 'end' ? snapDirection(handles.start, position, snap) : handles.end+ if (Math.hypot(start.x - end.x, start.y - end.y) < 0.001) return original+ return {+ ...original,+ m00: (start.x - end.x) / width,+ m10: (start.y - end.y) / height,+ m01: -(start.y - end.y) / height,+ m11: (start.x - end.x) / width,+ m02: end.x / width,+ m12: end.y / height+ }+ }+ const center = handles.center+ let radiusX = handles.end+ let radiusY = handles.radiusY ?? center+ if (handle === 'radius-x' || handle === 'end') {+ radiusX = snapDirection(center, position, snap)+ // The second axis turns with the first, as in Figma.+ const angle =+ Math.atan2(radiusX.y - center.y, radiusX.x - center.x) -+ Math.atan2(handles.end.y - center.y, handles.end.x - center.x)+ const dx = radiusY.x - center.x+ const dy = radiusY.y - center.y+ radiusY = {+ x: center.x + dx * Math.cos(angle) - dy * Math.sin(angle),+ y: center.y + dx * Math.sin(angle) + dy * Math.cos(angle)+ }+ } else if (handle === 'radius-y') {+ radiusY = snapDirection(center, position, snap)+ }+ const m00 = (2 * (radiusX.x - center.x)) / width+ const m10 = (2 * (radiusX.y - center.y)) / height+ const m01 = (2 * (radiusY.x - center.x)) / width+ const m11 = (2 * (radiusY.y - center.y)) / height+ if (Math.abs(m00 * m11 - m01 * m10) < 1e-8) return original+ return {+ m00,+ m01,+ m10,+ m11,+ m02: center.x / width - (m00 + m01) / 2,+ m12: center.y / height - (m10 + m11) / 2+ }+}++/** Screen-pixel sizes of the handles, measured on Figma desktop 126. */+export const GRADIENT_HANDLE = {+ /** Stop squares, including their 2 px border and 1 px white ring. */+ stopSize: 24,+ /** From the square's edge to the point it marks, where its pointer ends. */+ stopGap: 5.5,+ dotRadius: 4+} as const++export interface GradientStopLayout {+ index: number+ /** The point on the line or ellipse the stop marks. */+ anchor: Vector+ /** The centre of its square. */+ center: Vector+ /** Unit vector from the square towards its anchor. */+ pointing: Vector+}++export interface GradientHandleLayout {+ type: GradientFillType+ dots: Array<{ handle: GradientHandle; point: Vector }>+ line: { from: Vector; to: Vector }+ /** The angular gradient's ellipse: centre and its two axis ends. */+ ellipse?: { center: Vector; radiusX: Vector; radiusY: Vector }+ stops: GradientStopLayout[]+}++/**+ * Where the handles of a gradient sit on screen, for drawing and for hit testing alike.+ * `toScreen` maps a point in the layer's pixels to screen pixels.+ */+export function gradientHandleLayout(+ type: GradientFillType,+ t: GradientTransform,+ stops: readonly GradientStop[],+ width: number,+ height: number,+ toScreen: (local: Vector) => Vector+): GradientHandleLayout {+ const local = gradientHandles(type, t, width, height)+ const start = toScreen(local.start)+ const end = toScreen(local.end)+ const center = toScreen(local.center)+ const radiusY = local.radiusY ? toScreen(local.radiusY) : undefined+ const offset = GRADIENT_HANDLE.stopGap + GRADIENT_HANDLE.stopSize / 2+ const along = { x: end.x - start.x, y: end.y - start.y }+ const length = Math.hypot(along.x, along.y) || 1+ // Above a left-to-right line: the left-hand normal of its direction.+ const above = { x: along.y / length, y: -along.x / length }+ const stopLayouts = stops.map((stop, index): GradientStopLayout => {+ const anchor = toScreen(gradientStopPoint(type, t, width, height, stop.position))+ let outward = above+ if (type === 'GRADIENT_ANGULAR') {+ const dx = anchor.x - center.x+ const dy = anchor.y - center.y+ const distance = Math.hypot(dx, dy) || 1+ outward = { x: dx / distance, y: dy / distance }+ }+ return {+ index,+ anchor,+ center: { x: anchor.x + outward.x * offset, y: anchor.y + outward.y * offset },+ pointing: { x: -outward.x, y: -outward.y }+ }+ })+ if (type === 'GRADIENT_LINEAR') {+ return {+ type,+ dots: [+ { handle: 'start', point: start },+ { handle: 'end', point: end }+ ],+ line: { from: start, to: end },+ stops: stopLayouts+ }+ }+ return {+ type,+ dots: [+ { handle: 'center', point: center },+ { handle: 'radius-x', point: end },+ ...(radiusY ? [{ handle: 'radius-y' as const, point: radiusY }] : [])+ ],+ line: { from: center, to: end },+ ellipse: type === 'GRADIENT_ANGULAR' && radiusY ? { center, radiusX: end, radiusY } : undefined,+ stops: stopLayouts+ }+}++export type GradientHit =+ | { kind: 'handle'; handle: GradientHandle }+ | { kind: 'stop'; index: number }++/** The handle under a screen point: squares first, then dots, then the line next to a stop. */+export function hitTestGradientHandles(+ layout: GradientHandleLayout,+ screen: Vector+): GradientHit | null {+ const half = GRADIENT_HANDLE.stopSize / 2+ for (let index = layout.stops.length - 1; index >= 0; index--) {+ const stop = layout.stops[index]+ if (Math.abs(screen.x - stop.center.x) <= half && Math.abs(screen.y - stop.center.y) <= half)+ return { kind: 'stop', index: stop.index }+ }+ for (const dot of layout.dots) {+ if (Math.hypot(screen.x - dot.point.x, screen.y - dot.point.y) <= GRADIENT_HANDLE.dotRadius + 3)+ return { kind: 'handle', handle: dot.handle }+ }+ // Pressing the line beside a stop takes that stop, as in Figma.+ for (const stop of layout.stops) {+ if (Math.hypot(screen.x - stop.anchor.x, screen.y - stop.anchor.y) <= half)+ return { kind: 'stop', index: stop.index }+ }+ return null+}diff --git a/packages/core/src/geometry/index.ts b/packages/core/src/geometry/index.tsindex 5bb082610..9af821b6f 100644--- a/packages/core/src/geometry/index.ts+++ b/packages/core/src/geometry/index.ts@@ -5,6 +5,24 @@ export {panelRotation,panelRotationChange} from './figma'+export {+ GRADIENT_HANDLE,+ gradientHandleLayout,+ gradientHandles,+ gradientStopPoint,+ gradientStopPosition,+ hitTestGradientHandles,+ isGradientFill,+ moveGradientHandle+} from './gradient'+export type {+ GradientFillType,+ GradientHandle,+ GradientHandleLayout,+ GradientHandles,+ GradientHit,+ GradientStopLayout+} from './gradient'export { createSceneGeometry, nodeOrientationMatrix, projectedNode, viewportMatrix } from './scene'export type { SceneGeometry } from './scene'export { selectionPath, selectionHandleRect, rotationHandleLayout } from './selection'diff --git a/packages/core/tests/geometry/gradient.test.ts b/packages/core/tests/geometry/gradient.test.tsnew file mode 100644index 000000000..68e80b6da--- /dev/null+++ b/packages/core/tests/geometry/gradient.test.ts@@ -0,0 +1,112 @@+import { describe, expect, test } from 'bun:test'++import {+ gradientHandleLayout,+ gradientHandles,+ gradientStopPosition,+ hitTestGradientHandles,+ moveGradientHandle+} from '#core/geometry'+import type { Vector } from '@open-pencil/scene-graph'++// A 200 × 140 layer with a linear gradient from its left edge's middle to its right edge's middle.+const LEFT_TO_RIGHT = { m00: -1, m01: 0, m02: 1, m10: 0, m11: -1, m12: 0.5 }+const STOPS = [+ { position: 0, color: { r: 1, g: 0, b: 0, a: 1 } },+ { position: 0.5, color: { r: 1, g: 1, b: 0, a: 1 } },+ { position: 1, color: { r: 0, g: 0, b: 1, a: 1 } }+]++function close(actual: Vector, expected: Vector) {+ expect(actual.x).toBeCloseTo(expected.x, 6)+ expect(actual.y).toBeCloseTo(expected.y, 6)+}++describe('gradient handles', () => {+ test('a linear gradient runs between its two end dots', () => {+ const handles = gradientHandles('GRADIENT_LINEAR', LEFT_TO_RIGHT, 200, 140)+ close(handles.start, { x: 0, y: 70 })+ close(handles.end, { x: 200, y: 70 })+ })++ // Figma desktop 126: dragging the end moves only the end, exactly with the pointer.+ test('dragging an end moves only that end', () => {+ const moved = moveGradientHandle('GRADIENT_LINEAR', LEFT_TO_RIGHT, 200, 140, 'end', {+ x: 200,+ y: 10+ })+ const handles = gradientHandles('GRADIENT_LINEAR', moved, 200, 140)+ close(handles.start, { x: 0, y: 70 })+ close(handles.end, { x: 200, y: 10 })+ })++ // Figma desktop 126: the pointer at −10.2° from the start lands on −15°, at the pointer's distance.+ test('Shift turns an end in 15° steps and keeps its distance', () => {+ const pointer = { x: 195.5, y: 35 }+ const moved = moveGradientHandle(+ 'GRADIENT_LINEAR',+ LEFT_TO_RIGHT,+ 200,+ 140,+ 'end',+ pointer,+ true+ )+ const { start, end } = gradientHandles('GRADIENT_LINEAR', moved, 200, 140)+ const angle = (Math.atan2(end.y - start.y, end.x - start.x) * 180) / Math.PI+ expect(angle).toBeCloseTo(-15, 6)+ expect(Math.hypot(end.x - start.x, end.y - start.y)).toBeCloseTo(+ Math.hypot(pointer.x, pointer.y - 70),+ 6+ )+ })++ test('a stop slides to where the pointer projects onto the line, within its ends', () => {+ expect(gradientStopPosition('GRADIENT_LINEAR', LEFT_TO_RIGHT, 200, 140, { x: 150, y: 3 })).toBe(+ 0.75+ )+ expect(gradientStopPosition('GRADIENT_LINEAR', LEFT_TO_RIGHT, 200, 140, { x: -40, y: 70 })).toBe(+ 0+ )+ })++ test('an angular stop follows the pointer around the centre', () => {+ const centred = { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }+ // Straight below the centre is a quarter turn, as the sweep runs clockwise from the right.+ expect(+ gradientStopPosition('GRADIENT_ANGULAR', centred, 200, 140, { x: 100, y: 130 })+ ).toBeCloseTo(0.25, 6)+ expect(+ gradientStopPosition('GRADIENT_ANGULAR', centred, 200, 140, { x: 100, y: 10 })+ ).toBeCloseTo(0.75, 6)+ })++ // Figma desktop 126 puts the squares on the left of the line's run from the first stop to the+ // last: above a left-to-right gradient, below a right-to-left one, right of a top-to-bottom one.+ test('stop squares sit on the left of the run from the first stop to the last', () => {+ const screen = (point: Vector) => point+ const above = gradientHandleLayout('GRADIENT_LINEAR', LEFT_TO_RIGHT, STOPS, 200, 140, screen)+ expect(above.stops[1]?.center.y).toBeLessThan(70)+ // Its first stop at the right edge and its last at the left.+ const reversed = { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0.5 }+ const below = gradientHandleLayout('GRADIENT_LINEAR', reversed, STOPS, 200, 140, screen)+ expect(below.stops[1]?.center.y).toBeGreaterThan(70)+ // Its first stop at the top edge and its last at the bottom.+ const downward = { m00: 0, m01: 1, m02: 0.5, m10: -1, m11: 0, m12: 1 }+ const right = gradientHandleLayout('GRADIENT_LINEAR', downward, STOPS, 200, 140, screen)+ expect(right.stops[1]?.center.x).toBeGreaterThan(100)+ })++ test('a press takes a stop square before an end dot', () => {+ const screen = (point: Vector) => point+ const layout = gradientHandleLayout('GRADIENT_LINEAR', LEFT_TO_RIGHT, STOPS, 200, 140, screen)+ const square = layout.stops[2]?.center+ if (!square) throw new Error('Expected a stop square')+ expect(hitTestGradientHandles(layout, square)).toEqual({ kind: 'stop', index: 2 })+ expect(hitTestGradientHandles(layout, { x: 0, y: 72 })).toEqual({+ kind: 'handle',+ handle: 'start'+ })+ expect(hitTestGradientHandles(layout, { x: 50, y: 120 })).toBeNull()+ })+})diff --git a/packages/docs/user-guide/drawing-shapes.md b/packages/docs/user-guide/drawing-shapes.mdindex 66f1ea6e2..cbebeadba 100644--- a/packages/docs/user-guide/drawing-shapes.md+++ b/packages/docs/user-guide/drawing-shapes.md@@ -42,7 +42,7 @@ After drawing a shape, select it to edit its properties in the Design tab of theEvery shape can have a fill. The fill section supports:- **Solid color** — pick via the HSV color picker or type a hex value-- **Gradient** — Linear, Radial, Angular, or Diamond with editable gradient stops+- **Gradient** — Linear, Radial, Angular, or Diamond with editable gradient stops. While the gradient's picker is open, the canvas shows its handles: drag an end or a radius dot to move it, hold <kbd>Shift</kbd> to turn it in 15° steps, and drag a stop's square to slide the stop along the line- **Image** — select an image file as the fill### Strokediff --git a/packages/vue/src/canvas/useCanvasInput.ts b/packages/vue/src/canvas/useCanvasInput.tsindex 0f46283c3..200e9d150 100644--- a/packages/vue/src/canvas/useCanvasInput.ts+++ b/packages/vue/src/canvas/useCanvasInput.ts@@ -324,6 +324,11 @@ export function useCanvasInput(const { sx, sy, cx, cy } = getCoords(e)+ if (d.type === 'gradient') {+ d.update(sx, sy, e.shiftKey)+ return+ }+if (d.type === 'guide') {const frameId = e.altKey && !d.guideId ? selectedTopLevelGuideFrameId(editor) : nullguideInput.handleMove(@@ -408,7 +413,7 @@ export function useCanvasInput(editor.commitRotation(d.nodeId, d.origRotation)}if (editor.state.rotationPreview === preview) editor.setRotationPreview(null)- } else if (d.type === 'draw') d.commit()+ } else if (d.type === 'draw' || d.type === 'gradient') d.commit()else if (d.type === 'marquee') editor.setMarquee(null)drag.value = null@@ -429,7 +434,7 @@ export function useCanvasInput(drag.value = nullif (editor.state.rotationPreview?.nodeId === rotation.nodeId) editor.setRotationPreview(null)}- if (drag.value?.type === 'draw') {+ if (drag.value?.type === 'draw' || drag.value?.type === 'gradient') {const drawing = drag.valuedrag.value = nulldrawing.cancel()@@ -486,7 +491,8 @@ export function useCanvasInput('keydown',(event) => {if (event.code !== 'Escape' || event.isComposing || !isEnabled()) return- if (drag.value?.type !== 'draw' && drag.value?.type !== 'rotate') return+ const type = drag.value?.type+ if (type !== 'draw' && type !== 'gradient' && type !== 'rotate') returnevent.preventDefault()event.stopImmediatePropagation()cancelPointerInteraction()diff --git a/packages/vue/src/primitives/GradientEditor/GradientEditorRoot.vue b/packages/vue/src/primitives/GradientEditor/GradientEditorRoot.vueindex aa4c0d823..88f0821c5 100644--- a/packages/vue/src/primitives/GradientEditor/GradientEditorRoot.vue+++ b/packages/vue/src/primitives/GradientEditor/GradientEditorRoot.vue@@ -1,5 +1,5 @@<script setup lang="ts">-import { computed } from 'vue'+import { computed, watch } from 'vue'import type { Fill } from '@open-pencil/scene-graph'@@ -7,6 +7,8 @@ import { useGradientStops } from '#vue/primitives/GradientEditor/useGradientStopconst { fill } = defineProps<{ fill: Fill }>()const emit = defineEmits<{ update: [fill: Fill] }>()+/** The selected stop, which the canvas handles can also change. */+const selectedStop = defineModel<number>('activeStopIndex')const {activeStopIndex,@@ -29,6 +31,17 @@ const {(updated) => emit('update', updated))+watch(+ selectedStop,+ (index) => {+ if (index !== undefined && index !== activeStopIndex.value) activeStopIndex.value = index+ },+ { immediate: true }+)+watch(activeStopIndex, (index) => {+ if (index !== selectedStop.value) selectedStop.value = index+})+const actions = {setSubtype,selectStop,diff --git a/packages/vue/src/shared/input/gradient.ts b/packages/vue/src/shared/input/gradient.tsnew file mode 100644index 000000000..75f5e7f19--- /dev/null+++ b/packages/vue/src/shared/input/gradient.ts@@ -0,0 +1,96 @@+import { editedGradient, editedGradientLayout, type Editor } from '@open-pencil/core/editor'+import {+ createSceneGeometry,+ gradientStopPosition,+ hitTestGradientHandles,+ moveGradientHandle+} from '@open-pencil/core/geometry'+import type { Fill } from '@open-pencil/scene-graph'++import type { DragGradient, DragState } from '#vue/shared/input/types'++/**+ * Starts dragging a handle or stop of the gradient whose picker is open, if one is under the+ * pointer. Handles move exactly with the pointer, Shift turns them in 15° steps, and a stop slides+ * along the line or around the ellipse; each drag is one undo step, as in Figma desktop 126.+ */+export function tryStartGradientDrag(+ editor: Editor,+ sx: number,+ sy: number,+ setDrag: (drag: DragState) => void+): boolean {+ const edit = editor.state.gradientEdit+ const edited = editedGradient(editor.graph, edit)+ const layout = editedGradientLayout(editor.graph, edit, editor.state)+ if (!edit || !edited || !layout) return false+ const found = hitTestGradientHandles(layout, { x: sx, y: sy })+ if (!found) return false+ const hit = found+ const { paint: paintKey, index: paintIndex } = edit++ const { node, type } = edited+ const original: Fill = structuredClone(edited.paint)+ const originalStop = edit.stop+ if (hit.kind === 'stop') editor.state.gradientEdit = { ...edit, stop: hit.index }+ const preview = editor.beginNodePreview('Edit gradient')++ function paintsWith(paint: Fill): Fill[] {+ const paints = editor.graph.getNode(node.id)?.[paintKey] ?? []+ return paints.map((current, index) => (index === paintIndex ? paint : current))+ }++ function update(screenX: number, screenY: number, shiftKey: boolean) {+ const current = editor.graph.getNode(node.id)+ const transform = original.gradientTransform+ if (!current || !transform) return+ const local = createSceneGeometry(editor.graph).screenToLocal(+ current,+ { x: screenX, y: screenY },+ editor.state+ )+ if (!local) return+ if (hit.kind === 'handle') {+ const moved = moveGradientHandle(+ type,+ transform,+ current.width,+ current.height,+ hit.handle,+ local,+ shiftKey+ )+ preview.update(node.id, {+ [paintKey]: paintsWith({ ...original, gradientTransform: moved })+ })+ return+ }+ const position = gradientStopPosition(type, transform, current.width, current.height, local)+ const moving = original.gradientStops?.[hit.index]+ if (!moving) return+ // Stops stay in order, so the moved one may change places with its neighbours.+ const stops = (original.gradientStops ?? [])+ .map((stop, index) => (index === hit.index ? { ...stop, position } : stop))+ .map((stop, index) => ({ stop, index }))+ .sort((a, b) => a.stop.position - b.stop.position)+ const stop = stops.findIndex((entry) => entry.index === hit.index)+ preview.update(node.id, {+ [paintKey]: paintsWith({ ...original, gradientStops: stops.map((entry) => entry.stop) })+ })+ const latest = editor.state.gradientEdit+ if (latest) editor.state.gradientEdit = { ...latest, stop }+ }++ const drag: DragGradient = {+ type: 'gradient',+ update,+ commit: () => preview.commit(),+ cancel: () => {+ preview.cancel()+ const latest = editor.state.gradientEdit+ if (latest) editor.state.gradientEdit = { ...latest, stop: originalStop }+ }+ }+ setDrag(drag)+ return true+}diff --git a/packages/vue/src/shared/input/select.ts b/packages/vue/src/shared/input/select.tsindex f2af663be..d402a6f6e 100644--- a/packages/vue/src/shared/input/select.ts+++ b/packages/vue/src/shared/input/select.ts@@ -2,9 +2,10 @@ import { getNodeEditState, handleNodeEditDown } from '#vue/shared/input/vector'export { resolveHit } from '#vue/shared/input/select/hit'import { resolveHit } from '#vue/shared/input/select/hit'export { updateHoverCursor } from '#vue/shared/input/select/hover'-import type { Editor } from '@open-pencil/core/editor'+import { editedGradient, type Editor } from '@open-pencil/core/editor'import type { SceneNode } from '@open-pencil/scene-graph'+import { tryStartGradientDrag } from '#vue/shared/input/gradient'import { tryStartResize } from '#vue/shared/input/resize'import {createSelectionMoveDrag,@@ -29,6 +30,25 @@ function startMarquee(cx: number, cy: number, editor: Editor, setDrag: (d: DragSsetDrag({ type: 'marquee', startX: cx, startY: cy, containerId: container?.id })}+/** Starts dragging a gradient handle, or else the selection's rotation or resize handles. */+function tryStartHandleDrag(+ cx: number,+ cy: number,+ sx: number,+ sy: number,+ editor: Editor,+ tryStartRotation: (cx: number, cy: number) => boolean,+ setDrag: (d: DragState) => void+): boolean {+ 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 (tryStartRotation(cx, cy)) return true+ const resizeDrag = tryStartResize(cx, cy, editor)+ if (resizeDrag) setDrag(resizeDrag)+ return resizeDrag !== null+}+export function handleSelectDown(e: MouseEvent,cx: number,@@ -51,13 +71,7 @@ export function handleSelectDown(if (editor.state.editingTextId) editor.commitTextEdit()- if (tryStartRotation(cx, cy)) return-- const resizeDrag = tryStartResize(cx, cy, editor)- if (resizeDrag) {- setDrag(resizeDrag)- return- }+ if (tryStartHandleDrag(cx, cy, sx, sy, editor, tryStartRotation, setDrag)) returnconst hit = resolveHit(cx, cy, editor, fns, e.metaKey || e.ctrlKey)if (!hit) {diff --git a/packages/vue/src/shared/input/types.ts b/packages/vue/src/shared/input/types.tsindex 7a7ce0e75..3810adfcf 100644--- a/packages/vue/src/shared/input/types.ts+++ b/packages/vue/src/shared/input/types.ts@@ -166,8 +166,18 @@ export interface DragGuide {originalPosition?: number}+/** Dragging a handle or stop of the gradient whose picker is open. */+export interface DragGradient {+ type: 'gradient'+ /** Moves the dragged handle or stop to a screen point. */+ update: (screenX: number, screenY: number, shiftKey: boolean) => void+ commit: () => void+ cancel: () => void+}+export type DragState =| DragDraw+ | DragGradient| DragMove| DragPan| DragResizediff --git a/src/components/fill-picker/FillPicker.vue b/src/components/fill-picker/FillPicker.vueindex ebc2f5b52..0227283ec 100644--- a/src/components/fill-picker/FillPicker.vue+++ b/src/components/fill-picker/FillPicker.vue@@ -1,5 +1,6 @@<script setup lang="ts">import { PopoverContent, PopoverPortal, PopoverRoot, PopoverTrigger } from 'reka-ui'+import type { FocusOutsideEvent, PointerDownOutsideEvent } from 'reka-ui'import { tv } from 'tailwind-variants'import type { Fill } from '@open-pencil/scene-graph'@@ -23,14 +24,18 @@ function tabClass(active: boolean) {const {fill,okhcl = null,- swatchBackground+ swatchBackground,+ keepOpen} = defineProps<{fill: Fillokhcl?: OkHCLControls | nullswatchBackground?: string/** Names the trigger for a paint that is not a fill, such as a stroke. */label?: string+ /** Whether a press outside the picker should leave it open, such as on a gradient handle. */+ keepOpen?: (event: PointerEvent) => boolean}>()+const activeStop = defineModel<number>('activeStop')const emit = defineEmits<{update: [fill: Fill]openChange: [open: boolean]@@ -43,6 +48,17 @@ const { open: popupOpen, portalActive } = useRetainedPopup(undefined, () => {const cls = usePopoverUI({ content: 'w-60 p-2' })const { panels } = useI18n()+/** Dragging a gradient handle on the canvas leaves the picker open, as in Figma. */+function keepOpenOnPress(event: PointerDownOutsideEvent) {+ if (keepOpen?.(event.detail.originalEvent)) event.preventDefault()+}++/** A press focuses the canvas before the press itself reaches the picker, so the press decides. */+function keepOpenOnFocus(event: FocusOutsideEvent) {+ if (keepOpen && event.detail.originalEvent.target instanceof HTMLCanvasElement)+ event.preventDefault()+}+function cancelFromEscape(event: KeyboardEvent) {event.stopPropagation()emit('cancel')@@ -75,6 +91,8 @@ function cancelFromEscape(event: KeyboardEvent) {side="left"data-picker-content@escape-key-down="cancelFromEscape"+ @pointer-down-outside="keepOpenOnPress"+ @focus-outside="keepOpenOnFocus"><div class="mb-2 flex items-center gap-0.5"><Tip :label="panels.solid">@@ -118,6 +136,7 @@ function cancelFromEscape(event: KeyboardEvent) {<GradientEditorv-if="root.category === 'GRADIENT'"+ v-model:active-stop="activeStop":fill="root.fill"@update="emit('update', $event)"/>diff --git a/src/components/fill-picker/GradientEditor.vue b/src/components/fill-picker/GradientEditor.vueindex 1e84bcc8a..ea2bb2572 100644--- a/src/components/fill-picker/GradientEditor.vue+++ b/src/components/fill-picker/GradientEditor.vue@@ -13,12 +13,14 @@ import {import ColorPickerPanel from '@/components/color-picker-panel/ColorPickerPanel.vue'import NumberField from '@/components/inputs/NumberField.vue'+import PaintField from '@/components/inputs/PaintField.vue'import IconButton from '@/components/ui/button/IconButton.vue'import AppSelect from '@/components/ui/select/AppSelect.vue'import fillPickerTheme from '@/theme/fill-picker'const { fill } = defineProps<{ fill: Fill }>()const emit = defineEmits<{ update: [fill: Fill] }>()+const activeStop = defineModel<number>('activeStop')const { panels, editor } = useI18n()const fillPicker = tv(fillPickerTheme)@@ -32,7 +34,12 @@ function listStopClass(active: boolean) {</script><template>- <GradientEditorRoot :fill="fill" @update="emit('update', $event)" v-slot="root">+ <GradientEditorRoot+ v-model:active-stop-index="activeStop"+ :fill="fill"+ @update="emit('update', $event)"+ v-slot="root"+ ><div><div class="mb-2 w-28"><AppSelect@@ -97,7 +104,8 @@ function listStopClass(active: boolean) {v-slot="s"><NumberField- class="w-11"+ class="w-14 flex-none"+ :ui="{ leading: 'hidden', field: 'pl-1.5', display: 'pl-1.5' }"suffix="%":model-value="s.positionPercent":min="0"@@ -105,27 +113,29 @@ function listStopClass(active: boolean) {@update:model-value="s.actions.updatePosition(Number($event))"@click.stop/>- <button- class="size-4 shrink-0 cursor-pointer rounded border border-border p-0"- :style="{ background: s.css }"- @click.stop="s.actions.select"- />- <input- class="min-w-0 flex-1 rounded border border-border bg-input px-1 py-0.5 font-mono text-[11px] text-surface"- :value="s.hex"- maxlength="6"- @change="s.actions.updateColor(inputValue($event))"+ <PaintField+ :opacity="s.opacityPercent / 100"+ :opacity-label="panels.opacity"+ @update:opacity="s.actions.updateOpacity($event * 100)"@click.stop- />- <NumberField- class="w-9"- suffix="%"- :model-value="s.opacityPercent"- :min="0"- :max="100"- @update:model-value="s.actions.updateOpacity(Number($event))"- @click.stop- />+ >+ <template #preview>+ <button+ class="size-4 shrink-0 cursor-pointer rounded border border-border p-0"+ :style="{ background: s.css }"+ @click.stop="s.actions.select"+ />+ </template>+ <template #value>+ <input+ class="min-w-0 flex-1 border-none bg-transparent font-mono text-[11px] text-surface outline-none"+ :value="s.hex"+ maxlength="6"+ @change="s.actions.updateColor(inputValue($event))"+ @click.stop+ />+ </template>+ </PaintField><IconButtonv-if="root.stops.length > 2":label="editor.removeGradientStop"diff --git a/src/components/properties/paint/PaintField.vue b/src/components/inputs/PaintField.vuesimilarity index 100%rename from src/components/properties/paint/PaintField.vuerename to src/components/inputs/PaintField.vuediff --git a/src/components/properties/FillSection.vue b/src/components/properties/FillSection.vueindex df565cc1d..6da22582f 100644--- a/src/components/properties/FillSection.vue+++ b/src/components/properties/FillSection.vue@@ -12,6 +12,7 @@ import {import type { BindableValueActions } from '@open-pencil/vue'import FillPicker from '@/components/fill-picker/FillPicker.vue'+import PaintField from '@/components/inputs/PaintField.vue'import VariableBindingPicker from '@/components/properties/binding/VariableBindingPicker.vue'import {commitDiscretePropertyListChange,@@ -25,8 +26,8 @@ import {commitPaintMutation,paintBindingTargets} from '@/components/properties/paint/binding'+import { useGradientEditing } from '@/components/properties/paint/gradient-edit'import { createFillOkhclAdapter } from '@/components/properties/paint/okhcl'-import PaintField from '@/components/properties/paint/PaintField.vue'import PaintValue from '@/components/properties/paint/PaintValue.vue'import PropertyListRoot from '@/components/properties/PropertyListRoot.vue'import { useSharedStylePicker } from '@/components/properties/shared-style/useSharedStylePicker'@@ -37,6 +38,18 @@ import AppSelect from '@/components/ui/select/AppSelect.vue'const fillCtx = useFillControls()const okhcl = useOkHCL()+const gradients = useGradientEditing()++/** Opening a paint's picker shows its gradient handles on the canvas; closing commits the edit. */+function onPickerOpenChange(+ nodeIds: readonly string[],+ index: number,+ open: boolean,+ binding: BindableValueActions<Color>+) {+ gradients.setOpen(gradients.target(nodeIds, 'fills', index), open)+ if (!open) commitPaintMutation(binding)+}const colorProvider = useColorBindingProvider()const { panels, common } = useI18n()const blendModeOptions = useBlendModeOptions()@@ -136,12 +149,17 @@ function updateSolidColor(<FillPicker:fill="displayFill(fill, binding.resolvedValue)":okhcl="createFillOkhclAdapter(okhcl, activeNode, index)"+ :keep-open="gradients.pressesHandle"+ :active-stop="gradients.stop(gradients.target(selectedNodeIds, 'fills', index))"+ @update:active-stop="+ gradients.setStop(gradients.target(selectedNodeIds, 'fills', index), $event)+ "@update="updatePickerFill(binding.actions, flush, $event, (next) =>actions.update(index, next))"- @open-change="!$event && commitPaintMutation(binding.actions)"+ @open-change="onPickerOpenChange(selectedNodeIds, index, $event, binding.actions)"@cancel="cancelPaintMutation(binding.actions)"/></template>diff --git a/src/components/properties/PageSection.vue b/src/components/properties/PageSection.vueindex 608ba0424..ea1b8fe62 100644--- a/src/components/properties/PageSection.vue+++ b/src/components/properties/PageSection.vue@@ -6,7 +6,7 @@ import { useI18n } from '@open-pencil/vue'import { useEditorStore } from '@/app/editor/active-store'import ColorPicker from '@/components/ColorPicker/ColorPicker.vue'-import PaintField from '@/components/properties/paint/PaintField.vue'+import PaintField from '@/components/inputs/PaintField.vue'import PaintValue from '@/components/properties/paint/PaintValue.vue'import FillSwatch from '@/components/ui/paint/FillSwatch.vue'import PanelSection from '@/components/ui/panel/PanelSection.vue'diff --git a/src/components/properties/paint/gradient-edit.ts b/src/components/properties/paint/gradient-edit.tsnew file mode 100644index 000000000..59e713247--- /dev/null+++ b/src/components/properties/paint/gradient-edit.ts@@ -0,0 +1,65 @@+import { editedGradientLayout, type GradientEdit } from '@open-pencil/core/editor'+import { hitTestGradientHandles } from '@open-pencil/core/geometry'++import { useEditorStore } from '@/app/editor/active-store'++type GradientTarget = Omit<GradientEdit, 'stop'>++/**+ * Ties a paint's picker to the canvas gradient handles: while the picker of a single layer's+ * paint is open, the canvas shows that gradient's handles and both share the selected stop.+ */+export function useGradientEditing() {+ const store = useEditorStore()++ function target(+ nodeIds: readonly string[],+ paint: GradientEdit['paint'],+ index: number+ ): GradientTarget | null {+ const [nodeId] = nodeIds+ return nodeIds.length === 1 && nodeId ? { nodeId, paint, index } : null+ }++ function editing(target: GradientTarget | null) {+ const edit = store.state.gradientEdit+ if (!edit || !target) return null+ const same =+ edit.nodeId === target.nodeId && edit.paint === target.paint && edit.index === target.index+ return same ? edit : null+ }++ function setOpen(target: GradientTarget | null, open: boolean) {+ if (open && target) store.state.gradientEdit = { ...target, stop: 0 }+ else if (!open && editing(target)) store.state.gradientEdit = null+ store.requestRepaint()+ }++ function stop(target: GradientTarget | null): number | undefined {+ return editing(target)?.stop+ }++ function setStop(target: GradientTarget | null, stop: number | undefined) {+ const edit = editing(target)+ if (!edit || stop === undefined || edit.stop === stop) return+ store.state.gradientEdit = { ...edit, stop }+ store.requestRepaint()+ }++ /** Whether a press lands on a gradient handle, which must not close the picker. */+ function pressesHandle(event: PointerEvent): boolean {+ const canvas = event.target+ if (!(canvas instanceof HTMLCanvasElement)) return false+ const layout = editedGradientLayout(store.graph, store.state.gradientEdit, store.state)+ if (!layout) return false+ const bounds = canvas.getBoundingClientRect()+ return (+ hitTestGradientHandles(layout, {+ x: event.clientX - bounds.left,+ y: event.clientY - bounds.top+ }) !== null+ )+ }++ return { target, setOpen, stop, setStop, pressesHandle }+}diff --git a/src/components/properties/stroke/StrokeSection.vue b/src/components/properties/stroke/StrokeSection.vueindex 6a14fb824..437cfa5a2 100644--- a/src/components/properties/stroke/StrokeSection.vue+++ b/src/components/properties/stroke/StrokeSection.vue@@ -16,6 +16,7 @@ import type { BindableValueActions } from '@open-pencil/vue'import FillPicker from '@/components/fill-picker/FillPicker.vue'import NumberField from '@/components/inputs/NumberField.vue'+import PaintField from '@/components/inputs/PaintField.vue'import VariableBindingPicker from '@/components/properties/binding/VariableBindingPicker.vue'import PropertyItemRow from '@/components/properties/item-list/PropertyItemRow.vue'import {@@ -24,8 +25,8 @@ import {commitPaintMutation,paintBindingTargets} from '@/components/properties/paint/binding'+import { useGradientEditing } from '@/components/properties/paint/gradient-edit'import { createStrokeOkhclAdapter } from '@/components/properties/paint/okhcl'-import PaintField from '@/components/properties/paint/PaintField.vue'import PaintValue from '@/components/properties/paint/PaintValue.vue'import PropertyListRoot from '@/components/properties/PropertyListRoot.vue'import { useSharedStylePicker } from '@/components/properties/shared-style/useSharedStylePicker'@@ -47,6 +48,18 @@ const strokeCtx = useStrokeControls()const { advancedActive } = strokeCtxconst colorProvider = useColorBindingProvider()const okhcl = useOkHCL()+const gradients = useGradientEditing()++/** Opening a paint's picker shows its gradient handles on the canvas; closing commits the edit. */+function onPickerOpenChange(+ nodeIds: readonly string[],+ index: number,+ open: boolean,+ binding: BindableValueActions<Color>+) {+ gradients.setOpen(gradients.target(nodeIds, 'strokes', index), open)+ if (!open) commitPaintMutation(binding)+}const { panels, common } = useI18n()const expandedSides = ref(false)@@ -157,12 +170,17 @@ function onToggleSides(activeNode: SceneNode | null) {:label="panels.stroke":fill="displayStroke(stroke, binding.resolvedValue)":okhcl="createStrokeOkhclAdapter(okhcl, activeNode, index)"+ :keep-open="gradients.pressesHandle"+ :active-stop="gradients.stop(gradients.target(selectedNodeIds, 'strokes', index))"+ @update:active-stop="+ gradients.setStop(gradients.target(selectedNodeIds, 'strokes', index), $event)+ "@update="updateStrokePaint(binding.actions, flush, stroke, $event, (next) =>actions.update(index, next))"- @open-change="!$event && commitPaintMutation(binding.actions)"+ @open-change="onPickerOpenChange(selectedNodeIds, index, $event, binding.actions)"@cancel="cancelPaintMutation(binding.actions)"/></template>diff --git a/tests/e2e/canvas/gradient-handles-visual.spec.ts b/tests/e2e/canvas/gradient-handles-visual.spec.tsnew file mode 100644index 000000000..5bce2d1c2--- /dev/null+++ b/tests/e2e/canvas/gradient-handles-visual.spec.ts@@ -0,0 +1,26 @@+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'+import { gradientDriver } from '#tests/helpers/canvas/gradient-driver'++// Figma desktop 126: a linear gradient shows its line, end dots, and stop squares; radial and+// diamond add a centre and a second radius dot; angular draws its ellipse with squares outside it.++const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')++const gradient = gradientDriver(() => editor.page)++for (const type of [+ 'GRADIENT_LINEAR',+ 'GRADIENT_RADIAL',+ 'GRADIENT_ANGULAR',+ 'GRADIENT_DIAMOND'+] as const) {+ test(`${type.toLowerCase()} gradient handles`, async () => {+ const nodeId = await gradient.show(type)+ await gradient.edit(nodeId)+ await editor.canvas.waitForRender()+ expect(await editor.canvas.screenshotCanvasRegion(600, 480)).toMatchSnapshot(+ `${type.toLowerCase()}.png`+ )+ editor.canvas.assertNoErrors()+ })+}diff --git a/tests/e2e/canvas/gradient-handles-visual.spec.ts-snapshots/gradient-angular-openpencil-darwin.png b/tests/e2e/canvas/gradient-handles-visual.spec.ts-snapshots/gradient-angular-openpencil-darwin.pngnew file mode 100644index 000000000..d961c30bdBinary files /dev/null and b/tests/e2e/canvas/gradient-handles-visual.spec.ts-snapshots/gradient-angular-openpencil-darwin.png differdiff --git a/tests/e2e/canvas/gradient-handles-visual.spec.ts-snapshots/gradient-diamond-openpencil-darwin.png b/tests/e2e/canvas/gradient-handles-visual.spec.ts-snapshots/gradient-diamond-openpencil-darwin.pngnew file mode 100644index 000000000..5671f3839Binary files /dev/null and b/tests/e2e/canvas/gradient-handles-visual.spec.ts-snapshots/gradient-diamond-openpencil-darwin.png differdiff --git a/tests/e2e/canvas/gradient-handles-visual.spec.ts-snapshots/gradient-linear-openpencil-darwin.png b/tests/e2e/canvas/gradient-handles-visual.spec.ts-snapshots/gradient-linear-openpencil-darwin.pngnew file mode 100644index 000000000..194c7293fBinary files /dev/null and b/tests/e2e/canvas/gradient-handles-visual.spec.ts-snapshots/gradient-linear-openpencil-darwin.png differdiff --git a/tests/e2e/canvas/gradient-handles-visual.spec.ts-snapshots/gradient-radial-openpencil-darwin.png b/tests/e2e/canvas/gradient-handles-visual.spec.ts-snapshots/gradient-radial-openpencil-darwin.pngnew file mode 100644index 000000000..54748e82cBinary files /dev/null and b/tests/e2e/canvas/gradient-handles-visual.spec.ts-snapshots/gradient-radial-openpencil-darwin.png differdiff --git a/tests/e2e/canvas/gradient-handles.spec.ts b/tests/e2e/canvas/gradient-handles.spec.tsnew file mode 100644index 000000000..e854d9fab--- /dev/null+++ b/tests/e2e/canvas/gradient-handles.spec.ts@@ -0,0 +1,97 @@+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'+import { gradientDriver } from '#tests/helpers/canvas/gradient-driver'+import { propertyItems } from '#tests/helpers/properties'++// Figma desktop 126: while a gradient's picker is open the canvas shows its handles. An end moves+// exactly with the pointer, a stop square slides its stop along the line, and pressing either+// keeps the picker open.++const editor = useEditorSetupWithClear('/?test&no-rulers')++const gradient = gradientDriver(() => editor.page)++const bar = () => editor.page.getByTestId('fill-picker-gradient-bar').locator('[data-slot=stop]')++async function closePicker() {+ await editor.page.keyboard.press('Escape')+ await expect.poll(() => gradient.editing()).toBe(false)+}++async function openPicker() {+ const nodeId = await gradient.show('GRADIENT_LINEAR')+ await editor.canvas.waitForRender()+ await propertyItems(editor.page, 'fills')+ .first()+ .getByRole('button', { name: 'Fill', exact: true })+ .click()+ await expect(editor.page.getByTestId('fill-picker-gradient-bar')).toBeVisible()+ await expect.poll(() => gradient.editing()).toBe(true)+ return nodeId+}++test('dragging an end dot moves that end, and closing the picker leaves one undo step', async () => {+ const nodeId = await openPicker()+ const before = await gradient.fill(nodeId)+ const end = gradient.point(200, 70)+ const target = gradient.point(200, 10)+ await editor.canvas.drag(end.x, end.y, target.x, target.y)+ await editor.canvas.waitForRender()++ const moved = await gradient.fill(nodeId)+ // The end, (m02, m12), follows the pointer to (200, 10) within the half screen pixel it lands+ // on; the start, end plus (m00, m10), stays at the left edge's middle.+ expect(moved?.transform?.m02).toBeCloseTo(1, 2)+ expect(moved?.transform?.m12).toBeCloseTo(10 / 140, 2)+ expect(moved?.transform?.m00).toBeCloseTo(-1, 2)+ expect(moved?.transform?.m10).toBeCloseTo(60 / 140, 2)+ await expect(editor.page.getByTestId('fill-picker-gradient-bar')).toBeVisible()++ // Shortcuts wait for open popovers to close; closing the picker also hides the handles.+ await closePicker()+ await editor.canvas.undo()+ expect(await gradient.fill(nodeId)).toEqual(before)+ editor.canvas.assertNoErrors()+})++test('Escape during a drag puts the gradient back and leaves the picker open', async () => {+ const nodeId = await openPicker()+ const before = await gradient.fill(nodeId)+ const end = gradient.point(200, 70)+ const box = await editor.canvas.canvas.boundingBox()+ if (!box) throw new Error('Expected the canvas')+ await editor.page.mouse.move(box.x + end.x, box.y + end.y)+ await editor.page.mouse.down()+ await editor.page.mouse.move(box.x + end.x, box.y + end.y - 120, { steps: 5 })+ expect(await gradient.fill(nodeId)).not.toEqual(before)++ await editor.page.keyboard.press('Escape')+ await editor.page.mouse.up()+ await editor.canvas.waitForRender()+ expect(await gradient.fill(nodeId)).toEqual(before)+ await expect(editor.page.getByTestId('fill-picker-gradient-bar')).toBeVisible()+ await closePicker()+})++test('dragging a stop square slides the stop and selects it in the picker', async () => {+ const nodeId = await openPicker()+ // The middle stop's square sits above the line, half a square and the gap from it.+ const square = gradient.point(100, 70)+ await editor.canvas.drag(square.x, square.y - 18, square.x + 100, square.y - 18)+ await editor.canvas.waitForRender()++ const [first, moved, last] = (await gradient.fill(nodeId))?.stops ?? []+ expect([first, last]).toEqual([0, 1])+ // 50 layer pixels right of the middle, within the half screen pixel the pointer lands on.+ expect(moved).toBeCloseTo(0.75, 2)+ expect(await gradient.editedStop()).toBe(1)+ await expect(bar().nth(1)).toHaveAttribute('data-selected', '')+ await closePicker()+ editor.canvas.assertNoErrors()+})++test('selecting a stop in the picker selects its square on the canvas', async () => {+ await openPicker()+ await bar().nth(2).click()+ await expect.poll(() => gradient.editedStop()).toBe(2)+ await closePicker()+})diff --git a/tests/helpers/canvas/gradient-driver.ts b/tests/helpers/canvas/gradient-driver.tsnew file mode 100644index 000000000..007a4ae1d--- /dev/null+++ b/tests/helpers/canvas/gradient-driver.ts@@ -0,0 +1,62 @@+import type { Page } from '@playwright/test'++import type * as GradientScene from '#tests/helpers/canvas/gradient'++type GradientType = Parameters<typeof GradientScene.createGradientScene>[2]++/** Builds a gradient scene, opens its fill picker, and reads the gradient back. */+export function gradientDriver(page: () => Page) {+ return {+ /** The gradient rectangle, selected, at 200% with its top-left 100 px into the canvas. */+ async show(type: GradientType) {+ return page().evaluate(async (type) => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const fixtureURL = '/tests/helpers/canvas/gradient.ts'+ const scene: typeof GradientScene = await import(fixtureURL)+ const { nodeId } = scene.createGradientScene(store.graph, store.state.currentPageId, type)+ store.select([nodeId])+ store.state.zoom = 2+ store.state.panX = 100+ store.state.panY = 100+ store.requestRender()+ return nodeId+ }, type)+ },++ /** Canvas coordinates of a point in the layer's own pixels. */+ point(x: number, y: number) {+ return { x: 100 + x * 2, y: 100 + y * 2 }+ },++ fill(nodeId: string) {+ return page().evaluate((id) => {+ const fill = window.openPencil?.getStore?.().graph.getNode(id)?.fills[0]+ return fill+ ? {+ transform: fill.gradientTransform,+ stops: fill.gradientStops?.map((stop) => stop.position)+ }+ : null+ }, nodeId)+ },++ editedStop() {+ return page().evaluate(() => window.openPencil?.getStore?.().state.gradientEdit?.stop ?? null)+ },++ /** Shows the handles without the picker, as when its fill picker is open. */+ edit(nodeId: string) {+ return page().evaluate((nodeId) => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ store.state.gradientEdit = { nodeId, paint: 'fills', index: 0, stop: 1 }+ store.requestRender()+ }, nodeId)+ },++ editing() {+ return page().evaluate(() => Boolean(window.openPencil?.getStore?.().state.gradientEdit))+ }+ }+}diff --git a/tests/helpers/canvas/gradient.ts b/tests/helpers/canvas/gradient.tsnew file mode 100644index 000000000..9fea7a7d0--- /dev/null+++ b/tests/helpers/canvas/gradient.ts@@ -0,0 +1,36 @@+import type { Fill, GradientTransform, SceneGraph } from '@open-pencil/scene-graph'++type GradientType = 'GRADIENT_LINEAR' | 'GRADIENT_RADIAL' | 'GRADIENT_ANGULAR' | 'GRADIENT_DIAMOND'++/** Linear from the left edge's middle to the right's; the others centred, filling the layer. */+const TRANSFORMS: Record<GradientType, GradientTransform> = {+ GRADIENT_LINEAR: { m00: -1, m01: 0, m02: 1, m10: 0, m11: -1, m12: 0.5 },+ GRADIENT_RADIAL: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 },+ GRADIENT_ANGULAR: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 },+ GRADIENT_DIAMOND: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }+}++/** A 200 × 140 rectangle at the origin with a red, yellow, and blue gradient fill. */+export function createGradientScene(graph: SceneGraph, pageId: string, type: GradientType) {+ const fill: Fill = {+ type,+ visible: true,+ opacity: 1,+ color: { r: 0, g: 0, b: 0, a: 1 },+ gradientTransform: TRANSFORMS[type],+ gradientStops: [+ { position: 0, color: { r: 1, g: 0.3, b: 0.2, a: 1 } },+ { position: 0.5, color: { r: 1, g: 0.85, b: 0.2, a: 1 } },+ { position: 1, color: { r: 0.2, g: 0.4, b: 1, a: 1 } }+ ]+ }+ const node = graph.createNode('RECTANGLE', pageId, {+ name: 'Gradient',+ x: 0,+ y: 0,+ width: 200,+ height: 140,+ fills: [fill]+ })+ return { nodeId: node.id }+}