Skip to content

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

feat: add a pencil tool for freehand vector strokes (#1199)

Danila Poyarkov19cb5ef59b08
diff --git a/changes/1199/added.md b/changes/1199/added.md
new file mode 100644
index 000000000..c1d6ab80e
--- /dev/null
+++ b/changes/1199/added.md
@@ -0,0 +1 @@
+- A pencil tool (<kbd>⇧</kbd><kbd>P</kbd>) draws freehand strokes as smoothed, editable vector paths, with <kbd>Shift</kbd> for straight lines, as Figma's pencil does.
diff --git a/packages/core/src/canvas/pen-overlay.ts b/packages/core/src/canvas/pen-overlay.ts
index e08e45ffa..6c1851748 100644
--- a/packages/core/src/canvas/pen-overlay.ts
+++ b/packages/core/src/canvas/pen-overlay.ts
@@ -160,6 +160,27 @@ function drawPenTangentHandles(
}
}
+/** The pencil stroke as sampled so far, in the colour and width it will be drawn with. */
+export function drawPencilOverlay(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ pencilState: RenderOverlays['pencilState']
+): void {
+ if (!pencilState) return
+ const [first, ...rest] = pencilState.points
+ const path = new r.ck.PathBuilder()
+ path.moveTo(first.x * r.zoom + r.panX, first.y * r.zoom + r.panY)
+ if (rest.length === 0) path.lineTo(first.x * r.zoom + r.panX, first.y * r.zoom + r.panY)
+ for (const point of rest) path.lineTo(point.x * r.zoom + r.panX, point.y * r.zoom + r.panY)
+ const { color, weight } = pencilState.preview
+ const paint = r.pencilStrokePaint
+ paint.setColor(r.ck.Color4f(color.r, color.g, color.b, color.a))
+ paint.setStrokeWidth(weight * r.zoom)
+ const stroke = path.detachAndDelete()
+ canvas.drawPath(stroke, paint)
+ stroke.delete()
+}
+
export function drawPenOverlay(
r: SkiaRenderer,
canvas: Canvas,
diff --git a/packages/core/src/canvas/renderer.ts b/packages/core/src/canvas/renderer.ts
index 351b91d66..ef852745e 100644
--- a/packages/core/src/canvas/renderer.ts
+++ b/packages/core/src/canvas/renderer.ts
@@ -199,6 +199,8 @@ export class SkiaRenderer {
declare rulerLabelPaint: Paint
declare penPathPaint: Paint
declare penLiveStrokePaint: Paint
+ /** The pencil stroke being drawn; its colour and width are set per frame. */
+ declare pencilStrokePaint: Paint
declare penHandlePaint: Paint
declare penVertexFill: Paint
declare penVertexStroke: Paint
@@ -311,6 +313,7 @@ export class SkiaRenderer {
editState?: RenderOverlays['nodeEditState']
) => void
declare drawPenOverlay: (canvas: Canvas, penState: RenderOverlays['penState']) => void
+ declare drawPencilOverlay: (canvas: Canvas, pencilState: RenderOverlays['pencilState']) => void
declare drawPresenceCursors: (
canvas: Canvas,
graph: SceneGraph,
diff --git a/packages/core/src/canvas/renderer/lifecycle.ts b/packages/core/src/canvas/renderer/lifecycle.ts
index 4eb578ec5..103ac9fa0 100644
--- a/packages/core/src/canvas/renderer/lifecycle.ts
+++ b/packages/core/src/canvas/renderer/lifecycle.ts
@@ -77,6 +77,7 @@ export function destroyRenderer(r: SkiaRenderer): void {
r.rulerLabelPaint.delete()
r.penPathPaint.delete()
r.penLiveStrokePaint.delete()
+ r.pencilStrokePaint.delete()
r.penHandlePaint.delete()
r.penVertexFill.delete()
r.penVertexStroke.delete()
diff --git a/packages/core/src/canvas/renderer/methods.ts b/packages/core/src/canvas/renderer/methods.ts
index 02e6a9262..6c73cd199 100644
--- a/packages/core/src/canvas/renderer/methods.ts
+++ b/packages/core/src/canvas/renderer/methods.ts
@@ -162,6 +162,10 @@ const rendererMethods: ThisType<SkiaRenderer> = {
PenOverlay.drawPenOverlay(this, canvas, penState)
},
+ drawPencilOverlay(canvas: Canvas, pencilState: RenderOverlays['pencilState']): void {
+ PenOverlay.drawPencilOverlay(this, canvas, pencilState)
+ },
+
drawPresenceCursors(canvas: Canvas, graph: SceneGraph, cursors?: PresenceCursor[]): void {
Overlays.drawPresenceCursors(this, canvas, graph, cursors)
},
diff --git a/packages/core/src/canvas/renderer/overlay-pass.ts b/packages/core/src/canvas/renderer/overlay-pass.ts
index ebbc7e5f3..0677d9eed 100644
--- a/packages/core/src/canvas/renderer/overlay-pass.ts
+++ b/packages/core/src/canvas/renderer/overlay-pass.ts
@@ -145,6 +145,7 @@ export function drawOverlayPass(
}
r.drawNodeEditOverlay(canvas, graph, overlays.nodeEditState)
r.drawPenOverlay(canvas, overlays.penState)
+ r.drawPencilOverlay(canvas, overlays.pencilState)
updateIssueMarkers(r, graph, overlays)
drawIssueMarkers(r, canvas, r.issueMarkers, overlays.designIssues?.hoveredMarkerKey)
r.drawPresenceCursors(canvas, graph, overlays.presenceCursors)
diff --git a/packages/core/src/canvas/renderer/paints.ts b/packages/core/src/canvas/renderer/paints.ts
index 55d1adffa..e1145013b 100644
--- a/packages/core/src/canvas/renderer/paints.ts
+++ b/packages/core/src/canvas/renderer/paints.ts
@@ -90,6 +90,12 @@ export function initializeRendererPaints(r: SkiaRenderer): void {
r.penLiveStrokePaint.setColor(ck.Color4f(0, 0, 0, 1))
r.penLiveStrokePaint.setAntiAlias(true)
+ r.pencilStrokePaint = new ck.Paint()
+ r.pencilStrokePaint.setStyle(ck.PaintStyle.Stroke)
+ r.pencilStrokePaint.setStrokeCap(ck.StrokeCap.Round)
+ r.pencilStrokePaint.setStrokeJoin(ck.StrokeJoin.Round)
+ r.pencilStrokePaint.setAntiAlias(true)
+
r.penHandlePaint = new ck.Paint()
r.penHandlePaint.setStyle(ck.PaintStyle.Stroke)
r.penHandlePaint.setStrokeWidth(1)
diff --git a/packages/core/src/canvas/renderer/pipeline.ts b/packages/core/src/canvas/renderer/pipeline.ts
index 31c16b64a..be3562690 100644
--- a/packages/core/src/canvas/renderer/pipeline.ts
+++ b/packages/core/src/canvas/renderer/pipeline.ts
@@ -106,6 +106,7 @@ export function renderFromEditorState(
cursorY: state.penCursorY ?? undefined
} as RenderOverlays['penState'])
: null,
+ pencilState: state.pencilState,
nodeEditState: state.nodeEditState ?? null,
presenceCursors: state.presenceCursors,
designIssues: state.designIssues,
diff --git a/packages/core/src/canvas/renderer/types.ts b/packages/core/src/canvas/renderer/types.ts
index 48c7d9565..2b2d73768 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 { ShapeHandleHover, GradientEdit } from '#core/editor/types'
+import type { ShapeHandleHover, GradientEdit, PencilState } from '#core/editor/types'
import type { RotationPreview } from '#core/geometry'
import type { TextEditor } from '#core/text/editor'
@@ -87,6 +87,7 @@ export interface RenderOverlays {
cursorX?: number
cursorY?: number
} | null
+ pencilState?: PencilState | null
nodeEditState?: {
nodeId: string
vertices: VectorVertex[]
diff --git a/packages/core/src/constants.ts b/packages/core/src/constants.ts
index 2fd6bfee5..27f982966 100644
--- a/packages/core/src/constants.ts
+++ b/packages/core/src/constants.ts
@@ -569,6 +569,13 @@ export const ZOOM_SCALE_MIN = 0.75
export const ZOOM_SCALE_MAX = 1.25
export const PEN_CLOSE_THRESHOLD = 8
+/**
+ * Screen pixels a pencil sample may stray from the line through its neighbours before the curve
+ * keeps it, so a stroke drawn zoomed in keeps more detail.
+ */
+export const PENCIL_TOLERANCE = 2.5
+/** A new pencil layer's stroke weight (Figma desktop 126). */
+export const PENCIL_STROKE_WEIGHT = 2
export const ROTATION_SNAP_DEGREES = 15
export const HANDLE_HIT_RADIUS = 6
/** How far outside a shape, in screen pixels, a click still selects it (Figma desktop 126). */
diff --git a/packages/core/src/editor/shapes.ts b/packages/core/src/editor/shapes.ts
index 8f7bca384..28ffed515 100644
--- a/packages/core/src/editor/shapes.ts
+++ b/packages/core/src/editor/shapes.ts
@@ -5,6 +5,7 @@ import { adoptCoveredLayers } from './shapes/adopt'
import { newLayerDefaults } from './shapes/defaults'
import { createFramePresetActions } from './shapes/frame-presets'
import { createPenActions } from './shapes/pen'
+import { createPencilActions } from './shapes/pencil'
import { defaultNodeName, nextNumberedName } from './structure/rename'
import type { EditorContext } from './types'
export type { PenDragOptions } from './shapes/pen'
@@ -71,6 +72,7 @@ export function createShapeActions(ctx: EditorContext) {
}
const penActions = createPenActions(ctx, createShape)
+ const pencilActions = createPencilActions(ctx, createShape)
const framePresetActions = createFramePresetActions(ctx, createShape)
function setTool(tool: typeof ctx.state.activeTool) {
@@ -80,6 +82,7 @@ export function createShapeActions(ctx: EditorContext) {
return {
createShape,
...penActions,
+ ...pencilActions,
...framePresetActions,
adoptCoveredLayers: (containerId: string) => adoptCoveredLayers(ctx, containerId),
setTool
diff --git a/packages/core/src/editor/shapes/pen.ts b/packages/core/src/editor/shapes/pen.ts
index 0ea026a2b..c37296576 100644
--- a/packages/core/src/editor/shapes/pen.ts
+++ b/packages/core/src/editor/shapes/pen.ts
@@ -1,14 +1,9 @@
-import type {
- SceneNode,
- VectorNetwork,
- VectorRegion,
- VectorSegment
-} from '@open-pencil/scene-graph'
+import type { SceneNode, VectorRegion, VectorSegment } from '@open-pencil/scene-graph'
import type { Vector } from '@open-pencil/scene-graph/primitives'
import { BLACK } from '#core/constants'
+import { createVectorFromNetwork, type CreateShape } from '#core/editor/shapes/vector'
import type { EditorContext } from '#core/editor/types'
-import { computeAccurateBounds } from '#core/vector'
export interface PenDragOptions {
keepOpposite?: boolean
@@ -16,15 +11,6 @@ export interface PenDragOptions {
oppositeTangent?: Vector | null
}
-type CreateShape = (
- type: 'VECTOR',
- x: number,
- y: number,
- w: number,
- h: number,
- parentId?: string
-) => string
-
const PEN_DEFAULT_STROKE: SceneNode['strokes'][number] = {
type: 'SOLID',
color: BLACK,
@@ -173,42 +159,17 @@ export function createPenActions(ctx: EditorContext, createShape: CreateShape) {
? [{ windingRule: 'NONZERO', loops: [ps.segments.map((_, i) => i)] }]
: []
- const network: VectorNetwork = {
- vertices: ps.vertices.map((v) => ({ ...v })),
- segments: ps.segments.map((s) => ({
- ...s,
- tangentStart: { ...s.tangentStart },
- tangentEnd: { ...s.tangentEnd }
- })),
- regions
- }
-
- const bounds = computeAccurateBounds(network)
-
- const normalizedVertices = network.vertices.map((v) => ({
- ...v,
- x: v.x - bounds.x,
- y: v.y - bounds.y
- }))
-
- const normalizedNetwork: VectorNetwork = {
- vertices: normalizedVertices,
- segments: network.segments,
- regions: network.regions
- }
-
const fills = ps.resumedFills ? ps.resumedFills.map((f) => ({ ...f })) : []
const strokes = ps.resumedStrokes
? ps.resumedStrokes.map((s) => ({ ...s }))
: [{ ...PEN_DEFAULT_STROKE }]
- const nodeId = createShape('VECTOR', bounds.x, bounds.y, bounds.width, bounds.height)
- ctx.graph.updateNode(nodeId, {
- vectorNetwork: normalizedNetwork,
- name: 'Vector',
- fills,
- strokes
- })
+ const nodeId = createVectorFromNetwork(
+ ctx,
+ createShape,
+ { vertices: ps.vertices, segments: ps.segments, regions },
+ { name: 'Vector', fills, strokes }
+ )
ctx.setSelectedIds(new Set([nodeId]))
ctx.state.penState = null
diff --git a/packages/core/src/editor/shapes/pencil.ts b/packages/core/src/editor/shapes/pencil.ts
new file mode 100644
index 000000000..d9ff7638d
--- /dev/null
+++ b/packages/core/src/editor/shapes/pencil.ts
@@ -0,0 +1,137 @@
+import { pick } from 'es-toolkit'
+
+import type { SceneNode } from '@open-pencil/scene-graph'
+import { compositeOver, readableForeground } from '@open-pencil/scene-graph/color'
+import type { Color, Vector } from '@open-pencil/scene-graph/primitives'
+
+import { PEN_CLOSE_THRESHOLD, PENCIL_STROKE_WEIGHT, PENCIL_TOLERANCE } from '#core/constants'
+import { createVectorFromNetwork, type CreateShape } from '#core/editor/shapes/vector'
+import { nextNumberedName } from '#core/editor/structure/rename'
+import type { EditorContext } from '#core/editor/types'
+import { freehandNetwork, simplifyFreehand } from '#core/vector/freehand'
+
+const STYLE_FIELDS = ['strokes', 'strokeCap', 'strokeJoin'] as const
+
+type PencilStyle = Pick<SceneNode, (typeof STYLE_FIELDS)[number]>
+
+/** `point` moved onto the horizontal or vertical line through `anchor`, whichever is nearer. */
+function axisLocked(anchor: Vector, point: Vector): Vector {
+ return Math.abs(point.x - anchor.x) >= Math.abs(point.y - anchor.y)
+ ? { x: point.x, y: anchor.y }
+ : { x: anchor.x, y: point.y }
+}
+
+/**
+ * Freehand strokes, as Figma's pencil draws them: each stroke becomes its own outlined vector
+ * whose curve is fitted to the samples at the zoom it was drawn at, and the tool stays active.
+ * New strokes contrast with what they are drawn on until the last pencil layer is restyled; from
+ * then on they take its strokes, cap, and join, even after that layer is gone.
+ */
+export function createPencilActions(ctx: EditorContext, createShape: CreateShape) {
+ let lastNodeId: string | null = null
+ let remembered: PencilStyle | null = null
+
+ function pencilBegin(x: number, y: number) {
+ const stroke = strokeStyle(undefined).strokes.find((paint) => paint.visible)
+ ctx.state.pencilState = {
+ points: [{ x, y }],
+ straightFrom: null,
+ preview: {
+ color: stroke?.color ?? readableForeground(ctx.state.pageColor),
+ weight: stroke?.weight ?? PENCIL_STROKE_WEIGHT
+ }
+ }
+ ctx.requestRepaint()
+ }
+
+ /** Adds a sample; while `straight`, the stroke runs from where Shift was pressed along an axis. */
+ function pencilAddPoint(x: number, y: number, straight = false) {
+ const pencil = ctx.state.pencilState
+ if (!pencil) return
+ if (!straight) {
+ pencil.straightFrom = null
+ pencil.points.push({ x, y })
+ } else {
+ pencil.straightFrom ??= pencil.points.length - 1
+ const anchor = pencil.points[pencil.straightFrom]
+ pencil.points.length = pencil.straightFrom + 1
+ pencil.points.push(axisLocked(anchor, { x, y }))
+ }
+ ctx.requestRepaint()
+ }
+
+ function background(parentId: string | undefined): Color {
+ const page = ctx.state.pageColor
+ const parent = parentId ? ctx.graph.getNode(parentId) : undefined
+ const fill = parent?.fills.findLast((paint) => paint.visible && paint.type === 'SOLID')
+ return fill ? compositeOver(fill.color, page, fill.color.a * fill.opacity) : page
+ }
+
+ ctx.onEditorEvent('node:updated', (id, changes) => {
+ if (id !== lastNodeId || !STYLE_FIELDS.some((field) => field in changes)) return
+ const node = ctx.graph.getNode(id)
+ if (node) remembered = structuredClone(pick(node, STYLE_FIELDS))
+ })
+
+ function strokeStyle(parentId: string | undefined): PencilStyle {
+ return structuredClone(remembered ?? contrastingStyle(parentId))
+ }
+
+ function contrastingStyle(parentId: string | undefined): PencilStyle {
+ return {
+ strokes: [
+ {
+ type: 'SOLID',
+ color: readableForeground(background(parentId)),
+ weight: PENCIL_STROKE_WEIGHT,
+ opacity: 1,
+ visible: true,
+ align: 'CENTER'
+ }
+ ],
+ strokeCap: 'ROUND',
+ strokeJoin: 'ROUND'
+ }
+ }
+
+ function pencilCancel() {
+ ctx.state.pencilState = null
+ ctx.requestRepaint()
+ }
+
+ /**
+ * Turns the stroke into a vector layer in `parentId`, the current page when omitted. A press
+ * without movement draws nothing.
+ */
+ function pencilCommit(parentId?: string): string | null {
+ const points = ctx.state.pencilState?.points ?? []
+ ctx.state.pencilState = null
+ const zoom = ctx.state.zoom
+ const first = points.at(0)
+ const last = points.at(-1)
+ const ends = first && last ? Math.hypot(last.x - first.x, last.y - first.y) * zoom : 0
+ const tolerance = PENCIL_TOLERANCE / zoom
+ let controls = simplifyFreehand(points, tolerance)
+ const closed = controls.length > 3 && ends <= PEN_CLOSE_THRESHOLD
+ if (closed) controls = simplifyFreehand(points, tolerance, true)
+ if (controls.length < 2) {
+ ctx.requestRepaint()
+ return null
+ }
+
+ const pageId = parentId ?? ctx.state.currentPageId
+ const nodeId = createVectorFromNetwork(
+ ctx,
+ createShape,
+ freehandNetwork(controls, closed),
+ { ...strokeStyle(parentId), name: nextNumberedName(ctx.graph, pageId, 'Vector'), fills: [] },
+ parentId
+ )
+ lastNodeId = nodeId
+ ctx.setSelectedIds(new Set())
+ ctx.requestRender()
+ return nodeId
+ }
+
+ return { pencilBegin, pencilAddPoint, pencilCommit, pencilCancel }
+}
diff --git a/packages/core/src/editor/shapes/vector.ts b/packages/core/src/editor/shapes/vector.ts
new file mode 100644
index 000000000..7568cb516
--- /dev/null
+++ b/packages/core/src/editor/shapes/vector.ts
@@ -0,0 +1,55 @@
+import {
+ transformVectorNetwork,
+ type SceneNode,
+ type VectorNetwork
+} from '@open-pencil/scene-graph'
+import { getWorldMatrix } from '@open-pencil/scene-graph/coordinate'
+import Matrix from '@open-pencil/scene-graph/matrix'
+
+import type { EditorContext } from '#core/editor/types'
+import { computeAccurateBounds } from '#core/vector'
+
+export type CreateShape = (
+ type: 'VECTOR',
+ x: number,
+ y: number,
+ w: number,
+ h: number,
+ parentId?: string
+) => string
+
+/** A network drawn in canvas coordinates, mapped into the axes of the layer it goes into. */
+function inParentSpace(ctx: EditorContext, network: VectorNetwork, parentId?: string) {
+ const parent = parentId ? ctx.graph.getNode(parentId) : undefined
+ if (!parent || parent.type === 'CANVAS') return network
+ const toLocal = Matrix.invert(getWorldMatrix(parent, ctx.graph))
+ return toLocal ? transformVectorNetwork(toLocal, network) : network
+}
+
+/**
+ * Adds a drawn path as a vector layer: `network` is in canvas coordinates, and the layer is
+ * placed at the path's bounds in `parentId`, the current page when omitted, with the path moved
+ * to start at its own origin. Pen and pencil strokes both finish here.
+ */
+export function createVectorFromNetwork(
+ ctx: EditorContext,
+ createShape: CreateShape,
+ network: VectorNetwork,
+ style: Partial<SceneNode>,
+ parentId?: string
+): string {
+ const local = inParentSpace(ctx, network, parentId)
+ const bounds = computeAccurateBounds(local)
+ const vectorNetwork: VectorNetwork = {
+ vertices: local.vertices.map((v) => ({ ...v, x: v.x - bounds.x, y: v.y - bounds.y })),
+ segments: local.segments.map((s) => ({
+ ...s,
+ tangentStart: { ...s.tangentStart },
+ tangentEnd: { ...s.tangentEnd }
+ })),
+ regions: local.regions
+ }
+ const nodeId = createShape('VECTOR', bounds.x, bounds.y, bounds.width, bounds.height, parentId)
+ ctx.graph.updateNode(nodeId, { ...style, vectorNetwork })
+ return nodeId
+}
diff --git a/packages/core/src/editor/state/view.ts b/packages/core/src/editor/state/view.ts
index 670f87f23..9e8ba2264 100644
--- a/packages/core/src/editor/state/view.ts
+++ b/packages/core/src/editor/state/view.ts
@@ -19,6 +19,7 @@ export function createDefaultEditorViewState(pageId: string): EditorViewState {
penState: null,
penCursorX: null,
penCursorY: null,
+ pencilState: null,
autoLayoutHover: null,
shapeHandleHover: null,
panX: 0,
@@ -46,6 +47,7 @@ export function copyEditorViewState(source: EditorViewState): EditorViewState {
rotationPreview: structuredClone(source.rotationPreview),
layoutInsertIndicator: structuredClone(source.layoutInsertIndicator),
penState: structuredClone(source.penState),
+ pencilState: structuredClone(source.pencilState),
autoLayoutHover: structuredClone(source.autoLayoutHover),
shapeHandleHover: structuredClone(source.shapeHandleHover),
pageColor: { ...source.pageColor },
diff --git a/packages/core/src/editor/tool-registry.ts b/packages/core/src/editor/tool-registry.ts
index 4b81cccbb..3f2e3e6ec 100644
--- a/packages/core/src/editor/tool-registry.ts
+++ b/packages/core/src/editor/tool-registry.ts
@@ -16,7 +16,7 @@ export const EDITOR_TOOLS: EditorToolDef[] = [
shortcut: 'R',
flyout: ['RECTANGLE', 'LINE', 'ELLIPSE', 'POLYGON', 'STAR']
},
- { key: 'PEN', label: 'Pen', shortcut: 'P' },
+ { key: 'PEN', label: 'Pen', shortcut: 'P', flyout: ['PEN', 'PENCIL'] },
{ key: 'TEXT', label: 'Text', shortcut: 'T' },
{ key: 'HAND', label: 'Hand', shortcut: 'H' },
{ key: 'COMMENT', label: 'Comment', shortcut: 'C' }
@@ -32,6 +32,7 @@ export const TOOL_SHORTCUTS: Partial<Record<string, Tool>> = {
KeyL: 'LINE',
KeyT: 'TEXT',
KeyP: 'PEN',
+ 'Shift+KeyP': 'PENCIL',
KeyH: 'HAND',
KeyC: 'COMMENT'
}
diff --git a/packages/core/src/editor/types.ts b/packages/core/src/editor/types.ts
index 29a6732bb..d888d945b 100644
--- a/packages/core/src/editor/types.ts
+++ b/packages/core/src/editor/types.ts
@@ -42,6 +42,7 @@ export type Tool =
| 'STAR'
| 'TEXT'
| 'PEN'
+ | 'PENCIL'
| 'HAND'
| 'COMMENT'
@@ -94,6 +95,14 @@ export interface EditorSharedState {
canvasVersion: number
}
+export interface PencilState {
+ points: Vector[]
+ /** The point Shift was pressed at; the stroke runs straight from it while Shift is held. */
+ straightFrom: number | null
+ /** How the stroke shows while it is drawn. */
+ preview: { color: Color; weight: number }
+}
+
export interface EditorViewState {
currentPageId: string
selectedIds: Set<string>
@@ -128,6 +137,8 @@ export interface EditorViewState {
} | null
penCursorX: number | null
penCursorY: number | null
+ /** The freehand stroke being drawn with the pencil, in canvas coordinates. */
+ pencilState: PencilState | null
autoLayoutHover: {
nodeId: string
kind: 'frame' | 'children' | 'spacing' | 'spacing-value' | 'padding' | 'padding-value'
diff --git a/packages/core/src/vector/freehand.ts b/packages/core/src/vector/freehand.ts
new file mode 100644
index 000000000..b20a70bcd
--- /dev/null
+++ b/packages/core/src/vector/freehand.ts
@@ -0,0 +1,128 @@
+import type { VectorNetwork, VectorSegment, VectorVertex } from '@open-pencil/scene-graph'
+import type { Vector } from '@open-pencil/scene-graph/primitives'
+
+const ZERO: Vector = { x: 0, y: 0 }
+
+function distanceToLine(point: Vector, a: Vector, b: Vector): number {
+ const dx = b.x - a.x
+ const dy = b.y - a.y
+ const length = Math.hypot(dx, dy)
+ if (length === 0) return Math.hypot(point.x - a.x, point.y - a.y)
+ return Math.abs((point.x - a.x) * dy - (point.y - a.y) * dx) / length
+}
+
+/** Indexes Douglas–Peucker keeps between `first` and `last`, both kept by the caller. */
+function keepFarthest(
+ points: readonly Vector[],
+ first: number,
+ last: number,
+ tolerance: number,
+ kept: number[]
+) {
+ let farthest = -1
+ let distance = tolerance
+ for (let i = first + 1; i < last; i++) {
+ const d = distanceToLine(points[i], points[first], points[last])
+ if (d > distance) {
+ distance = d
+ farthest = i
+ }
+ }
+ if (farthest < 0) return
+ keepFarthest(points, first, farthest, tolerance, kept)
+ kept.push(farthest)
+ keepFarthest(points, farthest, last, tolerance, kept)
+}
+
+/**
+ * The points of a freehand stroke a pencil curve is built on: the first and last, the first
+ * sample after the press, which sets the direction the stroke leaves in, and the points that
+ * stray more than `tolerance` from the line through their neighbours. A stroke that never strays
+ * from the line between its ends keeps only the ends. Pass a tolerance in the stroke's units, so
+ * screen pixels divided by zoom for a stroke in canvas coordinates. A stroke that ends where it
+ * started has no direction to leave in, so `closed` skips the first sample.
+ */
+export function simplifyFreehand(
+ points: readonly Vector[],
+ tolerance: number,
+ closed = false
+): Vector[] {
+ const distinct = points.filter(
+ (point, i) => i === 0 || point.x !== points[i - 1].x || point.y !== points[i - 1].y
+ )
+ if (distinct.length <= 2) return distinct.map((point) => ({ ...point }))
+
+ const first = distinct[0]
+ const last = distinct[distinct.length - 1]
+ if (distinct.every((point) => distanceToLine(point, first, last) <= tolerance)) {
+ return [{ ...first }, { ...last }]
+ }
+
+ const kept = closed ? [0] : [0, 1]
+ keepFarthest(distinct, kept.length - 1, distinct.length - 1, tolerance, kept)
+ kept.push(distinct.length - 1)
+ return kept.map((i) => ({ ...distinct[i] }))
+}
+
+function lerp(a: Vector, b: Vector, scale: number): Vector {
+ return { x: (b.x - a.x) * scale, y: (b.y - a.y) * scale }
+}
+
+/** A closed stroke's loop: every control is a knot with neighbours on both sides. */
+function closedNetwork(controls: readonly Vector[]): VectorNetwork {
+ // The last control is the release, next to the press, so the loop goes round the others.
+ const q = controls.slice(0, -1)
+ const m = q.length
+ const at = (i: number) => q[(i + m) % m]
+ const vertices: VectorVertex[] = q.map((point, i) => ({
+ x: (at(i - 1).x + 4 * point.x + at(i + 1).x) / 6,
+ y: (at(i - 1).y + 4 * point.y + at(i + 1).y) / 6,
+ handleMirroring: 'ANGLE'
+ }))
+ const segments: VectorSegment[] = q.map((_, i) => ({
+ start: i,
+ end: (i + 1) % m,
+ tangentStart: lerp(at(i - 1), at(i + 1), 1 / 6),
+ tangentEnd: lerp(at(i + 2), at(i), 1 / 6)
+ }))
+ return { vertices, segments, regions: [] }
+}
+
+/**
+ * A pencil stroke as a vector network, as Figma's pencil builds it: `controls` are the control
+ * polygon of a uniform cubic B-spline whose ends are pinned to the first and last control, and
+ * each knot becomes a smooth vertex, so corners in the polygon come out rounded. A `closed`
+ * stroke, whose last control lands back on its first, wraps round as one smooth loop with no
+ * region, so it stays an outline.
+ */
+export function freehandNetwork(controls: readonly Vector[], closed = false): VectorNetwork {
+ if (closed && controls.length > 3) return closedNetwork(controls)
+ const q = [...controls]
+ const n = q.length - 1
+ if (n < 1) return { vertices: q.map((point) => ({ ...point })), segments: [], regions: [] }
+
+ const vertices: VectorVertex[] = q.map((point, i) => {
+ if (i === 0 || i === n) return { x: point.x, y: point.y, handleMirroring: 'ANGLE' }
+ return {
+ x: (q[i - 1].x + 4 * point.x + q[i + 1].x) / 6,
+ y: (q[i - 1].y + 4 * point.y + q[i + 1].y) / 6,
+ handleMirroring: 'ANGLE'
+ }
+ })
+
+ const segments: VectorSegment[] = []
+ if (n === 1) {
+ segments.push({ start: 0, end: 1, tangentStart: { ...ZERO }, tangentEnd: { ...ZERO } })
+ } else {
+ for (let i = 0; i < n; i++) {
+ segments.push({
+ start: i,
+ end: i + 1,
+ tangentStart: i === 0 ? lerp(q[0], q[1], 1 / 3) : lerp(q[i - 1], q[i + 1], 1 / 6),
+ tangentEnd: i + 1 === n ? lerp(q[n], q[n - 1], 1 / 3) : lerp(q[i + 2], q[i], 1 / 6)
+ })
+ }
+ }
+
+ return { vertices, segments, regions: [] }
+}
diff --git a/packages/core/src/vector/index.ts b/packages/core/src/vector/index.ts
index 4d236ee51..663b258a1 100644
--- a/packages/core/src/vector/index.ts
+++ b/packages/core/src/vector/index.ts
@@ -1,5 +1,6 @@
export * from './vectorize'
export * from './handle-selection'
+export { freehandNetwork, simplifyFreehand } from './freehand'
export {
breakAtVertex,
diff --git a/packages/core/tests/editor/pencil.test.ts b/packages/core/tests/editor/pencil.test.ts
new file mode 100644
index 000000000..daca10d86
--- /dev/null
+++ b/packages/core/tests/editor/pencil.test.ts
@@ -0,0 +1,190 @@
+import { describe, expect, test } from 'bun:test'
+
+import { getNodeOrThrow } from '#core-tests/helpers/assert'
+
+import { createEditor } from '@open-pencil/core/editor'
+import type { Vector } from '@open-pencil/scene-graph/primitives'
+
+type Editor = ReturnType<typeof createEditor>
+
+const DARK_PAGE = { r: 0.118, g: 0.118, b: 0.118, a: 1 }
+
+function sine(x0 = 0, y0 = 0) {
+ return Array.from({ length: 61 }, (_, i) => ({
+ x: x0 + 5 * i,
+ y: y0 + 40 * Math.sin((i / 60) * 2 * Math.PI)
+ }))
+}
+
+function draw(
+ editor: Editor,
+ points: Vector[],
+ { parentId, shift = false }: { parentId?: string; shift?: boolean } = {}
+) {
+ const [first, ...rest] = points
+ editor.pencilBegin(first.x, first.y)
+ for (const point of rest) editor.pencilAddPoint(point.x, point.y, shift)
+ return editor.pencilCommit(parentId)
+}
+
+function pencilEditor() {
+ const editor = createEditor()
+ editor.setTool('PENCIL')
+ return editor
+}
+
+// Behaviour measured live in Figma desktop's pencil.
+describe('pencil', () => {
+ test('draws an outlined, numbered vector and stays on the pencil with nothing selected', () => {
+ const editor = pencilEditor()
+ const id = draw(editor, sine())
+ if (!id) throw new Error('nothing drawn')
+ const node = getNodeOrThrow(editor.graph, id)
+
+ expect(node.type).toBe('VECTOR')
+ expect(node.name).toBe('Vector 1')
+ expect(node.fills).toEqual([])
+ expect(node.strokes).toHaveLength(1)
+ expect(node.strokes[0]).toMatchObject({ weight: 2, align: 'CENTER' })
+ expect(node.strokeCap).toBe('ROUND')
+ expect(node.strokeJoin).toBe('ROUND')
+ expect(node.vectorNetwork?.regions).toEqual([])
+ expect(node.vectorNetwork?.vertices.every((v) => v.handleMirroring === 'ANGLE')).toBe(true)
+ expect({ x: node.x, y: node.y, width: node.width }).toMatchObject({ x: 0, width: 300 })
+ expect(editor.state.selectedIds.size).toBe(0)
+ expect(editor.state.activeTool).toBe('PENCIL')
+ expect(editor.state.pencilState).toBeNull()
+
+ const second = draw(editor, sine(0, 100))
+ expect(second && getNodeOrThrow(editor.graph, second).name).toBe('Vector 2')
+ })
+
+ test('draws nothing for a press without movement', () => {
+ const editor = pencilEditor()
+ const before = editor.graph.getChildren(editor.state.currentPageId).length
+ expect(draw(editor, [{ x: 50, y: 50 }])).toBeNull()
+ expect(editor.graph.getChildren(editor.state.currentPageId)).toHaveLength(before)
+ })
+
+ test('keeps more detail when drawn zoomed in', () => {
+ const vertices = (zoom: number) => {
+ const editor = pencilEditor()
+ editor.state.zoom = zoom
+ const id = draw(editor, sine())
+ return id ? (getNodeOrThrow(editor.graph, id).vectorNetwork?.vertices.length ?? 0) : 0
+ }
+ expect(vertices(0.5)).toBeLessThan(vertices(1))
+ expect(vertices(1)).toBeLessThan(vertices(2))
+ })
+
+ test('collapses a straight stroke to one segment', () => {
+ const editor = pencilEditor()
+ const id = draw(
+ editor,
+ Array.from({ length: 101 }, (_, i) => ({ x: 3 * i, y: 0 }))
+ )
+ const network = id ? getNodeOrThrow(editor.graph, id).vectorNetwork : undefined
+ expect(network?.vertices).toHaveLength(2)
+ expect(network?.segments[0]?.tangentStart).toEqual({ x: 0, y: 0 })
+ })
+
+ test('draws straight along the nearer axis while Shift is held', () => {
+ const editor = pencilEditor()
+ const id = draw(
+ editor,
+ Array.from({ length: 60 }, (_, i) => ({ x: 3 * i, y: 3 * i * Math.tan(Math.PI / 9) })),
+ { shift: true }
+ )
+ const node = id ? getNodeOrThrow(editor.graph, id) : undefined
+ expect(node?.vectorNetwork?.vertices.map((v) => v.y)).toEqual([0, 0])
+ expect(node?.width).toBe(177)
+
+ const vertical = draw(
+ editor,
+ Array.from({ length: 60 }, (_, i) => ({ x: 3 * i * 0.5, y: 3 * i })),
+ { shift: true }
+ )
+ expect(vertical && getNodeOrThrow(editor.graph, vertical).width).toBe(0)
+ })
+
+ test('closes a stroke that ends where it started, without a fill', () => {
+ const editor = pencilEditor()
+ const circle = Array.from({ length: 73 }, (_, t) => ({
+ x: 80 * Math.cos((t * 2 * Math.PI) / 72),
+ y: 80 * Math.sin((t * 2 * Math.PI) / 72)
+ }))
+ const id = draw(editor, circle)
+ const network = id ? getNodeOrThrow(editor.graph, id).vectorNetwork : undefined
+ expect(network?.segments.at(-1)?.end).toBe(0)
+ expect(network?.segments).toHaveLength(network?.vertices.length ?? -1)
+ expect(network?.regions).toEqual([])
+ })
+
+ test('goes into the given parent at its local position', () => {
+ const editor = pencilEditor()
+ const frame = editor.createShape('FRAME', -50, -100, 400, 200)
+ const id = draw(editor, sine(), { parentId: frame })
+ const node = id ? getNodeOrThrow(editor.graph, id) : undefined
+ expect(node?.parentId).toBe(frame)
+ expect(node?.x).toBe(50)
+ })
+
+ test('contrasts with what it is drawn on', () => {
+ const editor = pencilEditor()
+ editor.state.pageColor = DARK_PAGE
+ const onPage = draw(editor, sine())
+ expect(onPage && getNodeOrThrow(editor.graph, onPage).strokes[0]?.color).toMatchObject({
+ r: 1,
+ g: 1,
+ b: 1
+ })
+
+ const frame = editor.createShape('FRAME', -50, -100, 400, 200)
+ const inFrame = draw(editor, sine(), { parentId: frame })
+ expect(inFrame && getNodeOrThrow(editor.graph, inFrame).strokes[0]?.color).toMatchObject({
+ r: 0,
+ g: 0,
+ b: 0
+ })
+ })
+
+ test('takes the style of the last pencil layer once it is restyled', () => {
+ const editor = pencilEditor()
+ const first = draw(editor, sine())
+ if (!first) throw new Error('nothing drawn')
+ const red = { r: 1, g: 0, b: 0, a: 1 }
+ editor.graph.updateNode(first, {
+ strokes: [{ type: 'SOLID', color: red, opacity: 1, visible: true, weight: 6, align: 'CENTER' }]
+ })
+ editor.graph.deleteNode(first)
+
+ const second = draw(editor, sine(0, 100))
+ expect(second && getNodeOrThrow(editor.graph, second).strokes[0]).toMatchObject({
+ color: red,
+ weight: 6
+ })
+ expect(editor.state.pencilState).toBeNull()
+ })
+
+ test('shows the stroke being drawn in the colour it will have', () => {
+ const editor = pencilEditor()
+ editor.state.pageColor = DARK_PAGE
+ editor.pencilBegin(0, 0)
+ expect(editor.state.pencilState?.preview).toEqual({
+ color: { r: 1, g: 1, b: 1, a: 1 },
+ weight: 2
+ })
+ editor.pencilCancel()
+ expect(editor.state.pencilState).toBeNull()
+ })
+
+ test('undoes a stroke in one step', () => {
+ const editor = pencilEditor()
+ const id = draw(editor, sine())
+ if (!id) throw new Error('nothing drawn')
+ editor.undo.undo()
+ expect(editor.graph.getNode(id)).toBeUndefined()
+ editor.undo.redo()
+ expect(getNodeOrThrow(editor.graph, id).vectorNetwork?.segments.length).toBeGreaterThan(1)
+ })
+})
diff --git a/packages/core/tests/vector/freehand.test.ts b/packages/core/tests/vector/freehand.test.ts
new file mode 100644
index 000000000..362573a5a
--- /dev/null
+++ b/packages/core/tests/vector/freehand.test.ts
@@ -0,0 +1,163 @@
+import { describe, expect, test } from 'bun:test'
+
+import type { Vector } from '@open-pencil/scene-graph/primitives'
+
+import { freehandNetwork, simplifyFreehand } from '#core/vector/freehand'
+
+const round = (value: number) => Math.round(value * 100) / 100
+
+function knots(controls: Vector[], closed = false) {
+ const network = freehandNetwork(controls, closed)
+ return {
+ vertices: network.vertices.map((v) => [round(v.x), round(v.y)]),
+ segments: network.segments.map((s) => [
+ s.start,
+ s.end,
+ [round(s.tangentStart.x), round(s.tangentStart.y)],
+ [round(s.tangentEnd.x), round(s.tangentEnd.y)]
+ ]),
+ mirroring: network.vertices.map((v) => v.handleMirroring),
+ regions: network.regions
+ }
+}
+
+// Expected knots match Figma desktop's pencil for the same mouse samples, measured live.
+describe('freehandNetwork', () => {
+ test('rounds a corner as a B-spline knot', () => {
+ const { vertices, segments } = knots([
+ { x: 0, y: 0 },
+ { x: 100, y: 100 },
+ { x: 200, y: 0 }
+ ])
+ expect(vertices).toEqual([
+ [0, 0],
+ [100, 66.67],
+ [200, 0]
+ ])
+ expect(segments).toEqual([
+ [0, 1, [33.33, 33.33], [-33.33, 0]],
+ [1, 2, [33.33, 0], [-33.33, 33.33]]
+ ])
+ })
+
+ test('places each inner knot from its neighbours', () => {
+ const { vertices } = knots([
+ { x: 0, y: 0 },
+ { x: 100, y: 0 },
+ { x: 200, y: 0 },
+ { x: 200, y: 100 }
+ ])
+ expect(vertices).toEqual([
+ [0, 0],
+ [100, 0],
+ [183.33, 16.67],
+ [200, 100]
+ ])
+ })
+
+ test('keeps smooth vertices and no region', () => {
+ const { mirroring, regions } = knots([
+ { x: 0, y: 0 },
+ { x: 100, y: 100 },
+ { x: 200, y: 0 }
+ ])
+ expect(mirroring).toEqual(['ANGLE', 'ANGLE', 'ANGLE'])
+ expect(regions).toEqual([])
+ })
+
+ test('draws two controls as one straight segment', () => {
+ expect(
+ knots([
+ { x: 0, y: 0 },
+ { x: 300, y: 0 }
+ ]).segments
+ ).toEqual([[0, 1, [0, 0], [0, 0]]])
+ })
+
+ test('wraps a closed stroke round as one smooth outline', () => {
+ const { vertices, segments, regions } = knots(
+ [
+ { x: 0, y: 0 },
+ { x: 100, y: 0 },
+ { x: 100, y: 100 },
+ { x: 0, y: 100 },
+ { x: 2, y: 1 }
+ ],
+ true
+ )
+ expect(vertices).toEqual([
+ [16.67, 16.67],
+ [83.33, 16.67],
+ [83.33, 83.33],
+ [16.67, 83.33]
+ ])
+ expect(segments.at(-1)?.slice(0, 2)).toEqual([3, 0])
+ // The handles either side of the closing vertex mirror each other.
+ expect(segments.at(-1)?.[3]).toEqual([-16.67, 16.67])
+ expect(segments[0][2]).toEqual([16.67, -16.67])
+ expect(regions).toEqual([])
+ })
+})
+
+describe('simplifyFreehand', () => {
+ test('collapses a straight stroke to its ends', () => {
+ const line = Array.from({ length: 101 }, (_, i) => ({ x: 3 * i, y: 0 }))
+ expect(simplifyFreehand(line, 2)).toEqual([
+ { x: 0, y: 0 },
+ { x: 300, y: 0 }
+ ])
+ })
+
+ test('keeps the first sample after the press and the corners', () => {
+ const corner = [
+ ...Array.from({ length: 5 }, (_, i) => ({ x: 50 * i, y: 0 })),
+ ...Array.from({ length: 4 }, (_, i) => ({ x: 200, y: 50 * (i + 1) }))
+ ]
+ expect(simplifyFreehand(corner, 2)).toEqual([
+ { x: 0, y: 0 },
+ { x: 50, y: 0 },
+ { x: 200, y: 0 },
+ { x: 200, y: 200 }
+ ])
+ })
+
+ test('keeps about as many points however densely the stroke was sampled', () => {
+ const arc = (samples: number) =>
+ Array.from({ length: samples + 1 }, (_, i) => ({
+ x: 80 * Math.cos((Math.PI * i) / samples),
+ y: 80 * Math.sin((Math.PI * i) / samples)
+ }))
+ const sparse = simplifyFreehand(arc(72), 2).length
+ const dense = simplifyFreehand(arc(288), 2).length
+ expect(Math.abs(dense - sparse)).toBeLessThanOrEqual(1)
+ })
+
+ test('skips the first sample of a stroke that ends where it started', () => {
+ const square = [
+ { x: 0, y: 0 },
+ { x: 2, y: 0 },
+ { x: 100, y: 0 },
+ { x: 100, y: 100 },
+ { x: 0, y: 100 },
+ { x: 0, y: 1 }
+ ]
+ expect(simplifyFreehand(square, 2, true)).not.toContainEqual({ x: 2, y: 0 })
+ expect(simplifyFreehand(square, 2)).toContainEqual({ x: 2, y: 0 })
+ })
+
+ test('drops repeated samples', () => {
+ expect(
+ simplifyFreehand(
+ [
+ { x: 0, y: 0 },
+ { x: 0, y: 0 },
+ { x: 10, y: 0 }
+ ],
+ 2
+ )
+ ).toEqual([
+ { x: 0, y: 0 },
+ { x: 10, y: 0 }
+ ])
+ })
+})
diff --git a/packages/docs/overview/features.md b/packages/docs/overview/features.md
index 4e98dc9af..8632eb5aa 100644
--- a/packages/docs/overview/features.md
+++ b/packages/docs/overview/features.md
@@ -10,6 +10,7 @@ Open and save native Figma files directly. The import/export pipeline uses the s
- **Shapes** — Rectangle (<kbd>R</kbd>), Ellipse (<kbd>O</kbd>), Line (<kbd>L</kbd>), Polygon, Star
- **Pen tool** — vector networks (not simple paths), bezier curves with tangent handles
+- **Pencil** (<kbd>⇧</kbd><kbd>P</kbd>) — freehand strokes smoothed into editable curves
- **Text** — canvas-native editing with IME support, double-click to enter edit mode
- **Rich text** — per-character bold (<kbd>⌘</kbd><kbd>B</kbd>), italic (<kbd>⌘</kbd><kbd>I</kbd>), underline (<kbd>⌘</kbd><kbd>U</kbd>), strikethrough
- **Auto-layout** — flexbox and CSS Grid via Yoga WASM: direction, gap, padding, justify, align, child sizing, grid tracks. <kbd>⇧</kbd><kbd>A</kbd> to toggle
diff --git a/packages/docs/reference/figma-compatibility.md b/packages/docs/reference/figma-compatibility.md
index e803bb13a..da293cf4e 100644
--- a/packages/docs/reference/figma-compatibility.md
+++ b/packages/docs/reference/figma-compatibility.md
@@ -66,6 +66,7 @@ Feature-by-feature comparison of Figma Design capabilities with Open Pencil's cu
|---------|--------|-------|
| Vector networks | ✅ | Figma-compatible model, not simple paths |
| Pen tool | ✅ | Corner points, bezier curves, open/closed paths |
+| Pencil tool | ✅ | Freehand strokes smoothed into curves, <kbd>⇧</kbd> for straight lines |
| Edit vector layers | 🟡 | Creation works; advanced vertex editing (bend, delete points, join) limited |
| Boolean operations (Union, Subtract, Intersect, Exclude) | 🔲 | Combine shapes with boolean ops |
| Flatten layers | 🔲 | Merge vector paths into single path |
diff --git a/packages/docs/reference/keyboard-shortcuts.md b/packages/docs/reference/keyboard-shortcuts.md
index 93b5b382c..0458a7900 100644
--- a/packages/docs/reference/keyboard-shortcuts.md
+++ b/packages/docs/reference/keyboard-shortcuts.md
@@ -27,7 +27,7 @@ Full Figma-compatible shortcut map. ✅ = implemented.
| — | Star | ✅ (flyout only) |
| <kbd>⇧</kbd><kbd>L</kbd> | Arrow | 🔲 |
| <kbd>P</kbd> | Pen | ✅ |
-| <kbd>⇧</kbd><kbd>P</kbd> | Pencil | 🔲 |
+| <kbd>⇧</kbd><kbd>P</kbd> | Pencil | ✅ |
| <kbd>T</kbd> | Text | ✅ |
| <kbd>C</kbd> | Comment | ✅ |
| <kbd>I</kbd> | Eyedropper | 🔲 |
diff --git a/packages/docs/user-guide/pen-tool.md b/packages/docs/user-guide/pen-tool.md
index 6bce131fb..b8efe4529 100644
--- a/packages/docs/user-guide/pen-tool.md
+++ b/packages/docs/user-guide/pen-tool.md
@@ -30,11 +30,22 @@ Press <kbd>Escape</kbd> to commit the current path as an open path. Open paths r
Paths in OpenPencil use vector networks — a more flexible model than simple point lists that supports branching paths and complex topology. This is the same model Figma uses, so paths round-trip perfectly in .fig files.
+## Pencil
+
+Press <kbd>⇧</kbd><kbd>P</kbd>, or pick Pencil from the pen tool's menu in the toolbar, to draw freehand. Each stroke becomes its own vector layer, smoothed into curves you can edit like any other path, and the pencil stays active for the next stroke.
+
+- Zoom in to keep more detail: the curve follows your stroke to within a few screen pixels.
+- Hold <kbd>Shift</kbd> to draw straight, horizontally or vertically, from where you pressed it.
+- End a stroke where it started to close it into a loop.
+- A stroke goes into the frame that holds all of it, otherwise onto the page.
+- New strokes contrast with what they are drawn on. Change the stroke of the last one you drew, and the pencil keeps that style.
+
## Keyboard Shortcuts
| Action | Mac | Windows / Linux |
|--------|-----|-----------------|
| Pen tool | <kbd>P</kbd> | <kbd>P</kbd> |
+| Pencil | <kbd>⇧</kbd><kbd>P</kbd> | <kbd>Shift</kbd>+<kbd>P</kbd> |
| Commit open path | <kbd>Escape</kbd> | Escape |
## Tips
diff --git a/packages/vue/src/canvas/pencil/input.ts b/packages/vue/src/canvas/pencil/input.ts
new file mode 100644
index 000000000..b62dc9d6e
--- /dev/null
+++ b/packages/vue/src/canvas/pencil/input.ts
@@ -0,0 +1,29 @@
+import type { Editor } from '@open-pencil/core/editor'
+
+import { findEnclosingDrawParent } from '#vue/shared/input/drop-target'
+import type { DragState } from '#vue/shared/input/types'
+
+export function startPencilInput(
+ cx: number,
+ cy: number,
+ editor: Editor,
+ setDrag: (drag: DragState) => void
+) {
+ editor.pencilBegin(cx, cy)
+ setDrag({ type: 'pencil-drag' })
+}
+
+/** Holding Shift draws on straight from where it was pressed, horizontally or vertically. */
+export function handlePencilDragMove(cx: number, cy: number, shiftKey: boolean, editor: Editor) {
+ editor.pencilAddPoint(cx, cy, shiftKey)
+}
+
+/** Adds the stroke to the frame that holds all of it, or to the page. */
+export function finishPencilDrag(editor: Editor) {
+ const points = editor.state.pencilState?.points
+ if (!points || points.length === 0) {
+ editor.pencilCancel()
+ return
+ }
+ editor.pencilCommit(findEnclosingDrawParent(points, 'VECTOR', editor))
+}
diff --git a/packages/vue/src/canvas/tools/input.ts b/packages/vue/src/canvas/tools/input.ts
index e1855c1c8..1abaedc4e 100644
--- a/packages/vue/src/canvas/tools/input.ts
+++ b/packages/vue/src/canvas/tools/input.ts
@@ -3,6 +3,7 @@ import type { Ref } from 'vue'
import type { Editor } from '@open-pencil/core/editor'
import { startPenInput } from '#vue/canvas/pen/input'
+import { startPencilInput } from '#vue/canvas/pencil/input'
import { HAND_GRAB_CURSOR } from '#vue/editor/tool-cursor'
import { startShapeDraw, startTextDraw } from '#vue/shared/input/draw'
import { startPanDrag } from '#vue/shared/input/pan'
@@ -71,6 +72,11 @@ export function handleToolMouseDown({
return
}
+ if (tool === 'PENCIL') {
+ startPencilInput(cx, cy, editor, setDrag)
+ return
+ }
+
if (tool === 'TEXT') {
startTextDraw(cx, cy, editor, setDrag)
return
diff --git a/packages/vue/src/canvas/useCanvasInput.ts b/packages/vue/src/canvas/useCanvasInput.ts
index e33b1df1a..96a705d4f 100644
--- a/packages/vue/src/canvas/useCanvasInput.ts
+++ b/packages/vue/src/canvas/useCanvasInput.ts
@@ -8,6 +8,7 @@ import { createAutoLayoutValueEdit } from '#vue/canvas/auto-layout/value-edit'
import { createGuideInput, selectedTopLevelGuideFrameId } from '#vue/canvas/guides/input'
import { createCanvasLabelEdit } from '#vue/canvas/labels/edit'
import { handlePenDragMove, updatePenHover } from '#vue/canvas/pen/input'
+import { finishPencilDrag, handlePencilDragMove } from '#vue/canvas/pencil/input'
import { createCanvasPointer } from '#vue/canvas/pointer/use'
import { createTextEditInput } from '#vue/canvas/text-edit/input'
import { handleToolMouseDown } from '#vue/canvas/tools/input'
@@ -308,6 +309,11 @@ export function useCanvasInput(
return
}
+ if (d.type === 'pencil-drag') {
+ handlePencilDragMove(cx, cy, e.shiftKey, editor)
+ return
+ }
+
if (d.type === 'edit-node' || d.type === 'edit-handle') {
handleNodeEditMove(d, cx, cy, editor, e.altKey, e.metaKey || e.ctrlKey, e.shiftKey, e.ctrlKey)
return
@@ -350,7 +356,8 @@ export function useCanvasInput(
}
drag.value = null
return
- } else if (d.type === 'rotate') {
+ } else if (d.type === 'pencil-drag') finishPencilDrag(editor)
+ else if (d.type === 'rotate') {
const preview = editor.state.rotationPreview
if (preview?.nodeId === d.nodeId && preview.angle !== d.origRotation) {
editor.updateNode(d.nodeId, { rotation: preview.angle })
@@ -373,8 +380,14 @@ export function useCanvasInput(
guideInput.clearHoverAndPreview()
}
+ /** Drops what a resize or pencil stroke showed without changing the document. */
+ function discardDrawnPreview(d: DragState) {
+ if (d.type === 'resize') cancelResizePreview(d, editor)
+ else if (d.type === 'pencil-drag') editor.pencilCancel()
+ }
+
function cancelPointerInteraction() {
- if (drag.value?.type === 'resize') cancelResizePreview(drag.value, editor)
+ if (drag.value) discardDrawnPreview(drag.value)
if (drag.value?.type === 'rotate') {
const rotation = drag.value
drag.value = null
diff --git a/packages/vue/src/editor/tool-cursor/index.ts b/packages/vue/src/editor/tool-cursor/index.ts
index a496701d2..071ec203b 100644
--- a/packages/vue/src/editor/tool-cursor/index.ts
+++ b/packages/vue/src/editor/tool-cursor/index.ts
@@ -4,6 +4,7 @@ import commentCursorSVG from '#vue/shared/assets/cursors/comment.svg?raw'
import handGrabCursorSVG from '#vue/shared/assets/cursors/hand-grab.svg?raw'
import handCursorSVG from '#vue/shared/assets/cursors/hand.svg?raw'
import penCursorSVG from '#vue/shared/assets/cursors/pen.svg?raw'
+import pencilCursorSVG from '#vue/shared/assets/cursors/pencil.svg?raw'
function svgCursor(svg: string, x: number, y: number, fallback: string): string {
return `url("data:image/svg+xml,${encodeURIComponent(svg)}") ${x} ${y}, ${fallback}`
@@ -11,6 +12,8 @@ function svgCursor(svg: string, x: number, y: number, fallback: string): string
/** The pen nib, pointing at its tip. */
export const PEN_CURSOR = svgCursor(penCursorSVG, 4, 4, 'crosshair')
+/** The pencil, pointing at its tip in the lower left. */
+const PENCIL_CURSOR = svgCursor(pencilCursorSVG, 4, 20, 'crosshair')
/** A speech bubble whose tail tip places the comment pin. */
const COMMENT_CURSOR = svgCursor(commentCursorSVG, 5, 24, 'crosshair')
/** The open hand of the hand tool. */
@@ -29,6 +32,7 @@ const TOOL_CURSORS: Record<Tool, string> = {
STAR: 'crosshair',
TEXT: 'text',
PEN: PEN_CURSOR,
+ PENCIL: PENCIL_CURSOR,
HAND: HAND_CURSOR,
COMMENT: COMMENT_CURSOR
}
diff --git a/packages/vue/src/i18n/locales/de/tools.json b/packages/vue/src/i18n/locales/de/tools.json
index cf9769adc..0608a1892 100644
--- a/packages/vue/src/i18n/locales/de/tools.json
+++ b/packages/vue/src/i18n/locales/de/tools.json
@@ -8,6 +8,7 @@
"polygon": "Polygon",
"star": "Stern",
"pen": "Stift",
+ "pencil": "Bleistift",
"text": "Text",
"hand": "Hand",
"comment": "Kommentar"
diff --git a/packages/vue/src/i18n/locales/es/tools.json b/packages/vue/src/i18n/locales/es/tools.json
index 042ba1337..efae826c1 100644
--- a/packages/vue/src/i18n/locales/es/tools.json
+++ b/packages/vue/src/i18n/locales/es/tools.json
@@ -8,6 +8,7 @@
"polygon": "Polígono",
"star": "Estrella",
"pen": "Pluma",
+ "pencil": "Lápiz",
"text": "Texto",
"hand": "Mano",
"comment": "Comentario"
diff --git a/packages/vue/src/i18n/locales/fr/tools.json b/packages/vue/src/i18n/locales/fr/tools.json
index 8e8777c3c..e6efa5c28 100644
--- a/packages/vue/src/i18n/locales/fr/tools.json
+++ b/packages/vue/src/i18n/locales/fr/tools.json
@@ -8,6 +8,7 @@
"polygon": "Polygone",
"star": "Étoile",
"pen": "Plume",
+ "pencil": "Crayon",
"text": "Texte",
"hand": "Main",
"comment": "Commentaire"
diff --git a/packages/vue/src/i18n/locales/it/tools.json b/packages/vue/src/i18n/locales/it/tools.json
index b00d02ec9..5e2569228 100644
--- a/packages/vue/src/i18n/locales/it/tools.json
+++ b/packages/vue/src/i18n/locales/it/tools.json
@@ -8,6 +8,7 @@
"polygon": "Poligono",
"star": "Stella",
"pen": "Penna",
+ "pencil": "Matita",
"text": "Testo",
"hand": "Mano",
"comment": "Commento"
diff --git a/packages/vue/src/i18n/locales/ja/tools.json b/packages/vue/src/i18n/locales/ja/tools.json
index 73d4e1bb5..c4007d9ea 100644
--- a/packages/vue/src/i18n/locales/ja/tools.json
+++ b/packages/vue/src/i18n/locales/ja/tools.json
@@ -8,6 +8,7 @@
"polygon": "多角形",
"star": "スター",
"pen": "ペンツール",
+ "pencil": "鉛筆",
"text": "テキスト",
"hand": "手のひらツール",
"comment": "コメント"
diff --git a/packages/vue/src/i18n/locales/pl/tools.json b/packages/vue/src/i18n/locales/pl/tools.json
index 20151c6cb..817b8b4bd 100644
--- a/packages/vue/src/i18n/locales/pl/tools.json
+++ b/packages/vue/src/i18n/locales/pl/tools.json
@@ -8,6 +8,7 @@
"polygon": "Wielokąt",
"star": "Gwiazda",
"pen": "Pióro",
+ "pencil": "Ołówek",
"text": "Tekst",
"hand": "Dłoń",
"comment": "Komentarz"
diff --git a/packages/vue/src/i18n/locales/ru/tools.json b/packages/vue/src/i18n/locales/ru/tools.json
index d639bcfeb..f92e8cc28 100644
--- a/packages/vue/src/i18n/locales/ru/tools.json
+++ b/packages/vue/src/i18n/locales/ru/tools.json
@@ -8,6 +8,7 @@
"polygon": "Многоугольник",
"star": "Звезда",
"pen": "Перо",
+ "pencil": "Карандаш",
"text": "Текст",
"hand": "Рука",
"comment": "Комментарий"
diff --git a/packages/vue/src/i18n/locales/zh-cn/tools.json b/packages/vue/src/i18n/locales/zh-cn/tools.json
index 549696aaa..c3160d632 100644
--- a/packages/vue/src/i18n/locales/zh-cn/tools.json
+++ b/packages/vue/src/i18n/locales/zh-cn/tools.json
@@ -8,6 +8,7 @@
"polygon": "多边形",
"star": "星形",
"pen": "钢笔",
+ "pencil": "铅笔",
"text": "文本",
"hand": "抓手",
"comment": "评论"
diff --git a/packages/vue/src/i18n/messages/tools.ts b/packages/vue/src/i18n/messages/tools.ts
index 6471d9848..745df484b 100644
--- a/packages/vue/src/i18n/messages/tools.ts
+++ b/packages/vue/src/i18n/messages/tools.ts
@@ -10,6 +10,7 @@ export const toolMessageDefaults = {
polygon: 'Polygon',
star: 'Star',
pen: 'Pen',
+ pencil: 'Pencil',
text: 'Text',
hand: 'Hand',
comment: 'Comment'
diff --git a/packages/vue/src/shared/assets/cursors/pencil.svg b/packages/vue/src/shared/assets/cursors/pencil.svg
new file mode 100644
index 000000000..45a984d3c
--- /dev/null
+++ b/packages/vue/src/shared/assets/cursors/pencil.svg
@@ -0,0 +1,18 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
+ <filter id="shadow" x="-50%" y="-50%" width="200%" height="200%">
+ <feDropShadow dx="0" dy="1.25" stdDeviation="1" flood-opacity="0.5"/>
+ </filter>
+ <g filter="url(#shadow)" stroke-linecap="round" stroke-linejoin="round">
+ <g transform="translate(2.16 2.16) scale(0.8)">
+ <g fill="#fff" stroke="#fff" stroke-width="3.75">
+ <path d="M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"/>
+ </g>
+ <g fill="#fff">
+ <path d="M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"/>
+ </g>
+ <g fill="none" stroke="#000" stroke-width="1.25">
+ <path d="M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497zM15 5l4 4"/>
+ </g>
+ </g>
+ </g>
+</svg>
diff --git a/packages/vue/src/shared/input/drop-target.ts b/packages/vue/src/shared/input/drop-target.ts
index 86e4391ad..72cbc493a 100644
--- a/packages/vue/src/shared/input/drop-target.ts
+++ b/packages/vue/src/shared/input/drop-target.ts
@@ -1,5 +1,8 @@
import type { Editor } from '@open-pencil/core/editor'
import { cycleSafeParent, type NodeType, type SceneNode } from '@open-pencil/scene-graph'
+import { getWorldMatrix } from '@open-pencil/scene-graph/coordinate'
+import Matrix from '@open-pencil/scene-graph/matrix'
+import type { Vector } from '@open-pencil/scene-graph/primitives'
/** Parents a layer stays in while dragged until it lands on another frame. */
const ENCLOSING_TYPES = new Set<NodeType>(['GROUP', 'BOOLEAN_OPERATION'])
@@ -66,6 +69,45 @@ export function findDrawParent(cx: number, cy: number, type: NodeType, editor: E
return acceptingTarget(target, editor)?.id ?? editor.state.currentPageId
}
+/** Whether every canvas point lies inside the container's own box, rotated or flipped with it. */
+function holdsPoints(target: SceneNode, points: readonly Vector[], editor: Editor): boolean {
+ const toLocal = Matrix.invert(getWorldMatrix(target, editor.graph))
+ if (!toLocal) return false
+ const local = Matrix.mapPoints(
+ toLocal,
+ points.flatMap((point) => [point.x, point.y])
+ )
+ for (let i = 0; i < local.length; i += 2) {
+ const [x, y] = [local[i], local[i + 1]]
+ if (x < 0 || y < 0 || x > target.width || y > target.height) return false
+ }
+ return true
+}
+
+/**
+ * The parent a layer drawn through `points` goes into: the one it would go into from the first
+ * point, or the nearest container above that holds all of them, as Figma places a pencil stroke.
+ */
+export function findEnclosingDrawParent(
+ points: readonly Vector[],
+ type: NodeType,
+ editor: Editor
+): string {
+ const pageId = editor.state.currentPageId
+ const start = points.at(0)
+ if (!start) return pageId
+ let target = editor.graph.getNode(findDrawParent(start.x, start.y, type, editor))
+ while (target && target.type !== 'CANVAS') {
+ if (holdsPoints(target, points, editor)) return target.id
+ let parent = target.parentId ? editor.graph.getNode(target.parentId) : undefined
+ while (parent && parent.type !== 'CANVAS' && !takesDrawnLayer(parent, type)) {
+ parent = parent.parentId ? editor.graph.getNode(parent.parentId) : undefined
+ }
+ target = acceptingTarget(parent ?? null, editor) ?? undefined
+ }
+ return pageId
+}
+
/** The frame or page that holds a layer, looking past the groups it sits in. */
function enclosingContainer(id: string, editor: Editor): string {
let parent = editor.graph.getNode(editor.graph.getNode(id)?.parentId ?? '')
diff --git a/packages/vue/src/shared/input/types.ts b/packages/vue/src/shared/input/types.ts
index 356c0d1bd..6a3f40a4c 100644
--- a/packages/vue/src/shared/input/types.ts
+++ b/packages/vue/src/shared/input/types.ts
@@ -130,6 +130,10 @@ export interface DragPen {
knotStartY: number
}
+export interface DragPencil {
+ type: 'pencil-drag'
+}
+
export interface DragTextSelect {
type: 'text-select'
startX: number
@@ -208,6 +212,7 @@ export type DragState =
| DragMarquee
| DragRotate
| DragPen
+ | DragPencil
| DragTextSelect
| DragEditNode
| DragEditHandle
diff --git a/packages/vue/tests/canvas/pencil/input.test.ts b/packages/vue/tests/canvas/pencil/input.test.ts
new file mode 100644
index 000000000..4566c8e71
--- /dev/null
+++ b/packages/vue/tests/canvas/pencil/input.test.ts
@@ -0,0 +1,91 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test'
+
+import { createEditor, type Editor } from '@open-pencil/core/editor'
+import type { SceneNode } from '@open-pencil/scene-graph'
+import { getWorldMatrix } from '@open-pencil/scene-graph/coordinate'
+import Matrix from '@open-pencil/scene-graph/matrix'
+import type { Vector } from '@open-pencil/scene-graph/primitives'
+
+import { finishPencilDrag, handlePencilDragMove, startPencilInput } from '#vue/canvas/pencil/input'
+
+let editor: Editor
+
+afterEach(() => editor.dispose())
+
+function setup() {
+ editor = createEditor()
+ editor.setTool('PENCIL')
+ return editor.state.currentPageId
+}
+
+function frame(parentId: string, props: Partial<SceneNode>) {
+ return editor.graph.createNode('FRAME', parentId, props)
+}
+
+/** Draws through canvas points and returns the parent the stroke went into. */
+function stroke(points: Vector[]) {
+ const [first, ...rest] = points
+ startPencilInput(first.x, first.y, editor, mock())
+ for (const point of rest) handlePencilDragMove(point.x, point.y, false, editor)
+ const before = new Set([...editor.graph.getAllNodes()].map((node) => node.id))
+ finishPencilDrag(editor)
+ const vector = [...editor.graph.getAllNodes()].find(
+ (node) => node.type === 'VECTOR' && !before.has(node.id)
+ )
+ if (!vector?.parentId) throw new Error('Expected a pencil stroke')
+ return vector.parentId
+}
+
+function wave(x0: number, y0: number, length: number) {
+ return Array.from({ length: 21 }, (_, i) => ({
+ x: x0 + (length * i) / 20,
+ y: y0 + 10 * Math.sin((i / 20) * 2 * Math.PI)
+ }))
+}
+
+/** Canvas points for points in a layer's own axes. */
+function inLayer(layer: SceneNode, points: Vector[]): Vector[] {
+ const world = Matrix.mapPoints(
+ getWorldMatrix(layer, editor.graph),
+ points.flatMap((point) => [point.x, point.y])
+ )
+ return points.map((_, i) => ({ x: world[2 * i], y: world[2 * i + 1] }))
+}
+
+// Measured in Figma desktop: a stroke goes into the frame that holds all of it.
+describe('pencil parent', () => {
+ test('goes into the frame that holds the whole stroke', () => {
+ const page = setup()
+ const host = frame(page, { x: 0, y: 0, width: 400, height: 200 })
+ expect(stroke(wave(50, 100, 300))).toBe(host.id)
+ })
+
+ test('goes onto the page when the stroke leaves the frame it started in', () => {
+ const page = setup()
+ frame(page, { x: 0, y: 0, width: 200, height: 200 })
+ expect(stroke(wave(50, 100, 300))).toBe(page)
+ })
+
+ test('goes into the outer frame when it leaves the inner one', () => {
+ const page = setup()
+ const outer = frame(page, { x: 0, y: 0, width: 600, height: 400 })
+ frame(outer.id, { x: 20, y: 20, width: 150, height: 150 })
+ expect(stroke(wave(50, 100, 300))).toBe(outer.id)
+ })
+
+ test('checks a rotated frame by its own box, not the box around it', () => {
+ const page = setup()
+ const band = frame(page, { x: 200, y: 100, width: 300, height: 40, rotation: 45 })
+ expect(stroke(inLayer(band, wave(20, 20, 260).map((p) => ({ x: p.x, y: 20 }))))).toBe(band.id)
+ // Leaves the band sideways while staying inside its axis-aligned bounds.
+ expect(
+ stroke(
+ inLayer(band, [
+ { x: 150, y: 20 },
+ { x: 150, y: 60 },
+ { x: 150, y: 90 }
+ ])
+ )
+ ).toBe(page)
+ })
+})
diff --git a/src/app/editor/icons.ts b/src/app/editor/icons.ts
index 44d61291e..1b6ffbd31 100644
--- a/src/app/editor/icons.ts
+++ b/src/app/editor/icons.ts
@@ -12,6 +12,7 @@ import IconMessageCircle from '~icons/lucide/message-circle'
import IconMinus from '~icons/lucide/minus'
import IconMousePointer from '~icons/lucide/mouse-pointer'
import IconPenTool from '~icons/lucide/pen-tool'
+import IconPencil from '~icons/lucide/pencil'
import IconRows from '~icons/lucide/rows-3'
import IconSmile from '~icons/lucide/smile'
import IconSquare from '~icons/lucide/square'
@@ -34,6 +35,7 @@ export const toolIcons: Record<Tool, Component> = {
POLYGON: IconTriangle,
STAR: IconStar,
PEN: IconPenTool,
+ PENCIL: IconPencil,
TEXT: IconType,
HAND: IconHand,
COMMENT: IconMessageCircle
diff --git a/src/app/editor/toolbar/shortcuts.ts b/src/app/editor/toolbar/shortcuts.ts
index bf2229bb5..c66698eae 100644
--- a/src/app/editor/toolbar/shortcuts.ts
+++ b/src/app/editor/toolbar/shortcuts.ts
@@ -14,6 +14,7 @@ const TOOL_SHORTCUT_KEYS: Readonly<Record<Tool, string>> = {
POLYGON: '',
STAR: '',
PEN: 'P',
+ PENCIL: 'SHIFT+P',
TEXT: 'T',
HAND: 'H',
COMMENT: 'C'
diff --git a/src/app/shell/keyboard/actions.ts b/src/app/shell/keyboard/actions.ts
index b5f93d922..acf56ce65 100644
--- a/src/app/shell/keyboard/actions.ts
+++ b/src/app/shell/keyboard/actions.ts
@@ -76,6 +76,10 @@ export function createKeyboardActions({
store.exitNodeEditMode(true)
return
}
+ if (store.state.pencilState) {
+ store.pencilCancel()
+ return
+ }
// Figma keeps the path drawn so far; a lone point has nothing to keep.
if (store.state.penState) {
if (store.state.penState.vertices.length >= 2) store.penCommit(false)
diff --git a/src/components/toolbar/labels.ts b/src/components/toolbar/labels.ts
index 6ee54caf0..1e1f3c5dc 100644
--- a/src/components/toolbar/labels.ts
+++ b/src/components/toolbar/labels.ts
@@ -19,6 +19,7 @@ export function useToolLabels() {
POLYGON: tools.value.polygon,
STAR: tools.value.star,
PEN: tools.value.pen,
+ PENCIL: tools.value.pencil,
TEXT: tools.value.text,
HAND: tools.value.hand,
COMMENT: tools.value.comment
diff --git a/tests/app/editor/toolbar/layout.test.ts b/tests/app/editor/toolbar/layout.test.ts
index fcbdc446b..6cc0b2d10 100644
--- a/tests/app/editor/toolbar/layout.test.ts
+++ b/tests/app/editor/toolbar/layout.test.ts
@@ -59,7 +59,7 @@ describe('normalizeToolbarLayout', () => {
['SELECT'],
['FRAME', 'SECTION'],
SHAPES,
- ['PEN'],
+ ['PEN', 'PENCIL'],
['HAND'],
['COMMENT'],
['insert-icon']
@@ -114,8 +114,8 @@ describe('editing', () => {
})
test('a button swaps with the button or flyout next to it', () => {
- const moved = moveToolbarEntry(base, 'PEN', -1)
- expect(moved.groups.slice(2, 4)).toEqual([['PEN'], SHAPES])
+ const moved = moveToolbarEntry(base, 'TEXT', -1)
+ expect(moved.groups.slice(3, 5)).toEqual([['TEXT'], ['PEN', 'PENCIL']])
expect(moveToolbarEntry(base, 'SELECT', -1)).toBe(base)
})
@@ -130,7 +130,7 @@ describe('editing', () => {
test('joining merges a group into the one above', () => {
const joined = joinToolbarEntry(base, 'TEXT')
- expect(joined.groups[3]).toEqual(['PEN', 'TEXT'])
+ expect(joined.groups[3]).toEqual(['PEN', 'PENCIL', 'TEXT'])
expect(joinToolbarEntry(base, 'insert-icon')).toBe(base)
expect(joinToolbarEntry(base, 'SELECT')).toBe(base)
expect(joinToolbarEntry(base, 'LINE')).toBe(base)
@@ -141,7 +141,7 @@ describe('editing', () => {
['RECTANGLE', 'LINE', 'POLYGON', 'STAR'],
['ELLIPSE']
])
- expect(detachToolbarEntry(base, 'PEN')).toBe(base)
+ expect(detachToolbarEntry(base, 'TEXT')).toBe(base)
})
test('rows say how each entry relates to the one above', () => {
@@ -186,7 +186,7 @@ describe('dragging', () => {
test('a flyout member dragged to the gap leaves its flyout', () => {
const flat = base.groups.flat().filter((entry) => entry !== 'SECTION')
const dropped = placeToolbarEntry(base, 'SECTION', flat.indexOf('PEN'))
- expect(dropped.groups.slice(1, 5)).toEqual([['FRAME'], SHAPES, ['SECTION'], ['PEN']])
+ expect(dropped.groups.slice(1, 5)).toEqual([['FRAME'], SHAPES, ['SECTION'], ['PEN', 'PENCIL']])
})
test('a command never lands inside a flyout', () => {
diff --git a/tests/e2e/canvas/tool-cursors.spec.ts b/tests/e2e/canvas/tool-cursors.spec.ts
index 2640e8389..57d3ed497 100644
--- a/tests/e2e/canvas/tool-cursors.spec.ts
+++ b/tests/e2e/canvas/tool-cursors.spec.ts
@@ -37,6 +37,19 @@ test('the pen keeps its nib cursor while placing points', async () => {
await editor.page.keyboard.press('Escape')
})
+test('the pencil points with its tip while drawing', async () => {
+ await editor.page.keyboard.press('Shift+KeyP')
+ expect(await canvasCursor()).toBe('4 20, crosshair')
+
+ const box = expectDefined(await editor.canvas.canvas.boundingBox(), 'canvas bounds')
+ await editor.page.mouse.move(box.x + 200, box.y + 200)
+ await editor.page.mouse.down()
+ await editor.page.mouse.move(box.x + 280, box.y + 240, { steps: 4 })
+ expect(await canvasCursor()).toBe('4 20, crosshair')
+ await editor.page.mouse.up()
+ await editor.page.keyboard.press('v')
+})
+
test('the comment tool shows a speech bubble pointing with its tail', async () => {
await editor.page.keyboard.press('c')
const cursor = commentsCapture().evaluate((el) => (el as HTMLElement).style.cursor)
diff --git a/tests/e2e/canvas/vector/pencil.spec.ts b/tests/e2e/canvas/vector/pencil.spec.ts
new file mode 100644
index 000000000..311c2d8ed
--- /dev/null
+++ b/tests/e2e/canvas/vector/pencil.spec.ts
@@ -0,0 +1,69 @@
+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'
+
+const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')
+
+async function canvasBox() {
+ const box = await editor.canvas.canvas.boundingBox()
+ if (!box) throw new Error('Canvas bounds unavailable')
+ return box
+}
+
+async function pencilState() {
+ return editor.page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const vectors = store.graph
+ .getChildren(store.state.currentPageId)
+ .filter((node) => node.type === 'VECTOR')
+ .map((node) => ({
+ vertices: node.vectorNetwork?.vertices.length ?? 0,
+ y: node.vectorNetwork?.vertices.map((vertex) => vertex.y),
+ strokes: node.strokes.length,
+ fills: node.fills.length
+ }))
+ return { tool: store.state.activeTool, selected: store.state.selectedIds.size, vectors }
+ })
+}
+
+test('Shift+P draws freehand strokes and stays on the pencil', async () => {
+ const box = await canvasBox()
+ await editor.page.mouse.click(box.x + 40, box.y + 40)
+ await editor.page.keyboard.press('Shift+KeyP')
+
+ await editor.page.mouse.move(box.x + 120, box.y + 200)
+ await editor.page.mouse.down()
+ for (let i = 1; i <= 60; i++) {
+ await editor.page.mouse.move(
+ box.x + 120 + 5 * i,
+ box.y + 200 + 40 * Math.sin((i / 60) * 2 * Math.PI)
+ )
+ }
+ await editor.canvas.waitForRender()
+ editor.canvas.assertNoErrors()
+ expect(await editor.canvas.screenshotCanvasRegion()).toMatchSnapshot('pencil-live-stroke.png')
+ await editor.page.mouse.up()
+
+ // Shift draws straight along the nearer axis.
+ await editor.page.mouse.move(box.x + 120, box.y + 320)
+ await editor.page.mouse.down()
+ await editor.page.keyboard.down('Shift')
+ await editor.page.mouse.move(box.x + 300, box.y + 350, { steps: 10 })
+ await editor.page.keyboard.up('Shift')
+ await editor.page.mouse.up()
+
+ const state = await pencilState()
+ expect(state.tool).toBe('PENCIL')
+ expect(state.selected).toBe(0)
+ expect(state.vectors).toHaveLength(2)
+ expect(state.vectors[0]).toMatchObject({ strokes: 1, fills: 0 })
+ expect(state.vectors[0].vertices).toBeGreaterThan(2)
+ expect(state.vectors[1]).toMatchObject({ vertices: 2, y: [0, 0] })
+})
+
+test('a click without dragging draws nothing', async () => {
+ const box = await canvasBox()
+ await editor.page.mouse.click(box.x + 40, box.y + 40)
+ await editor.page.keyboard.press('Shift+KeyP')
+ await editor.page.mouse.click(box.x + 200, box.y + 200)
+ expect((await pencilState()).vectors).toHaveLength(0)
+})
diff --git a/tests/e2e/canvas/vector/pencil.spec.ts-snapshots/pencil-live-stroke-openpencil-darwin.png b/tests/e2e/canvas/vector/pencil.spec.ts-snapshots/pencil-live-stroke-openpencil-darwin.png
new file mode 100644
index 000000000..2cab79741
Binary files /dev/null and b/tests/e2e/canvas/vector/pencil.spec.ts-snapshots/pencil-live-stroke-openpencil-darwin.png differ
diff --git a/tests/e2e/toolbar/basic.spec.ts b/tests/e2e/toolbar/basic.spec.ts
index bcad1bc36..167a95069 100644
--- a/tests/e2e/toolbar/basic.spec.ts
+++ b/tests/e2e/toolbar/basic.spec.ts
@@ -91,7 +91,7 @@ test('Pen creates VECTOR node with 3 vertices on Enter', async () => {
editor.canvas.assertNoErrors()
})
-test('Pen Escape with 2 vertices cancels path without creating node', async () => {
+test('Pen Escape with 2 vertices keeps the open path', async () => {
const before = (await getPageChildren(editor.page)).filter((n) => n.type === 'VECTOR').length
await editor.canvas.pressKey('p')
@@ -102,8 +102,9 @@ test('Pen Escape with 2 vertices cancels path without creating node', async () =
await editor.canvas.pressKey('Escape')
await editor.canvas.waitForRender()
+ // Figma keeps the path drawn so far.
const after = (await getPageChildren(editor.page)).filter((n) => n.type === 'VECTOR').length
- expect(after).toBe(before)
+ expect(after).toBe(before + 1)
editor.canvas.assertNoErrors()
})
diff --git a/tests/e2e/toolbar/customize.spec.ts b/tests/e2e/toolbar/customize.spec.ts
index c6c05e21d..f1e0f744f 100644
--- a/tests/e2e/toolbar/customize.spec.ts
+++ b/tests/e2e/toolbar/customize.spec.ts
@@ -29,7 +29,8 @@ test('the toolbar hides, reorders and regroups tools from Settings and keeps the
const settings = page.getByTestId('settings-toolbar-panel')
await expect(settings).toBeVisible()
- await settings.getByRole('switch', { name: 'Show Pen' }).click()
+ await settings.getByRole('switch', { name: 'Show Pen', exact: true }).click()
+ await settings.getByRole('switch', { name: 'Show Pencil', exact: true }).click()
// Dropping Comment onto Hand puts both in one menu; Text's grip moves it with the keyboard.
await settings
.getByRole('button', { name: 'Reorder Comment' })
@@ -40,6 +41,7 @@ test('the toolbar hides, reorders and regroups tools from Settings and keeps the
const expectCustomized = async () => {
await expect(page.getByTestId(toolbarToolTestId('PEN'))).toHaveCount(0)
+ await expect(page.getByTestId(toolbarToolTestId('PENCIL'))).toHaveCount(0)
expect(await toolbarOrder(page)).toEqual(
(['SELECT', 'FRAME', 'RECTANGLE', 'TEXT', 'HAND'] as const).map((tool) =>
toolbarToolTestId(tool)
diff --git a/tests/engine/render/canvas/renderer-lifecycle.test.ts b/tests/engine/render/canvas/renderer-lifecycle.test.ts
index f04493740..b6ab918a6 100644
--- a/tests/engine/render/canvas/renderer-lifecycle.test.ts
+++ b/tests/engine/render/canvas/renderer-lifecycle.test.ts
@@ -57,6 +57,7 @@ function createRenderer() {
rulerLabelPaint: deletable<Paint>(),
penPathPaint: deletable<Paint>(),
penLiveStrokePaint: deletable<Paint>(),
+ pencilStrokePaint: deletable<Paint>(),
penHandlePaint: deletable<Paint>(),
penVertexFill: deletable<Paint>(),
penVertexStroke: deletable<Paint>(),
@@ -98,10 +99,12 @@ test('destroyRenderer deletes all renderer-owned paints and label fonts', () =>
const parentOutlinePaint = renderer.parentOutlinePaint
const sectionTitleFont = renderer.sectionTitleFont
const componentLabelFont = renderer.componentLabelFont
+ const pencilStrokePaint = renderer.pencilStrokePaint
destroyRenderer(renderer)
expect(parentOutlinePaint.delete).toHaveBeenCalled()
+ expect(pencilStrokePaint.delete).toHaveBeenCalled()
expect(sectionTitleFont?.delete).toHaveBeenCalled()
expect(componentLabelFont?.delete).toHaveBeenCalled()
})