AI-native design editor. Open-source Figma alternative.
feat: add a sticky note tool with FigJam's editing (#1224)
Danila Poyarkov4be77164b869
diff --git a/changes/1224/added.md b/changes/1224/added.mdnew file mode 100644index 000000000..9f3104395--- /dev/null+++ b/changes/1224/added.md@@ -0,0 +1 @@+- A sticky note tool, shown from Customize toolbar, places FigJam sticky notes to type into. Their handles scale them or make them wide as in FigJam, the Design panel sets their colour, text size, and author line, and scripts read and edit them as Figma's `StickyNode` (#1118).diff --git a/packages/core/src/canvas/overlays/selection.ts b/packages/core/src/canvas/overlays/selection.tsindex 7112ac7a6..6a45bca1b 100644--- a/packages/core/src/canvas/overlays/selection.ts+++ b/packages/core/src/canvas/overlays/selection.ts@@ -287,7 +287,10 @@ function drawTextPathSelection()}-/** Figma's corner handles and our rotation stalk; a layer too small for handles shows none. */+/**+ * Figma's corner handles and our rotation stalk, absent for a layer that does not turn; a layer+ * too small for handles shows none.+ */function drawBoundsHandles(r: SkiaRenderer,canvas: Canvas,@@ -295,13 +298,14 @@ function drawBoundsHandles(minY: number,maxX: number,maxY: number,- stalk: RotationHandleLayout+ stalk: RotationHandleLayout | null): void {if (!hasTransformHandles((maxX - minX) * r.zoom, (maxY - minY) * r.zoom)) returnr.drawHandle(canvas, minX, minY)r.drawHandle(canvas, maxX, minY)r.drawHandle(canvas, minX, maxY)r.drawHandle(canvas, maxX, maxY)+ if (!stalk) returncanvas.drawLine(stalk.edge.x, stalk.edge.y, stalk.handle.x, stalk.handle.y, r.selectionPaint)r.drawHandle(canvas, stalk.handle.x, stalk.handle.y)}@@ -351,12 +355,15 @@ export function drawNodeSelection(y1,x2,y2,- rotationHandleLayout(node, createSceneGeometry(graph, preview), r.zoom, {- x: x1,- y: y1,- width: x2 - x1,- height: y2 - y1- })+ // FigJam keeps sticky notes upright.+ node.type === 'STICKY'+ ? null+ : rotationHandleLayout(node, createSceneGeometry(graph, preview), r.zoom, {+ x: x1,+ y: y1,+ width: x2 - x1,+ height: y2 - y1+ }))},previewdiff --git a/packages/core/src/canvas/renderer.ts b/packages/core/src/canvas/renderer.tsindex ef852745e..ea8a3a16e 100644--- a/packages/core/src/canvas/renderer.ts+++ b/packages/core/src/canvas/renderer.ts@@ -168,6 +168,11 @@ export class SkiaRenderer {navigationPhase: EditorState['navigation']['phase'] = 'idle'navigationGeneration = 0tiledSceneEnabled = false+ /**+ * What an empty sticky note shows while it is edited on this canvas, in the interface language;+ * null for a canvas that draws only the document, such as an export.+ */+ stickyPlaceholder: string | null = nulltracksSceneSettlement = true/** Colour space this renderer's surface presents; colours convert into it when painting. */presentationColorSpace: RenderColorSpace = 'srgb'diff --git a/packages/core/src/canvas/scene.ts b/packages/core/src/canvas/scene.tsindex 237c50988..df2bfc19c 100644--- a/packages/core/src/canvas/scene.ts+++ b/packages/core/src/canvas/scene.ts@@ -48,6 +48,7 @@ import {drawReflowedPathTextSilhouettes,isReflowedPathText} from './text/derived'+import { stickyPlaceholderNode } from './text/sticky-placeholder'function drawVisibleFills(r: SkiaRenderer,@@ -337,8 +338,9 @@ export function renderNode(parentAbsY = 0,hasTransformedAncestor = false): void {- const node = graph.getNode(nodeId)- if (!node || !drawsNode(node, overlays)) return+ const found = graph.getNode(nodeId)+ if (!found || !drawsNode(found, overlays)) return+ const node = stickyPlaceholderNode(graph, found, r.stickyPlaceholder) ?? foundr._nodeCount++diff --git a/packages/core/src/canvas/text/sticky-placeholder.ts b/packages/core/src/canvas/text/sticky-placeholder.tsnew file mode 100644index 000000000..43caa10cb--- /dev/null+++ b/packages/core/src/canvas/text/sticky-placeholder.ts@@ -0,0 +1,26 @@+import { generatedFrameOwner, stickySublayers } from '@open-pencil/scene-graph'+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { BLACK } from '@open-pencil/scene-graph/constants'++/**+ * The body of an empty sticky note as an editing canvas draws it: `placeholder`, in the+ * interface language, in the body's style, black at 30%, as measured in FigJam. The note's text+ * stays empty, and a canvas without a placeholder, such as an export, draws nothing there.+ */+export function stickyPlaceholderNode(+ graph: SceneGraph,+ node: SceneNode,+ placeholder: string | null+): SceneNode | null {+ if (!placeholder || node.type !== 'TEXT' || node.text !== '') return null+ const sticky = generatedFrameOwner(graph, node)+ if (sticky?.type !== 'STICKY' || stickySublayers(graph, sticky)?.body.id !== node.id) return null+ return {+ ...node,+ text: placeholder,+ styleRuns: [],+ textParagraphs: [],+ derivedTextGlyphs: null,+ fills: [{ type: 'SOLID', color: { ...BLACK }, opacity: 0.3, visible: true }]+ }+}diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.tsindex d28364d75..36b65f2ae 100644--- a/packages/core/src/editor/create.ts+++ b/packages/core/src/editor/create.ts@@ -48,6 +48,7 @@ import { createShaderActions } from './shaders/actions'import { createShaderFrames } from './shaders/frames'import { createShapeActions } from './shapes'import { createDefaultEditorState } from './state'+import { createStickyActions } from './stickies'import { createStructureActions } from './structure'import { createTextActions } from './text'import { createPendingTextLayout } from './text/pending-layout'@@ -241,6 +242,7 @@ export function createEditor(options?: EditorOptions) {loadFont: _loadFont,resolveFigmaClipboardImages: options?.resolveFigmaClipboardImages ?? null,getViewportSize: _getViewportSize,+ getUserName: () => options?.getUserName?.() ?? '',icons: options?.icons ?? iconify,getCk: () => _ck,getRenderer: () => _renderer,@@ -279,6 +281,7 @@ export function createEditor(options?: EditorOptions) {const designTokens = createDesignTokenActions(ctx, variables, nodes)const vectorize = createVectorizeActions(ctx)const icons = createIconActions(ctx)+ const stickies = createStickyActions(ctx)const shaders = createShaderActions(ctx, nodes)const alignment = createAlignmentActions(ctx)const preview = createPlayActions(ctx)@@ -437,6 +440,7 @@ export function createEditor(options?: EditorOptions) {// Bitmap-to-vector replacement...vectorize,...icons,+ ...stickies,...shaders,...shaderFrames,diff --git a/packages/core/src/editor/selection.ts b/packages/core/src/editor/selection.tsindex 086500afd..49f11dc75 100644--- a/packages/core/src/editor/selection.ts+++ b/packages/core/src/editor/selection.ts@@ -1,3 +1,5 @@+import { generatedFrameOwner } from '@open-pencil/scene-graph'+import { createSelectionContainerActions } from './selection/container'import { createSelectionHitTestActions } from './selection/hit-test'import { createSelectionNavigationActions } from './selection/navigation'@@ -21,11 +23,18 @@ export function createSelectionActions(ctx: EditorContext) {)}+ /** A generated frame's sublayer is selected as the frame, such as a sticky note's body. */+ function selectable(id: string): string {+ const node = ctx.graph.getNode(id)+ return (node && generatedFrameOwner(ctx.graph, node)?.id) ?? id+ }+/*** Figma never selects a layer together with one of its ancestors. A plain selection keeps the* outermost layers; adding a layer replaces its selected ancestors and descendants.*/- function select(ids: string[], additive = false) {+ function select(requested: string[], additive = false) {+ const ids = requested.map(selectable)if (!additive) {ctx.setSelectedIds(outermost(ids))returndiff --git a/packages/core/src/editor/stickies.ts b/packages/core/src/editor/stickies.tsnew file mode 100644index 000000000..a90810cb0--- /dev/null+++ b/packages/core/src/editor/stickies.ts@@ -0,0 +1,157 @@+import {+ createSticky,+ DEFAULT_STICKY_COLOR,+ generatedFrameOwner,+ rescaleNodeTree,+ stickyScale,+ stickyWidth,+ STICKY_SIZE,+ stickyBodySizeFields,+ stickySublayers+} from '@open-pencil/scene-graph'+import type { SceneNode, StickyTextSize } from '@open-pencil/scene-graph'+import type { Color, Vector } from '@open-pencil/scene-graph/primitives'++import { recordSubtreeEdit } from '#core/editor/components/slots/history'+import type { EditorContext } from '#core/editor/types'+import { pushCreatedSubtreesUndo } from '#core/editor/undo'++/** The name a note takes from its body while it was never renamed, as FigJam names it. */+function stickyNameFor(text: string): string {+ return text.trim() === '' ? 'Sticky' : text+}++/**+ * Typing in a note's body renames a note that was never renamed, as FigJam does. The caller+ * records the text edit; this records the rename beside it.+ */+export function applyStickyNameEdit(+ ctx: Pick<EditorContext, 'graph' | 'undo'>,+ nodeId: string,+ text: string+): void {+ const node = ctx.graph.getNode(nodeId)+ const sticky = node && generatedFrameOwner(ctx.graph, node)+ if (sticky?.type !== 'STICKY' || !sticky.autoRename) return+ if (stickySublayers(ctx.graph, sticky)?.body.id !== nodeId) return+ const before = sticky.name+ const after = stickyNameFor(text)+ if (before === after) return+ const rename = (name: string) => () => ctx.graph.updateNode(sticky.id, { name })+ rename(after)()+ ctx.undo.push({ label: 'Rename sticky', forward: rename(after), inverse: rename(before) })+}++/**+ * Sticky note commands. A note's colour sits on the note and its text on its sublayers, so each+ * change records the notes' whole subtrees as one step.+ */+export function createStickyActions(ctx: EditorContext) {+ /** The colour the sticky tool places notes in: the one picked last, as in FigJam. */+ let stickyColor: Color = DEFAULT_STICKY_COLOR++ function selectedStickies(ids: Iterable<string>): SceneNode[] {+ return [...ids].flatMap((id) => {+ const node = ctx.graph.getNode(id)+ return node?.type === 'STICKY' ? [node] : []+ })+ }++ /**+ * Places a note centred on `center`, in `parentId`'s coordinates, signed with the user's+ * name and in the colour picked last, and selects it.+ */+ function createStickyNote(parentId: string, center: Vector): SceneNode {+ const previousSelection = new Set(ctx.state.selectedIds)+ const sticky = createSticky(+ ctx.graph,+ parentId,+ { author: ctx.getUserName(), color: stickyColor },+ {+ x: Math.round(center.x - STICKY_SIZE / 2),+ y: Math.round(center.y - STICKY_SIZE / 2)+ }+ )+ ctx.runLayoutForNode(sticky.id)+ pushCreatedSubtreesUndo(ctx, 'Create sticky', [sticky.id], previousSelection)+ ctx.setSelectedIds(new Set([sticky.id]))+ ctx.requestRender()+ return sticky+ }++ function editStickies(label: string, ids: Iterable<string>, change: (sticky: SceneNode) => void) {+ const stickies = selectedStickies(ids)+ if (stickies.length === 0) return+ recordSubtreeEdit(+ ctx,+ label,+ stickies.map((sticky) => sticky.id),+ () => stickies.forEach(change)+ )+ }++ /** Paints the notes `ids` in `color`, which new notes take from now on. */+ function setStickyColor(ids: Iterable<string>, color: Color) {+ stickyColor = { ...color }+ editStickies('Change sticky color', ids, (sticky) => {+ const fill = sticky.fills.at(0)+ const fills = fill+ ? [{ ...fill, type: 'SOLID' as const, color: { ...color } }, ...sticky.fills.slice(1)]+ : [{ type: 'SOLID' as const, color: { ...color }, opacity: 1, visible: true }]+ ctx.graph.updateNode(sticky.id, { fills })+ })+ }++ /** Sets the size of the notes' body text to one of FigJam's presets. */+ function setStickyTextSize(ids: Iterable<string>, size: StickyTextSize) {+ editStickies('Change sticky text size', ids, (sticky) => {+ const body = stickySublayers(ctx.graph, sticky)?.body+ if (body) ctx.graph.updateNode(body.id, stickyBodySizeFields(size))+ })+ }++ /** Shows or hides the notes' author lines. */+ function setStickyAuthorVisible(ids: Iterable<string>, visible: boolean) {+ editStickies(visible ? 'Show sticky author' : 'Hide sticky author', ids, (sticky) => {+ const author = stickySublayers(ctx.graph, sticky)?.author+ if (author) ctx.graph.updateNode(author.id, { visible })+ })+ }++ /**+ * Scales the note `id`, its text and spacing included, and places its top-left at `position`,+ * as dragging a FigJam note's corner does.+ */+ function scaleStickyNote(id: string, scale: number, position: Vector) {+ if (ctx.graph.getNode(id)?.type !== 'STICKY') return+ recordSubtreeEdit(ctx, 'Scale sticky', id, () => {+ rescaleNodeTree(ctx.graph, id, scale)+ ctx.graph.updateNode(id, { x: position.x, y: position.y })+ })+ }++ /**+ * Makes the note `id` wide or square at its scale, keeping the edge on the `anchor` side in+ * place, as dragging a FigJam note's side does.+ */+ function setStickyWide(id: string, wide: boolean, anchor: 'left' | 'right' = 'left') {+ const sticky = ctx.graph.getNode(id)+ if (sticky?.type !== 'STICKY') return+ const scale = stickyScale(stickySublayers(ctx.graph, sticky)?.author)+ const width = stickyWidth(scale, wide)+ if (width === sticky.width) return+ const x = anchor === 'right' ? sticky.x + sticky.width - width : sticky.x+ recordSubtreeEdit(ctx, wide ? 'Make sticky wide' : 'Make sticky square', id, () => {+ ctx.graph.updateNode(id, { x, width })+ })+ }++ return {+ setStickyWide,+ createStickyNote,+ setStickyColor,+ setStickyTextSize,+ setStickyAuthorVisible,+ scaleStickyNote+ }+}diff --git a/packages/core/src/editor/structure.ts b/packages/core/src/editor/structure.tsindex dae4fcb49..dbddaacf2 100644--- a/packages/core/src/editor/structure.ts+++ b/packages/core/src/editor/structure.ts@@ -170,14 +170,16 @@ export function createStructureActions(ctx: EditorContext) {function renameNode(id: string, name: string) {const node = ctx.graph.getNode(id)if (!node) return- const previous = node.name+ const previous = { name: node.name, autoRename: node.autoRename }const next = name.trim() || defaultNodeName(node.type)- if (next === previous) return- ctx.graph.updateNode(id, { name: next })+ if (next === previous.name) return+ // A sticky note named by hand no longer takes its name from its text, as in FigJam.+ const renamed = { name: next, autoRename: node.type === 'STICKY' ? false : node.autoRename }+ ctx.graph.updateNode(id, renamed)ctx.undo.push({label: 'Rename',- forward: () => ctx.graph.updateNode(id, { name: next }),- inverse: () => ctx.graph.updateNode(id, { name: previous })+ forward: () => ctx.graph.updateNode(id, renamed),+ inverse: () => ctx.graph.updateNode(id, previous)})}diff --git a/packages/core/src/editor/text.ts b/packages/core/src/editor/text.tsindex 562279544..601c2d337 100644--- a/packages/core/src/editor/text.ts+++ b/packages/core/src/editor/text.ts@@ -12,6 +12,7 @@ import { weightToStyle } from '#core/text/fonts'import { hasGlyphOutlines } from '#core/text/opentype'import { applyBoundTextEdit } from './components/authoring/text-edit'+import { applyStickyNameEdit } from './stickies'import { pathTextEditChanges } from './text/path-edit'import {createTextEditSession,@@ -204,7 +205,10 @@ export function createTextActions(ctx: EditorContext) {ctx.runLayoutForNode(result.nodeId)}})- if (before.text !== after.text) applyBoundTextEdit(ctx, result.nodeId, after.text)+ if (before.text !== after.text) {+ applyBoundTextEdit(ctx, result.nodeId, after.text)+ applyStickyNameEdit(ctx, result.nodeId, after.text)+ }})}diff --git a/packages/core/src/editor/tool-registry.ts b/packages/core/src/editor/tool-registry.tsindex 3f2e3e6ec..6ee384cbe 100644--- a/packages/core/src/editor/tool-registry.ts+++ b/packages/core/src/editor/tool-registry.ts@@ -18,6 +18,8 @@ export const EDITOR_TOOLS: EditorToolDef[] = [},{ key: 'PEN', label: 'Pen', shortcut: 'P', flyout: ['PEN', 'PENCIL'] },{ key: 'TEXT', label: 'Text', shortcut: 'T' },+ // Figma's S is Slice, and FigJam's sticky tool has no key in Figma Design.+ { key: 'STICKY', label: 'Sticky note', shortcut: '' },{ key: 'HAND', label: 'Hand', shortcut: 'H' },{ key: 'COMMENT', label: 'Comment', shortcut: 'C' }]diff --git a/packages/core/src/editor/types.ts b/packages/core/src/editor/types.tsindex d888d945b..6de3ba9d8 100644--- a/packages/core/src/editor/types.ts+++ b/packages/core/src/editor/types.ts@@ -41,6 +41,7 @@ export type Tool =| 'POLYGON'| 'STAR'| 'TEXT'+ | 'STICKY'| 'PEN'| 'PENCIL'| 'HAND'@@ -216,6 +217,8 @@ export interface EditorOptions {) => Promise<ArrayBuffer | null>resolveFigmaClipboardImages?: FigmaClipboardImageResolvergetViewportSize?: () => { width: number; height: number }+ /** The name of whoever is editing, which a sticky note they place is signed with. */+ getUserName?: () => string/** Where icons are searched and fetched; defaults to Iconify. */icons?: IconProvider/** What draws shader frames, which needs a GPU; without one, saved frames stay. */@@ -236,6 +239,7 @@ export interface EditorContext {) => Promise<ArrayBuffer | null>resolveFigmaClipboardImages: FigmaClipboardImageResolver | nullgetViewportSize: () => { width: number; height: number }+ getUserName: () => stringicons: IconProvidergetCk: () => CanvasKit | nullgetRenderer: () => SkiaRenderer | nulldiff --git a/packages/core/src/figma-api/accessors/sticky.ts b/packages/core/src/figma-api/accessors/sticky.tsnew file mode 100644index 000000000..81e56039c--- /dev/null+++ b/packages/core/src/figma-api/accessors/sticky.ts@@ -0,0 +1,75 @@+import {+ isGeneratedFrame,+ isWideSticky,+ stickyScale,+ stickySublayers,+ stickyWidth+} from '@open-pencil/scene-graph'+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'++import {+ graph,+ raw,+ updateNode,+ type NodeProxyInternals,+ type ProxyThis+} from '#core/figma-api/accessor-utils'+import type { FigmaNodeProxy, NodeProxyHost } from '#core/figma-api/proxy'++/**+ * The layers a script sees inside a node. A generated frame, such as a sticky note, shows none:+ * Figma reaches its text through `text`, not `children`.+ */+export function pluginChildren(sceneGraph: SceneGraph, id: string): SceneNode[] {+ const node = sceneGraph.getNode(id)+ return node && isGeneratedFrame(node) ? [] : sceneGraph.getChildren(id)+}++function sublayers(target: ProxyThis, internals: NodeProxyInternals) {+ const node = raw(target, internals)+ return node.type === 'STICKY' ? stickySublayers(graph(target, internals), node) : null+}++function wrap(target: ProxyThis, internals: NodeProxyInternals, id: string): FigmaNodeProxy {+ return (target[internals.api] as NodeProxyHost).wrapNode(id)+}++/** `StickyNode`'s members: its body as `text`, its author line, and its wide shape. */+export function installStickyNodeProxyAccessors(+ prototype: object,+ internals: NodeProxyInternals+): void {+ Object.defineProperties(prototype, {+ text: {+ get(this: ProxyThis): FigmaNodeProxy | undefined {+ const layers = sublayers(this, internals)+ return layers ? wrap(this, internals, layers.body.id) : undefined+ }+ },+ authorName: {+ get(this: ProxyThis): string | undefined {+ return sublayers(this, internals)?.author.text+ }+ },+ authorVisible: {+ get(this: ProxyThis): boolean | undefined {+ return sublayers(this, internals)?.author.visible+ },+ set(this: ProxyThis, value: boolean) {+ const author = sublayers(this, internals)?.author+ if (author) wrap(this, internals, author.id).visible = value+ }+ },+ isWideWidth: {+ get(this: ProxyThis): boolean | undefined {+ const node = raw(this, internals)+ return node.type === 'STICKY' ? isWideSticky(graph(this, internals), node) : undefined+ },+ set(this: ProxyThis, value: boolean) {+ const layers = sublayers(this, internals)+ if (!layers) return+ updateNode(this, internals, { width: stickyWidth(stickyScale(layers.author), value) })+ }+ }+ })+}diff --git a/packages/core/src/figma-api/node-types.ts b/packages/core/src/figma-api/node-types.tsindex 2a098eb84..1132cb707 100644--- a/packages/core/src/figma-api/node-types.ts+++ b/packages/core/src/figma-api/node-types.ts@@ -17,3 +17,4 @@ export type FigmaSlotNode = FigmaNodeProxy & SlotNodeexport type FigmaSectionNode = FigmaNodeProxy & SectionNodeexport type FigmaGroupNode = FigmaNodeProxy & GroupNodeexport type FigmaBooleanOperationNode = FigmaNodeProxy & BooleanOperationNode+export type FigmaStickyNode = FigmaNodeProxy & StickyNodediff --git a/packages/core/src/figma-api/proxy.ts b/packages/core/src/figma-api/proxy.tsindex d05943825..da68cfadf 100644--- a/packages/core/src/figma-api/proxy.ts+++ b/packages/core/src/figma-api/proxy.ts@@ -29,6 +29,7 @@ import type { FigmaEffect } from '#core/figma-api/effects'import { prepareFollowedFieldEdit, fitGroupsAround } from './accessor-utils'import { installBasicNodeProxyAccessors } from './accessors/basic'import { installLayoutNodeProxyAccessors } from './accessors/layout'+import { installStickyNodeProxyAccessors, pluginChildren } from './accessors/sticky'import { installStrokeNodeProxyAccessors } from './accessors/strokes'import { installTextNodeProxyAccessors } from './accessors/text'import { installTextRangeMethods, type TextRangeMethods } from './accessors/text/ranges'@@ -162,6 +163,11 @@ export class FigmaNodeProxy {declare readonly explicitVariableModes: Readonly<Record<string, string>>declare readonly resolvedVariableModes: Readonly<Record<string, string>>declare readonly overrides: FigmaInstanceOverride[] | undefined+ /** A sticky note's body, its author line, and whether it is wide; undefined on other layers. */+ declare readonly text: FigmaNodeProxy | undefined+ declare readonly authorName: string | undefined+ declare authorVisible: boolean | undefined+ declare isWideWidth: boolean | undefineddeclare resetOverrides: () => voiddeclare strokeWeight: number@@ -373,9 +379,9 @@ export class FigmaNodeProxy {}get children(): FigmaNodeProxy[] {- return this[INTERNAL_GRAPH]- .getChildren(this[INTERNAL_ID])- .map((c) => this[INTERNAL_API].wrapNode(c.id))+ return pluginChildren(this[INTERNAL_GRAPH], this[INTERNAL_ID]).map((c) =>+ this[INTERNAL_API].wrapNode(c.id)+ )}appendChild(child: FigmaNodeProxy): void {@@ -570,6 +576,7 @@ const proxyInternals = {}installStrokeNodeProxyAccessors(FigmaNodeProxy.prototype, proxyInternals)+installStickyNodeProxyAccessors(FigmaNodeProxy.prototype, proxyInternals)installTextNodeProxyAccessors(FigmaNodeProxy.prototype, proxyInternals, MIXED)installTextRangeMethods(FigmaNodeProxy.prototype, proxyInternals, MIXED)installLayoutNodeProxyAccessors(FigmaNodeProxy.prototype, proxyInternals)diff --git a/packages/core/src/figma-api/serialization.ts b/packages/core/src/figma-api/serialization.tsindex 67f29fb38..7a8808688 100644--- a/packages/core/src/figma-api/serialization.ts+++ b/packages/core/src/figma-api/serialization.ts@@ -1,5 +1,6 @@import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { pluginChildren } from './accessors/sticky'import type { NodeProxyHost } from './proxy'function resolveBindings(graph: SceneGraph, node: SceneNode): Record<string, unknown> | undefined {@@ -70,7 +71,7 @@ export function nodeProxyToJSON(// Include variable bindings with resolved valuesconst bindings = resolveBindings(graph, n)if (bindings) obj.boundVariables = bindings- const children = graph.getChildren(nodeId)+ const children = pluginChildren(graph, nodeId)if (children.length > 0) {if (maxDepth !== undefined && currentDepth >= maxDepth) {obj.childCount = children.lengthdiff --git a/packages/core/src/figma-api/traversal.ts b/packages/core/src/figma-api/traversal.tsindex 730a46c40..bc45da7ea 100644--- a/packages/core/src/figma-api/traversal.ts+++ b/packages/core/src/figma-api/traversal.ts@@ -1,5 +1,6 @@import type { SceneGraph } from '@open-pencil/scene-graph'+import { pluginChildren } from './accessors/sticky'import type { FigmaNodeProxy, NodeProxyHost } from './proxy'export function findAll(@@ -10,7 +11,7 @@ export function findAll(): FigmaNodeProxy[] {const results: FigmaNodeProxy[] = []const walk = (id: string) => {- for (const child of graph.getChildren(id)) {+ for (const child of pluginChildren(graph, id)) {const proxy = api.wrapNode(child.id)if (!callback || callback(proxy)) results.push(proxy)walk(child.id)@@ -27,7 +28,7 @@ export function findOne(callback: (node: FigmaNodeProxy) => boolean): FigmaNodeProxy | null {const walk = (id: string): FigmaNodeProxy | null => {- for (const child of graph.getChildren(id)) {+ for (const child of pluginChildren(graph, id)) {const proxy = api.wrapNode(child.id)if (callback(proxy)) return proxyconst found = walk(child.id)@@ -44,7 +45,7 @@ export function findChild(rootId: string,callback: (node: FigmaNodeProxy) => boolean): FigmaNodeProxy | null {- for (const child of graph.getChildren(rootId)) {+ for (const child of pluginChildren(graph, rootId)) {const proxy = api.wrapNode(child.id)if (callback(proxy)) return proxy}@@ -57,8 +58,7 @@ export function findChildren(rootId: string,callback?: (node: FigmaNodeProxy) => boolean): FigmaNodeProxy[] {- return graph- .getChildren(rootId)+ return pluginChildren(graph, rootId).map((child) => api.wrapNode(child.id)).filter((proxy) => !callback || callback(proxy))}diff --git a/packages/core/tests/canvas/text/sticky-placeholder.test.ts b/packages/core/tests/canvas/text/sticky-placeholder.test.tsnew file mode 100644index 000000000..29c251975--- /dev/null+++ b/packages/core/tests/canvas/text/sticky-placeholder.test.ts@@ -0,0 +1,37 @@+import { describe, expect, test } from 'bun:test'++import { expectDefined } from '#core-tests/helpers/assert'++import { createSticky, SceneGraph, stickySublayers } from '@open-pencil/scene-graph'++import { stickyPlaceholderNode } from '#core/canvas/text/sticky-placeholder'++function emptyNote() {+ const graph = new SceneGraph()+ const sticky = createSticky(graph, graph.getPages()[0].id, { author: 'Ada' })+ return { graph, ...expectDefined(stickySublayers(graph, sticky)) }+}++describe('sticky note placeholder', () => {+ test("an empty body shows the canvas's placeholder, in the body's style at 30% black", () => {+ const { graph, body } = emptyNote()+ const drawn = expectDefined(stickyPlaceholderNode(graph, body, 'Пишите что угодно'))+ expect(drawn).toMatchObject({ text: 'Пишите что угодно', fontSize: 16, lineHeight: 24 })+ expect(drawn.fills[0]).toMatchObject({ opacity: 0.3, color: { r: 0, g: 0, b: 0 } })+ expect(body.text).toBe('')+ })++ test('a canvas without a placeholder, such as an export, draws none', () => {+ const { graph, body } = emptyNote()+ expect(stickyPlaceholderNode(graph, body, null)).toBeNull()+ })++ test('the author line and a body with text show no placeholder', () => {+ const { graph, body, author } = emptyNote()+ expect(stickyPlaceholderNode(graph, author, 'Type anything')).toBeNull()+ graph.updateNode(body.id, { text: 'Hello' })+ expect(+ stickyPlaceholderNode(graph, expectDefined(graph.getNode(body.id)), 'Type anything')+ ).toBeNull()+ })+})diff --git a/packages/core/tests/editor/stickies.test.ts b/packages/core/tests/editor/stickies.test.tsnew file mode 100644index 000000000..585a9d6ed--- /dev/null+++ b/packages/core/tests/editor/stickies.test.ts@@ -0,0 +1,106 @@+import { afterEach, beforeEach, describe, expect, test } from 'bun:test'++import { setTextMeasurer } from '@open-pencil/core'+import { createEditor } from '@open-pencil/core/editor'+import { STICKY_COLORS, stickySublayers } from '@open-pencil/scene-graph'+import type { SceneNode } from '@open-pencil/scene-graph'++import { applyStickyNameEdit } from '#core/editor/stickies'++import { expectDefined } from '../helpers/assert'++function setup() {+ const editor = createEditor({ getUserName: () => 'Ada Lovelace' })+ return { editor, pageId: editor.state.currentPageId }+}++function sublayers(editor: ReturnType<typeof setup>['editor'], sticky: SceneNode) {+ return expectDefined(stickySublayers(editor.graph, sticky))+}++beforeEach(() => {+ setTextMeasurer((node, maxWidth) => ({+ width: maxWidth ?? node.width,+ height: node.text.split('\n').length * (node.lineHeight ?? node.fontSize)+ }))+})+afterEach(() => setTextMeasurer(null))++describe('sticky notes', () => {+ test('a placed note is centred, signed by the user, selected, and one undo step', () => {+ const { editor, pageId } = setup()+ const sticky = editor.createStickyNote(pageId, { x: 500, y: 300 })+ expect([sticky.x, sticky.y, sticky.width, sticky.height]).toEqual([380, 180, 240, 240])+ expect(sublayers(editor, sticky).author.text).toBe('Ada Lovelace')+ expect([...editor.state.selectedIds]).toEqual([sticky.id])++ editor.undo.undo()+ expect(editor.graph.getNode(sticky.id)).toBeUndefined()+ editor.undo.redo()+ const restored = editor.graph.getNode(sticky.id)+ expect(restored && sublayers(editor, restored).author.text).toBe('Ada Lovelace')+ })++ test('the next note takes the colour picked last', () => {+ const { editor, pageId } = setup()+ const first = editor.createStickyNote(pageId, { x: 0, y: 0 })+ editor.setStickyColor([first.id], STICKY_COLORS.pink)+ expect(editor.graph.getNode(first.id)?.fills[0]?.color).toEqual(STICKY_COLORS.pink)+ const second = editor.createStickyNote(pageId, { x: 400, y: 0 })+ expect(second.fills[0]?.color).toEqual(STICKY_COLORS.pink)+ })++ test('text size and author changes are single undo steps over the whole note', () => {+ const { editor, pageId } = setup()+ const sticky = editor.createStickyNote(pageId, { x: 0, y: 0 })+ editor.setStickyTextSize([sticky.id], 'large')+ expect(sublayers(editor, sticky).body).toMatchObject({ fontSize: 40, lineHeight: 60 })+ editor.setStickyAuthorVisible([sticky.id], false)+ expect(sublayers(editor, sticky).author.visible).toBe(false)++ editor.undo.undo()+ const shown = expectDefined(editor.graph.getNode(sticky.id))+ expect(sublayers(editor, shown).author.visible).toBe(true)+ editor.undo.undo()+ const small = expectDefined(editor.graph.getNode(sticky.id))+ expect(sublayers(editor, small).body.fontSize).toBe(16)+ })++ test('scaling a note scales its text and spacing from the corner it keeps', () => {+ const { editor, pageId } = setup()+ const sticky = editor.createStickyNote(pageId, { x: 120, y: 120 })+ editor.scaleStickyNote(sticky.id, 1.5, { x: 0, y: 0 })+ const scaled = expectDefined(editor.graph.getNode(sticky.id))+ expect(scaled).toMatchObject({ width: 360, height: 360, paddingTop: 30, minHeight: 360 })+ expect(sublayers(editor, scaled).author.fontSize).toBe(18)+ editor.undo.undo()+ expect(editor.graph.getNode(sticky.id)?.width).toBe(240)+ })++ test('a note switches between square and wide, keeping the edge on the anchored side', () => {+ const { editor, pageId } = setup()+ const sticky = editor.createStickyNote(pageId, { x: 120, y: 120 })+ editor.setStickyWide(sticky.id, true)+ const wide = expectDefined(editor.graph.getNode(sticky.id))+ expect([wide.x, wide.width, sublayers(editor, wide).body.width]).toEqual([0, 416, 376])+ editor.setStickyWide(sticky.id, false, 'right')+ expect(editor.graph.getNode(sticky.id)).toMatchObject({ x: 176, width: 240 })+ editor.undo.undo()+ expect(editor.graph.getNode(sticky.id)).toMatchObject({ x: 0, width: 416 })+ })++ test("typing in a note's body renames a note that was never renamed", () => {+ const { editor, pageId } = setup()+ const sticky = editor.createStickyNote(pageId, { x: 0, y: 0 })+ const { body, author } = sublayers(editor, sticky)+ applyStickyNameEdit(editor, body.id, 'Hello')+ expect(editor.graph.getNode(sticky.id)?.name).toBe('Hello')+ applyStickyNameEdit(editor, author.id, 'Someone')+ expect(editor.graph.getNode(sticky.id)?.name).toBe('Hello')+ editor.renameNode(sticky.id, 'Kept')+ applyStickyNameEdit(editor, body.id, 'Changed')+ expect(editor.graph.getNode(sticky.id)?.name).toBe('Kept')+ editor.undo.undo()+ expect(editor.graph.getNode(sticky.id)?.autoRename).toBe(true)+ })+})diff --git a/packages/core/tests/figma-api/sticky.test.ts b/packages/core/tests/figma-api/sticky.test.tsnew file mode 100644index 000000000..87d62741b--- /dev/null+++ b/packages/core/tests/figma-api/sticky.test.ts@@ -0,0 +1,69 @@+import { describe, expect, test } from 'bun:test'++import { FigmaAPI } from '@open-pencil/core/figma-api'+import { createSticky, SceneGraph } from '@open-pencil/scene-graph'++function stickyNote() {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const sticky = createSticky(graph, page.id, { text: 'Hello', author: 'Ada Lovelace' })+ const api = new FigmaAPI(graph)+ const node = api.getNodeById(sticky.id)+ if (!node) throw new Error('Missing sticky note')+ return { api, node }+}++// Values and shapes as live Figma reports them for a StickyNode in FigJam.+describe('sticky notes in the Plugin API', () => {+ test('a note reports its type, text, and author, and has no children', () => {+ const { node } = stickyNote()+ expect(node.type).toBe('STICKY')+ expect(node.text?.characters).toBe('Hello')+ expect(node.text?.fontSize).toBe(16)+ expect(node.authorName).toBe('Ada Lovelace')+ expect(node.authorVisible).toBe(true)+ expect(node.isWideWidth).toBe(false)+ expect(node.children).toEqual([])+ })++ test('findAll does not reach into a note', () => {+ const { api } = stickyNote()+ expect(api.currentPage.findAll().map((found) => found.type)).toEqual(['STICKY'])+ })++ test('toJSON lists no children for a note, as children does', () => {+ const { node } = stickyNote()+ expect(node.toJSON()).not.toHaveProperty('children')+ })++ test('a layer cannot be added to a note', () => {+ const { api, node } = stickyNote()+ const rect = api.createRectangle()+ expect(() => node.appendChild(rect)).toThrow('Cannot move node')+ expect(() => node.insertChild(0, rect)).toThrow('Cannot move node')+ })++ test('hiding the author and making the note wide', () => {+ const { node } = stickyNote()+ node.authorVisible = false+ node.isWideWidth = true+ expect(node.authorVisible).toBe(false)+ expect([node.isWideWidth, node.width]).toEqual([true, 416])+ })++ test('rescale scales the note and its text, as in Figma', () => {+ const { node } = stickyNote()+ node.rescale(1.5)+ expect([node.width, node.height, node.text?.fontSize]).toEqual([360, 360, 24])+ })++ test('other layers have no sticky members', () => {+ const { api } = stickyNote()+ const frame = api.createFrame()+ expect([frame.text, frame.authorVisible, frame.isWideWidth]).toEqual([+ undefined,+ undefined,+ undefined+ ])+ })+})diff --git a/packages/docs/reference/keyboard-shortcuts.md b/packages/docs/reference/keyboard-shortcuts.mdindex 4fc8e0a1b..2cd83aceb 100644--- a/packages/docs/reference/keyboard-shortcuts.md+++ b/packages/docs/reference/keyboard-shortcuts.md@@ -29,6 +29,7 @@ Full Figma-compatible shortcut map. ✅ = implemented.| <kbd>P</kbd> | Pen | ✅ || <kbd>⇧</kbd><kbd>P</kbd> | Pencil | ✅ || <kbd>T</kbd> | Text | ✅ |+| — | Sticky note (FigJam) | ✅ (toolbar, hidden by default) || <kbd>C</kbd> | Comment | ✅ || <kbd>I</kbd> | Eyedropper | 🔲 |diff --git a/packages/scene-graph/src/generated/sticky.ts b/packages/scene-graph/src/generated/sticky.tsindex 5e3c930e0..533d85b0f 100644--- a/packages/scene-graph/src/generated/sticky.ts+++ b/packages/scene-graph/src/generated/sticky.ts@@ -34,6 +34,33 @@ export const STICKY_COLORS = {export const DEFAULT_STICKY_COLOR: Color = STICKY_COLORS.blue+/** FigJam's body text sizes, each with the tracking it sets, as a fraction of the size. */+export const STICKY_TEXT_SIZES = {+ small: { fontSize: 16, tracking: -0.011 },+ medium: { fontSize: 24, tracking: -0.019 },+ large: { fontSize: 40, tracking: -0.022 },+ extraLarge: { fontSize: 64, tracking: -0.022 },+ huge: { fontSize: 96, tracking: -0.023 }+} as const++export type StickyTextSize = keyof typeof STICKY_TEXT_SIZES++/** A body's text at a size preset: its line stays one and a half times the size. */+export function stickyBodySizeFields(size: StickyTextSize): Partial<SceneNode> {+ const { fontSize, tracking } = STICKY_TEXT_SIZES[size]+ return { fontSize, lineHeight: fontSize * 1.5, letterSpacing: fontSize * tracking }+}++/** The preset a body's text is closest to, as FigJam's size menu shows a rescaled note's. */+export function stickyTextSize(body: Pick<SceneNode, 'fontSize'>): StickyTextSize {+ const sizes = Object.entries(STICKY_TEXT_SIZES) as [StickyTextSize, { fontSize: number }][]+ return sizes.reduce((best, entry) =>+ Math.abs(entry[1].fontSize - body.fontSize) < Math.abs(best[1].fontSize - body.fontSize)+ ? entry+ : best+ )[0]+}+function solid(color: Color, opacity = 1): Fill {return { type: 'SOLID', color: { ...color }, opacity, visible: true }}@@ -113,6 +140,17 @@ export function stickyScale(author: Pick<SceneNode, 'fontSize'> | undefined): nureturn author ? author.fontSize / STICKY_AUTHOR_FONT_SIZE : 1}+/** A note's width at a scale, square or wide, as FigJam's side handles switch between them. */+export function stickyWidth(scale: number, wide: boolean): number {+ return (wide ? STICKY_WIDE_WIDTH : STICKY_SIZE) * scale+}++/** Whether a note is wide: nearer FigJam's wide width than its square one at its scale. */+export function isWideSticky(graph: SceneGraph, sticky: SceneNode): boolean {+ const scale = stickyScale(stickySublayers(graph, sticky)?.author)+ return sticky.width > ((STICKY_SIZE + STICKY_WIDE_WIDTH) / 2) * scale+}+export interface StickySublayers {body: SceneNodeauthor: SceneNode@@ -181,7 +219,6 @@ export function createSticky(height: size,fills: [solid(content.color ?? DEFAULT_STICKY_COLOR)],effects: stickyShadows(),- autoRename: false,...stickyFrameFields(scale),...props})diff --git a/packages/scene-graph/src/scaling/tree.ts b/packages/scene-graph/src/scaling/tree.tsindex 095639ad0..5c95a7952 100644--- a/packages/scene-graph/src/scaling/tree.ts+++ b/packages/scene-graph/src/scaling/tree.ts@@ -17,6 +17,7 @@ const RESCALABLE_NODE_TYPES = new Set<SceneNode['type']>(['POLYGON','RECTANGLE','STAR',+ 'STICKY','TEXT','VECTOR'])diff --git a/packages/vue/src/canvas/surface/lifecycle.ts b/packages/vue/src/canvas/surface/lifecycle.tsindex cc78e5a17..b4c379456 100644--- a/packages/vue/src/canvas/surface/lifecycle.ts+++ b/packages/vue/src/canvas/surface/lifecycle.ts@@ -22,6 +22,7 @@ import { createCanvasRenderLoop } from '#vue/canvas/surface/render-loop'import { useCanvasResizeObserver } from '#vue/canvas/surface/resize-observer'import { createShaderRasterizer } from '#vue/canvas/surface/shader/rasterizer'import type { UseCanvasOptions } from '#vue/canvas/surface/types'+import { editorMessages } from '#vue/i18n/messages/editor'type SurfaceManagerState = {renderer: SkiaRenderer | null@@ -56,6 +57,22 @@ export function createCanvasSurfaceManager({}let sceneBackingRenderTimer: ReturnType<typeof setTimeout> | null = null+ // The scene of an editing canvas shows an empty sticky note's placeholder in the interface+ // language, and draws it again when the language changes.+ const showsStickyPlaceholder = options?.layer !== 'overlays'+ let stickyPlaceholder: string = editorMessages.get().stickyPlaceholder+ const stopStickyPlaceholder = editorMessages.subscribe((messages) => {+ if (messages.stickyPlaceholder === stickyPlaceholder) return+ stickyPlaceholder = messages.stickyPlaceholder+ if (!state.renderer || !showsStickyPlaceholder) return+ state.renderer.stickyPlaceholder = stickyPlaceholder+ editor.requestRender()+ })++ function showStickyPlaceholder(renderer: SkiaRenderer) {+ if (showsStickyPlaceholder) renderer.stickyPlaceholder = stickyPlaceholder+ }+function clearSceneBackingRenderTimer() {if (sceneBackingRenderTimer === null) returnclearTimeout(sceneBackingRenderTimer)@@ -111,6 +128,7 @@ export function createCanvasSurfaceManager({state.renderer.presentationColorSpace = result.presentation ?? 'srgb'state.renderer.tracksSceneSettlement = options?.layer !== 'overlays'state.renderer.tiledSceneEnabled = options?.sceneRenderer === 'tiled'+ showStickyPlaceholder(state.renderer)editor.setCanvasKit(ck, state.renderer)// The scene surface draws shader frames; an overlay surface has none to draw.if (options?.layer !== 'overlays' && !editor.hasShaderRasterizer())@@ -223,6 +241,7 @@ export function createCanvasSurfaceManager({)function destroy() {+ stopStickyPlaceholder()stopPresentationRefresh()stopColorSpaceRefresh()clearSceneBackingRenderTimer()diff --git a/packages/vue/src/canvas/text-edit/input.ts b/packages/vue/src/canvas/text-edit/input.tsindex c4f7e29c2..6d957129b 100644--- a/packages/vue/src/canvas/text-edit/input.ts+++ b/packages/vue/src/canvas/text-edit/input.ts@@ -1,5 +1,5 @@import { getNodeEditCapability, type Editor } from '@open-pencil/core/editor'-import type { SceneNode } from '@open-pencil/scene-graph'+import { generatedFrameOwner, stickySublayers, type SceneNode } from '@open-pencil/scene-graph'import type { CanvasLabelKind } from '#vue/canvas/labels/edit'import type { DragState } from '#vue/shared/input/types'@@ -82,6 +82,17 @@ export function createTextEditInput(options: TextEditInputOptions) {}}+ /** A sticky note keeps its selection while its body is edited, all of it selected, as in Figma. */+ function startStickyEditing(sticky: SceneNode) {+ const body = stickySublayers(editor.graph, sticky)?.body+ if (!body) return+ editor.select([sticky.id])+ editor.startTextEditing(body.id)+ if (editor.state.editingTextId !== body.id) return+ editor.textEditor?.selectAll()+ editor.textSelectionChanged()+ }+function getContainerDescendantHit(containerId: string,cx: number,@@ -148,8 +159,10 @@ export function createTextEditInput(options: TextEditInputOptions) {editor.state.selectedIds.size === 1 ? [...editor.state.selectedIds][0] : undefinedif (handleContainerDoubleClick(selectedId, cx, cy)) return- const hit = hitTestInScope(cx, cy, true)- if (!hit) return+ const found = hitTestInScope(cx, cy, true)+ if (!found) return+ // A generated frame's sublayers are edited through the frame.+ const hit = generatedFrameOwner(editor.graph, found) ?? foundif (hit.type === 'TEXT') {const isTopLevelText = hit.parentId === editor.state.currentPageId@@ -166,6 +179,11 @@ export function createTextEditInput(options: TextEditInputOptions) {return}+ if (hit.type === 'STICKY') {+ startStickyEditing(hit)+ return+ }+editor.select([hit.id])}diff --git a/packages/vue/src/canvas/tools/input.ts b/packages/vue/src/canvas/tools/input.tsindex 1abaedc4e..a70375b5f 100644--- a/packages/vue/src/canvas/tools/input.ts+++ b/packages/vue/src/canvas/tools/input.ts@@ -9,6 +9,7 @@ import { startShapeDraw, startTextDraw } from '#vue/shared/input/draw'import { startPanDrag } from '#vue/shared/input/pan'import { handleSelectDown } from '#vue/shared/input/select'import type { HitTestFns } from '#vue/shared/input/select'+import { startStickyPlace } from '#vue/shared/input/sticky/place'import type { DragState } from '#vue/shared/input/types'type ToolMouseDownOptions = {@@ -82,5 +83,10 @@ export function handleToolMouseDown({return}+ if (tool === 'STICKY') {+ startStickyPlace(cx, cy, editor, setDrag)+ return+ }+startShapeDraw(cx, cy, editor, setDrag)}diff --git a/packages/vue/src/canvas/transform/rotation.ts b/packages/vue/src/canvas/transform/rotation.tsindex d3df58b60..0a1397f70 100644--- a/packages/vue/src/canvas/transform/rotation.ts+++ b/packages/vue/src/canvas/transform/rotation.ts@@ -23,7 +23,8 @@ export function tryStartRotation(if (editor.state.selectedIds.size !== 1) return falseconst id = [...editor.state.selectedIds][0]const node = editor.graph.getNode(id)- if (!node || node.locked) return false+ // FigJam keeps sticky notes upright.+ if (!node || node.locked || node.type === 'STICKY') return falseconst geometry = createSceneGeometry(editor.graph, editor.state.rotationPreview)const center = geometry.rotationOrigin(node)diff --git a/packages/vue/src/canvas/useCanvasInput.ts b/packages/vue/src/canvas/useCanvasInput.tsindex 96a705d4f..16134cc0f 100644--- a/packages/vue/src/canvas/useCanvasInput.ts+++ b/packages/vue/src/canvas/useCanvasInput.ts@@ -28,6 +28,7 @@ import { applyResize, cancelResizePreview, commitResizePreview } from '#vue/sharimport { updateHoverCursor } from '#vue/shared/input/select'import { resolveShapeHandleHover } from '#vue/shared/input/shape-handles'import { useSpaceHeld } from '#vue/shared/input/space-key'+import { applyStickyScale } from '#vue/shared/input/sticky/scale'import type { DragState } from '#vue/shared/input/types'import { handleNodeEditMove } from '#vue/shared/input/vector'@@ -329,6 +330,17 @@ export function useCanvasInput(return}+ if (d.type === 'place') {+ d.x = cx+ d.y = cy+ return+ }++ if (d.type === 'sticky-scale') {+ applyStickyScale(d, cx, cy, editor)+ return+ }+handleMarqueeMove(d, cx, cy)}@@ -364,7 +376,7 @@ export function useCanvasInput(editor.commitRotation(d.nodeId, d.origRotation)}if (editor.state.rotationPreview === preview) editor.setRotationPreview(null)- } else if (d.type === 'draw' || d.type === 'gradient' || d.type === 'shape-handle') d.commit()+ } else if ('commit' in d) d.commit()else if (d.type === 'marquee') finishMarquee(editor, d)drag.value = null@@ -383,6 +395,7 @@ export function useCanvasInput(/** 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 === 'sticky-scale') d.cancel()else if (d.type === 'pencil-drag') editor.pencilCancel()}@@ -512,7 +525,12 @@ export function useCanvasInput((event) =>editor.onEditorEvent(event, () => {const type = drag.value?.type- if (type === 'draw' || type === 'rotate' || type === 'shape-handle')+ if (+ type === 'draw' ||+ type === 'rotate' ||+ type === 'shape-handle' ||+ type === 'sticky-scale'+ )cancelPointerInteraction()}))diff --git a/packages/vue/src/controls/sticky/use.ts b/packages/vue/src/controls/sticky/use.tsnew file mode 100644index 000000000..efa82c7c8--- /dev/null+++ b/packages/vue/src/controls/sticky/use.ts@@ -0,0 +1,51 @@+import { computed } from 'vue'++import { stickySublayers, stickyTextSize } from '@open-pencil/scene-graph'+import type { SceneNode, StickyTextSize } from '@open-pencil/scene-graph'+import type { Color } from '@open-pencil/scene-graph/primitives'++import { useEditor } from '#vue/editor/context'+import { useSelectionState } from '#vue/editor/selection-state/use'+import { useSceneComputed } from '#vue/internal/scene-computed/use'++/**+ * Headless state and actions for selected sticky notes: their colour, text size, and whether+ * they show their author. A selection of several notes reads its first note and edits them all.+ */+export function useStickyNote() {+ const editor = useEditor()+ const { selectedIds } = useSelectionState()++ const stickies = useSceneComputed(() => {+ const nodes = [...selectedIds.value].map((id) => editor.graph.getNode(id))+ return nodes.length > 0 && nodes.every((node) => node?.type === 'STICKY')+ ? nodes.filter((node): node is SceneNode => node !== undefined)+ : []+ })+ const active = computed(() => stickies.value.length > 0)+ const ids = computed(() => stickies.value.map((sticky) => sticky.id))+ const sublayers = useSceneComputed(() => {+ const first = stickies.value.at(0)+ return first ? stickySublayers(editor.graph, first) : null+ })++ const color = computed<Color | null>(() => stickies.value.at(0)?.fills.at(0)?.color ?? null)+ const textSize = computed<StickyTextSize | null>(() =>+ sublayers.value ? stickyTextSize(sublayers.value.body) : null+ )+ const authorVisible = computed(() => sublayers.value?.author.visible ?? false)++ function setColor(value: Color) {+ editor.setStickyColor(ids.value, value)+ }++ function setTextSize(value: StickyTextSize) {+ editor.setStickyTextSize(ids.value, value)+ }++ function setAuthorVisible(value: boolean) {+ editor.setStickyAuthorVisible(ids.value, value)+ }++ return { active, color, textSize, authorVisible, setColor, setTextSize, setAuthorVisible }+}diff --git a/packages/vue/src/editor/tool-cursor/index.ts b/packages/vue/src/editor/tool-cursor/index.tsindex 071ec203b..0bee1459a 100644--- a/packages/vue/src/editor/tool-cursor/index.ts+++ b/packages/vue/src/editor/tool-cursor/index.ts@@ -31,6 +31,7 @@ const TOOL_CURSORS: Record<Tool, string> = {POLYGON: 'crosshair',STAR: 'crosshair',TEXT: 'text',+ STICKY: 'crosshair',PEN: PEN_CURSOR,PENCIL: PENCIL_CURSOR,HAND: HAND_CURSOR,diff --git a/packages/vue/src/i18n/locales/de/editor.json b/packages/vue/src/i18n/locales/de/editor.jsonindex fe92a82da..9d10ea7da 100644--- a/packages/vue/src/i18n/locales/de/editor.json+++ b/packages/vue/src/i18n/locales/de/editor.json@@ -4,6 +4,7 @@"cornerRadius": "Radius","pointCount": "Anzahl","starRatio": "Verhältnis",+ "stickyPlaceholder": "Beliebigen Text eingeben, jemanden mit @ erwähnen","showUI": "UI anzeigen ({shortcut})","previewing": "Vorschau","resetPreview": "Zurücksetzen",diff --git a/packages/vue/src/i18n/locales/de/panels.json b/packages/vue/src/i18n/locales/de/panels.jsonindex 0e7acac58..37fe41fc3 100644--- a/packages/vue/src/i18n/locales/de/panels.json+++ b/packages/vue/src/i18n/locales/de/panels.json@@ -445,6 +445,25 @@"maskTypeAlpha": "Alpha","maskTypeVector": "Vektor","maskTypeLuminance": "Luminanz",+ "sticky": "Haftnotiz",+ "stickyColor": "Farbe",+ "stickyColorWhite": "Weiß",+ "stickyColorGray": "Grau",+ "stickyColorRed": "Rot",+ "stickyColorOrange": "Orange",+ "stickyColorYellow": "Gelb",+ "stickyColorGreen": "Grün",+ "stickyColorTeal": "Türkis",+ "stickyColorBlue": "Blau",+ "stickyColorViolet": "Violett",+ "stickyColorPink": "Rosa",+ "stickyTextSize": "Textgröße",+ "stickyTextSmall": "Klein",+ "stickyTextMedium": "Mittel",+ "stickyTextLarge": "Groß",+ "stickyTextExtraLarge": "Sehr groß",+ "stickyTextHuge": "Riesig",+ "stickyShowAuthor": "Autor anzeigen","blendModePassThrough": "Durchreichen","blendModeNormal": "Normal","blendModeDarken": "Abdunkeln",diff --git a/packages/vue/src/i18n/locales/de/tools.json b/packages/vue/src/i18n/locales/de/tools.jsonindex 0608a1892..9cfbde641 100644--- a/packages/vue/src/i18n/locales/de/tools.json+++ b/packages/vue/src/i18n/locales/de/tools.json@@ -10,6 +10,7 @@"pen": "Stift","pencil": "Bleistift","text": "Text",+ "sticky": "Haftnotiz","hand": "Hand","comment": "Kommentar"}diff --git a/packages/vue/src/i18n/locales/es/editor.json b/packages/vue/src/i18n/locales/es/editor.jsonindex b5628a962..8a107612e 100644--- a/packages/vue/src/i18n/locales/es/editor.json+++ b/packages/vue/src/i18n/locales/es/editor.json@@ -4,6 +4,7 @@"cornerRadius": "Redondeado","pointCount": "Cantidad","starRatio": "Proporción",+ "stickyPlaceholder": "Escribe lo que quieras, @menciona a alguien","showUI": "Mostrar interfaz ({shortcut})","previewing": "Vista previa","resetPreview": "Restablecer",diff --git a/packages/vue/src/i18n/locales/es/panels.json b/packages/vue/src/i18n/locales/es/panels.jsonindex b4d5b0c6a..c73762e63 100644--- a/packages/vue/src/i18n/locales/es/panels.json+++ b/packages/vue/src/i18n/locales/es/panels.json@@ -445,6 +445,25 @@"maskTypeAlpha": "Alfa","maskTypeVector": "Vectorial","maskTypeLuminance": "Luminancia",+ "sticky": "Nota adhesiva",+ "stickyColor": "Color",+ "stickyColorWhite": "Blanco",+ "stickyColorGray": "Gris",+ "stickyColorRed": "Rojo",+ "stickyColorOrange": "Naranja",+ "stickyColorYellow": "Amarillo",+ "stickyColorGreen": "Verde",+ "stickyColorTeal": "Turquesa",+ "stickyColorBlue": "Azul",+ "stickyColorViolet": "Violeta",+ "stickyColorPink": "Rosa",+ "stickyTextSize": "Tamaño del texto",+ "stickyTextSmall": "Pequeño",+ "stickyTextMedium": "Mediano",+ "stickyTextLarge": "Grande",+ "stickyTextExtraLarge": "Muy grande",+ "stickyTextHuge": "Enorme",+ "stickyShowAuthor": "Mostrar autor","blendModePassThrough": "Pasar a través","blendModeNormal": "Normal","blendModeDarken": "Oscurecer",diff --git a/packages/vue/src/i18n/locales/es/tools.json b/packages/vue/src/i18n/locales/es/tools.jsonindex efae826c1..25010c286 100644--- a/packages/vue/src/i18n/locales/es/tools.json+++ b/packages/vue/src/i18n/locales/es/tools.json@@ -10,6 +10,7 @@"pen": "Pluma","pencil": "Lápiz","text": "Texto",+ "sticky": "Nota adhesiva","hand": "Mano","comment": "Comentario"}diff --git a/packages/vue/src/i18n/locales/fr/editor.json b/packages/vue/src/i18n/locales/fr/editor.jsonindex 6ec64aad5..e75c6bbfd 100644--- a/packages/vue/src/i18n/locales/fr/editor.json+++ b/packages/vue/src/i18n/locales/fr/editor.json@@ -4,6 +4,7 @@"cornerRadius": "Rayon","pointCount": "Nombre","starRatio": "Rapport",+ "stickyPlaceholder": "Écrivez ce que vous voulez, @mentionnez quelqu’un","showUI": "Afficher l’interface ({shortcut})","previewing": "Aperçu","resetPreview": "Réinitialiser",diff --git a/packages/vue/src/i18n/locales/fr/panels.json b/packages/vue/src/i18n/locales/fr/panels.jsonindex 20b49df1c..a0ab6ea50 100644--- a/packages/vue/src/i18n/locales/fr/panels.json+++ b/packages/vue/src/i18n/locales/fr/panels.json@@ -445,6 +445,25 @@"maskTypeAlpha": "Alpha","maskTypeVector": "Vectoriel","maskTypeLuminance": "Luminance",+ "sticky": "Note autocollante",+ "stickyColor": "Couleur",+ "stickyColorWhite": "Blanc",+ "stickyColorGray": "Gris",+ "stickyColorRed": "Rouge",+ "stickyColorOrange": "Orange",+ "stickyColorYellow": "Jaune",+ "stickyColorGreen": "Vert",+ "stickyColorTeal": "Turquoise",+ "stickyColorBlue": "Bleu",+ "stickyColorViolet": "Violet",+ "stickyColorPink": "Rose",+ "stickyTextSize": "Taille du texte",+ "stickyTextSmall": "Petite",+ "stickyTextMedium": "Moyenne",+ "stickyTextLarge": "Grande",+ "stickyTextExtraLarge": "Très grande",+ "stickyTextHuge": "Énorme",+ "stickyShowAuthor": "Afficher l’auteur","blendModePassThrough": "Traverser","blendModeNormal": "Normal","blendModeDarken": "Obscurcir",diff --git a/packages/vue/src/i18n/locales/fr/tools.json b/packages/vue/src/i18n/locales/fr/tools.jsonindex e6efa5c28..57ae831c7 100644--- a/packages/vue/src/i18n/locales/fr/tools.json+++ b/packages/vue/src/i18n/locales/fr/tools.json@@ -10,6 +10,7 @@"pen": "Plume","pencil": "Crayon","text": "Texte",+ "sticky": "Note autocollante","hand": "Main","comment": "Commentaire"}diff --git a/packages/vue/src/i18n/locales/it/editor.json b/packages/vue/src/i18n/locales/it/editor.jsonindex d01d28792..9b970e09a 100644--- a/packages/vue/src/i18n/locales/it/editor.json+++ b/packages/vue/src/i18n/locales/it/editor.json@@ -4,6 +4,7 @@"cornerRadius": "Raggio","pointCount": "Numero","starRatio": "Rapporto",+ "stickyPlaceholder": "Scrivi qualsiasi cosa, @menziona qualcuno","showUI": "Mostra interfaccia ({shortcut})","previewing": "Anteprima","resetPreview": "Ripristina",diff --git a/packages/vue/src/i18n/locales/it/panels.json b/packages/vue/src/i18n/locales/it/panels.jsonindex 80f8c3a74..469fbaba6 100644--- a/packages/vue/src/i18n/locales/it/panels.json+++ b/packages/vue/src/i18n/locales/it/panels.json@@ -445,6 +445,25 @@"maskTypeAlpha": "Alfa","maskTypeVector": "Vettore","maskTypeLuminance": "Luminanza",+ "sticky": "Nota adesiva",+ "stickyColor": "Colore",+ "stickyColorWhite": "Bianco",+ "stickyColorGray": "Grigio",+ "stickyColorRed": "Rosso",+ "stickyColorOrange": "Arancione",+ "stickyColorYellow": "Giallo",+ "stickyColorGreen": "Verde",+ "stickyColorTeal": "Verde acqua",+ "stickyColorBlue": "Blu",+ "stickyColorViolet": "Viola",+ "stickyColorPink": "Rosa",+ "stickyTextSize": "Dimensione del testo",+ "stickyTextSmall": "Piccolo",+ "stickyTextMedium": "Medio",+ "stickyTextLarge": "Grande",+ "stickyTextExtraLarge": "Molto grande",+ "stickyTextHuge": "Enorme",+ "stickyShowAuthor": "Mostra autore","blendModePassThrough": "Attraversa","blendModeNormal": "Normale","blendModeDarken": "Scurisci",diff --git a/packages/vue/src/i18n/locales/it/tools.json b/packages/vue/src/i18n/locales/it/tools.jsonindex 5e2569228..eb84af858 100644--- a/packages/vue/src/i18n/locales/it/tools.json+++ b/packages/vue/src/i18n/locales/it/tools.json@@ -10,6 +10,7 @@"pen": "Penna","pencil": "Matita","text": "Testo",+ "sticky": "Nota adesiva","hand": "Mano","comment": "Commento"}diff --git a/packages/vue/src/i18n/locales/ja/editor.json b/packages/vue/src/i18n/locales/ja/editor.jsonindex 5d121dd69..8fd5f2ecb 100644--- a/packages/vue/src/i18n/locales/ja/editor.json+++ b/packages/vue/src/i18n/locales/ja/editor.json@@ -4,6 +4,7 @@"cornerRadius": "角丸","pointCount": "数","starRatio": "比率",+ "stickyPlaceholder": "自由に入力、@で誰かをメンション","showUI": "UIを表示 ({shortcut})","previewing": "プレビュー中","resetPreview": "リセット",diff --git a/packages/vue/src/i18n/locales/ja/panels.json b/packages/vue/src/i18n/locales/ja/panels.jsonindex 85f529d79..6cb9bee63 100644--- a/packages/vue/src/i18n/locales/ja/panels.json+++ b/packages/vue/src/i18n/locales/ja/panels.json@@ -439,6 +439,25 @@"maskTypeAlpha": "アルファ","maskTypeVector": "ベクター","maskTypeLuminance": "輝度",+ "sticky": "付箋",+ "stickyColor": "色",+ "stickyColorWhite": "白",+ "stickyColorGray": "グレー",+ "stickyColorRed": "赤",+ "stickyColorOrange": "オレンジ",+ "stickyColorYellow": "黄",+ "stickyColorGreen": "緑",+ "stickyColorTeal": "ティール",+ "stickyColorBlue": "青",+ "stickyColorViolet": "紫",+ "stickyColorPink": "ピンク",+ "stickyTextSize": "テキストサイズ",+ "stickyTextSmall": "小",+ "stickyTextMedium": "中",+ "stickyTextLarge": "大",+ "stickyTextExtraLarge": "特大",+ "stickyTextHuge": "最大",+ "stickyShowAuthor": "作成者を表示","blendModePassThrough": "通過","blendModeNormal": "通常","blendModeDarken": "比較(暗)",diff --git a/packages/vue/src/i18n/locales/ja/tools.json b/packages/vue/src/i18n/locales/ja/tools.jsonindex c4007d9ea..8dad7f3a7 100644--- a/packages/vue/src/i18n/locales/ja/tools.json+++ b/packages/vue/src/i18n/locales/ja/tools.json@@ -10,6 +10,7 @@"pen": "ペンツール","pencil": "鉛筆","text": "テキスト",+ "sticky": "付箋","hand": "手のひらツール","comment": "コメント"}diff --git a/packages/vue/src/i18n/locales/pl/editor.json b/packages/vue/src/i18n/locales/pl/editor.jsonindex 7798daabd..d1daddefb 100644--- a/packages/vue/src/i18n/locales/pl/editor.json+++ b/packages/vue/src/i18n/locales/pl/editor.json@@ -4,6 +4,7 @@"cornerRadius": "Promień","pointCount": "Liczba","starRatio": "Proporcja",+ "stickyPlaceholder": "Wpisz cokolwiek, @wspomnij kogoś","showUI": "Pokaż interfejs ({shortcut})","previewing": "Podgląd","resetPreview": "Resetuj",diff --git a/packages/vue/src/i18n/locales/pl/panels.json b/packages/vue/src/i18n/locales/pl/panels.jsonindex f2e277006..fb3224b68 100644--- a/packages/vue/src/i18n/locales/pl/panels.json+++ b/packages/vue/src/i18n/locales/pl/panels.json@@ -451,6 +451,25 @@"maskTypeAlpha": "Alfa","maskTypeVector": "Wektorowa","maskTypeLuminance": "Luminancja",+ "sticky": "Karteczka",+ "stickyColor": "Kolor",+ "stickyColorWhite": "Biały",+ "stickyColorGray": "Szary",+ "stickyColorRed": "Czerwony",+ "stickyColorOrange": "Pomarańczowy",+ "stickyColorYellow": "Żółty",+ "stickyColorGreen": "Zielony",+ "stickyColorTeal": "Morski",+ "stickyColorBlue": "Niebieski",+ "stickyColorViolet": "Fioletowy",+ "stickyColorPink": "Różowy",+ "stickyTextSize": "Rozmiar tekstu",+ "stickyTextSmall": "Mały",+ "stickyTextMedium": "Średni",+ "stickyTextLarge": "Duży",+ "stickyTextExtraLarge": "Bardzo duży",+ "stickyTextHuge": "Ogromny",+ "stickyShowAuthor": "Pokaż autora","blendModePassThrough": "Przepuszczanie","blendModeNormal": "Normalny","blendModeDarken": "Ciemniej",diff --git a/packages/vue/src/i18n/locales/pl/tools.json b/packages/vue/src/i18n/locales/pl/tools.jsonindex 817b8b4bd..7d7d50170 100644--- a/packages/vue/src/i18n/locales/pl/tools.json+++ b/packages/vue/src/i18n/locales/pl/tools.json@@ -10,6 +10,7 @@"pen": "Pióro","pencil": "Ołówek","text": "Tekst",+ "sticky": "Karteczka","hand": "Dłoń","comment": "Komentarz"}diff --git a/packages/vue/src/i18n/locales/ru/editor.json b/packages/vue/src/i18n/locales/ru/editor.jsonindex b77178bc6..e8112a637 100644--- a/packages/vue/src/i18n/locales/ru/editor.json+++ b/packages/vue/src/i18n/locales/ru/editor.json@@ -4,6 +4,7 @@"cornerRadius": "Радиус","pointCount": "Количество","starRatio": "Соотношение",+ "stickyPlaceholder": "Пишите что угодно, @упоминайте кого угодно","showUI": "Показать интерфейс ({shortcut})","previewing": "Просмотр","resetPreview": "Сбросить",diff --git a/packages/vue/src/i18n/locales/ru/panels.json b/packages/vue/src/i18n/locales/ru/panels.jsonindex 2a0ddcac6..e7a7a9a5c 100644--- a/packages/vue/src/i18n/locales/ru/panels.json+++ b/packages/vue/src/i18n/locales/ru/panels.json@@ -451,6 +451,25 @@"maskTypeAlpha": "Альфа-канал","maskTypeVector": "Вектор","maskTypeLuminance": "Яркость",+ "sticky": "Стикер",+ "stickyColor": "Цвет",+ "stickyColorWhite": "Белый",+ "stickyColorGray": "Серый",+ "stickyColorRed": "Красный",+ "stickyColorOrange": "Оранжевый",+ "stickyColorYellow": "Жёлтый",+ "stickyColorGreen": "Зелёный",+ "stickyColorTeal": "Бирюзовый",+ "stickyColorBlue": "Синий",+ "stickyColorViolet": "Фиолетовый",+ "stickyColorPink": "Розовый",+ "stickyTextSize": "Размер текста",+ "stickyTextSmall": "Маленький",+ "stickyTextMedium": "Средний",+ "stickyTextLarge": "Крупный",+ "stickyTextExtraLarge": "Очень крупный",+ "stickyTextHuge": "Огромный",+ "stickyShowAuthor": "Показывать автора","blendModePassThrough": "Сквозной","blendModeNormal": "Обычный","blendModeDarken": "Затемнение",diff --git a/packages/vue/src/i18n/locales/ru/tools.json b/packages/vue/src/i18n/locales/ru/tools.jsonindex f92e8cc28..56bfa1cfa 100644--- a/packages/vue/src/i18n/locales/ru/tools.json+++ b/packages/vue/src/i18n/locales/ru/tools.json@@ -10,6 +10,7 @@"pen": "Перо","pencil": "Карандаш","text": "Текст",+ "sticky": "Стикер","hand": "Рука","comment": "Комментарий"}diff --git a/packages/vue/src/i18n/locales/zh-cn/editor.json b/packages/vue/src/i18n/locales/zh-cn/editor.jsonindex 712baa3be..837a59827 100644--- a/packages/vue/src/i18n/locales/zh-cn/editor.json+++ b/packages/vue/src/i18n/locales/zh-cn/editor.json@@ -4,6 +4,7 @@"cornerRadius": "圆角","pointCount": "数量","starRatio": "比例",+ "stickyPlaceholder": "输入任意内容,@提及任何人","showUI": "显示界面({shortcut})","previewing": "预览中","resetPreview": "重置",diff --git a/packages/vue/src/i18n/locales/zh-cn/panels.json b/packages/vue/src/i18n/locales/zh-cn/panels.jsonindex 8c60be969..9a970f4ce 100644--- a/packages/vue/src/i18n/locales/zh-cn/panels.json+++ b/packages/vue/src/i18n/locales/zh-cn/panels.json@@ -439,6 +439,25 @@"maskTypeAlpha": "Alpha","maskTypeVector": "矢量","maskTypeLuminance": "亮度",+ "sticky": "便利贴",+ "stickyColor": "颜色",+ "stickyColorWhite": "白色",+ "stickyColorGray": "灰色",+ "stickyColorRed": "红色",+ "stickyColorOrange": "橙色",+ "stickyColorYellow": "黄色",+ "stickyColorGreen": "绿色",+ "stickyColorTeal": "青色",+ "stickyColorBlue": "蓝色",+ "stickyColorViolet": "紫色",+ "stickyColorPink": "粉色",+ "stickyTextSize": "文字大小",+ "stickyTextSmall": "小",+ "stickyTextMedium": "中",+ "stickyTextLarge": "大",+ "stickyTextExtraLarge": "特大",+ "stickyTextHuge": "超大",+ "stickyShowAuthor": "显示作者","blendModePassThrough": "穿透","blendModeNormal": "正常","blendModeDarken": "变暗",diff --git a/packages/vue/src/i18n/locales/zh-cn/tools.json b/packages/vue/src/i18n/locales/zh-cn/tools.jsonindex c3160d632..7f5fdc344 100644--- a/packages/vue/src/i18n/locales/zh-cn/tools.json+++ b/packages/vue/src/i18n/locales/zh-cn/tools.json@@ -10,6 +10,7 @@"pen": "钢笔","pencil": "铅笔","text": "文本",+ "sticky": "便利贴","hand": "抓手","comment": "评论"}diff --git a/packages/vue/src/i18n/messages/editor.ts b/packages/vue/src/i18n/messages/editor.tsindex 0ec164af3..47653353c 100644--- a/packages/vue/src/i18n/messages/editor.ts+++ b/packages/vue/src/i18n/messages/editor.ts@@ -11,6 +11,8 @@ export const editorMessageDefaults = {pointCount: 'Count',/** The word before a star's inner ratio beside its dragged handle. */starRatio: 'Ratio',+ /** What an empty sticky note shows in its body on the canvas. */+ stickyPlaceholder: 'Type anything, @mention anyone',showUI: params('Show UI ({shortcut})'),previewing: 'Previewing',startPreview: params('Preview ({shortcut})'),diff --git a/packages/vue/src/i18n/messages/panels.ts b/packages/vue/src/i18n/messages/panels.tsindex ca8180078..4d3dd055b 100644--- a/packages/vue/src/i18n/messages/panels.ts+++ b/packages/vue/src/i18n/messages/panels.ts@@ -370,6 +370,26 @@ export const panelMessageDefaults = {maskTypeVector: 'Vector',maskTypeLuminance: 'Luminance',+ sticky: 'Sticky note',+ stickyColor: 'Color',+ stickyColorWhite: 'White',+ stickyColorGray: 'Gray',+ stickyColorRed: 'Red',+ stickyColorOrange: 'Orange',+ stickyColorYellow: 'Yellow',+ stickyColorGreen: 'Green',+ stickyColorTeal: 'Teal',+ stickyColorBlue: 'Blue',+ stickyColorViolet: 'Violet',+ stickyColorPink: 'Pink',+ stickyTextSize: 'Text size',+ stickyTextSmall: 'Small',+ stickyTextMedium: 'Medium',+ stickyTextLarge: 'Large',+ stickyTextExtraLarge: 'Extra large',+ stickyTextHuge: 'Huge',+ stickyShowAuthor: 'Show author',+blendModePassThrough: 'Pass through',blendModeNormal: 'Normal',blendModeDarken: 'Darken',diff --git a/packages/vue/src/i18n/messages/tools.ts b/packages/vue/src/i18n/messages/tools.tsindex 745df484b..124aafb0f 100644--- a/packages/vue/src/i18n/messages/tools.ts+++ b/packages/vue/src/i18n/messages/tools.ts@@ -12,6 +12,7 @@ export const toolMessageDefaults = {pen: 'Pen',pencil: 'Pencil',text: 'Text',+ sticky: 'Sticky note',hand: 'Hand',comment: 'Comment'} as constdiff --git a/packages/vue/src/index.ts b/packages/vue/src/index.tsindex 6761bbfd1..6ad390ab4 100644--- a/packages/vue/src/index.ts+++ b/packages/vue/src/index.ts@@ -125,6 +125,7 @@ export {type VariableModeOption} from '#vue/controls/variable-modes/helpers'export { useMask } from '#vue/controls/mask/use'+export { useStickyNote } from '#vue/controls/sticky/use'export { useIcon } from '#vue/controls/icon/use'export { useIconSearch } from '#vue/controls/icon/search'export { useTypography } from '#vue/controls/typography/use'diff --git a/packages/vue/src/shared/input/auto-layout-hover.ts b/packages/vue/src/shared/input/auto-layout-hover.tsindex 361ac8f02..de03a1bad 100644--- a/packages/vue/src/shared/input/auto-layout-hover.ts+++ b/packages/vue/src/shared/input/auto-layout-hover.ts@@ -4,6 +4,7 @@ import {AUTO_LAYOUT_HOVER_TICK_HIT_TOLERANCE} from '@open-pencil/core/constants'import type { Editor } from '@open-pencil/core/editor'+import { isGeneratedFrame } from '@open-pencil/scene-graph'import type { SceneNode, Vector } from '@open-pencil/scene-graph'type AutoLayoutHover = NonNullable<Editor['state']['autoLayoutHover']>@@ -143,6 +144,8 @@ export function resolveAutoLayoutHover(const nodeId = [...editor.state.selectedIds][0]const node = editor.graph.getNode(nodeId)if (!node || (node.layoutMode !== 'HORIZONTAL' && node.layoutMode !== 'VERTICAL')) return null+ // A generated frame, such as a sticky note, lays itself out; its spacing is not the user's.+ if (isGeneratedFrame(node)) return nullconst abs = editor.graph.getAbsolutePosition(node.id)const localX = cx - abs.xdiff --git a/packages/vue/src/shared/input/draw.ts b/packages/vue/src/shared/input/draw.tsindex 23d8ad114..13361b386 100644--- a/packages/vue/src/shared/input/draw.ts+++ b/packages/vue/src/shared/input/draw.ts@@ -9,7 +9,7 @@ import { TOOL_TO_NODE } from '#vue/shared/input/types'import type { DragDraw, DragState } from '#vue/shared/input/types'/** Maps canvas points into the axes of the parent a layer is drawn in. */-function parentSpace(editor: Editor, parentId: string): DragDraw['toLocal'] {+export function parentSpace(editor: Editor, parentId: string): DragDraw['toLocal'] {const parent = editor.graph.getNode(parentId)if (!parent || parent.type === 'CANVAS') return (x, y) => ({ x, y })const toLocal = Matrix.invert(getWorldMatrix(parent, editor.graph)) ?? Matrix.identity()diff --git a/packages/vue/src/shared/input/resize/start.ts b/packages/vue/src/shared/input/resize/start.tsindex a55ab511e..f1ca4e00f 100644--- a/packages/vue/src/shared/input/resize/start.ts+++ b/packages/vue/src/shared/input/resize/start.ts@@ -8,7 +8,8 @@ import type { DragResize } from '#vue/shared/input/types'export function tryStartResize(cx: number, cy: number, editor: Editor): DragResize | null {for (const id of editor.state.selectedIds) {const node = editor.graph.getNode(id)- if (!node || node.locked) continue+ // A sticky note only scales, from its corners; see `tryStartStickyScale`.+ if (!node || node.locked || node.type === 'STICKY') continueconst handleResult = getHitHandleByMatrix(cx,cy,diff --git a/packages/vue/src/shared/input/select.ts b/packages/vue/src/shared/input/select.tsindex aeb572c39..86c824c42 100644--- a/packages/vue/src/shared/input/select.ts+++ b/packages/vue/src/shared/input/select.ts@@ -14,6 +14,7 @@ import {selectionIsLocked} from '#vue/shared/input/select/move'import { tryStartShapeHandleDrag } from '#vue/shared/input/shape-handles'+import { tryStartStickyScale } from '#vue/shared/input/sticky/scale'import type { DragState } from '#vue/shared/input/types'export interface HitTestFns {@@ -50,6 +51,11 @@ function tryStartHandleDrag(// An open gradient's handles replace the layer's selection handles, which then do not respond.if (editedGradient(editor.graph, editor.state.gradientEdit)) return falseif (tryStartShapeHandleDrag(editor, sx, sy, altKey, setDrag)) return true+ const scaleDrag = tryStartStickyScale(cx, cy, editor)+ if (scaleDrag) {+ setDrag(scaleDrag)+ return true+ }const resizeDrag = tryStartResize(cx, cy, editor)if (resizeDrag) {setDrag(resizeDrag)diff --git a/packages/vue/src/shared/input/select/hover.ts b/packages/vue/src/shared/input/select/hover.tsindex 38c531c91..36215c949 100644--- a/packages/vue/src/shared/input/select/hover.ts+++ b/packages/vue/src/shared/input/select/hover.ts@@ -33,7 +33,7 @@ function getRotationCursorForSelection(cx: number, cy: number, editor: Editor):const id = [...editor.state.selectedIds][0]const node = editor.graph.getNode(id)- if (!node) return null+ if (!node || node.type === 'STICKY') return nullconst corner = hitTestCornerRotationByMatrix(cx,diff --git a/packages/vue/src/shared/input/sticky/place.ts b/packages/vue/src/shared/input/sticky/place.tsnew file mode 100644index 000000000..dd1120230--- /dev/null+++ b/packages/vue/src/shared/input/sticky/place.ts@@ -0,0 +1,31 @@+import type { Editor } from '@open-pencil/core/editor'+import { stickySublayers } from '@open-pencil/scene-graph'++import { parentSpace } from '#vue/shared/input/draw'+import { findDrawParent } from '#vue/shared/input/drop-target'+import type { DragPlace, DragState } from '#vue/shared/input/types'++/** Places a note centred on the canvas point, then types into its body, as FigJam does. */+function placeSticky(editor: Editor, cx: number, cy: number) {+ const parentId = findDrawParent(cx, cy, 'STICKY', editor)+ const sticky = editor.createStickyNote(parentId, parentSpace(editor, parentId)(cx, cy))+ editor.setTool('SELECT')+ const body = stickySublayers(editor.graph, sticky)?.body+ if (body) editor.startTextEditing(body.id)+}++/** The sticky tool places a note where the pointer is released, a click or the end of a drag. */+export function startStickyPlace(+ cx: number,+ cy: number,+ editor: Editor,+ setDrag: (d: DragState) => void+) {+ const drag: DragPlace = {+ type: 'place',+ x: cx,+ y: cy,+ commit: () => placeSticky(editor, drag.x, drag.y)+ }+ setDrag(drag)+}diff --git a/packages/vue/src/shared/input/sticky/scale.ts b/packages/vue/src/shared/input/sticky/scale.tsnew file mode 100644index 000000000..dd99c5384--- /dev/null+++ b/packages/vue/src/shared/input/sticky/scale.ts@@ -0,0 +1,135 @@+import { toRaw } from 'vue'++import type { Editor } from '@open-pencil/core/editor'+import {+ isWideSticky,+ scaleNodeChanges,+ stickyScale,+ stickySublayers,+ stickyWidth+} from '@open-pencil/scene-graph'+import type { SceneNode } from '@open-pencil/scene-graph'++import { getHitHandleByMatrix } from '#vue/shared/input/geometry'+import { calculateResizeRect } from '#vue/shared/input/resize/rect'+import type { DragStickyScale } from '#vue/shared/input/types'++/** The smallest scale a corner drag takes a note to, so it never folds away. */+const MIN_STICKY_SCALE = 0.1++function subtree(editor: Editor, root: SceneNode): Map<string, SceneNode> {+ const nodes = new Map<string, SceneNode>()+ const visit = (node: SceneNode) => {+ nodes.set(node.id, { ...node })+ for (const child of editor.graph.getChildren(node.id)) visit(child)+ }+ visit(root)+ return nodes+}++/**+ * Dragging a selected sticky note's handle changes it as FigJam does: a corner, the top, or the+ * bottom scales the whole note, its text included, and a side switches it between square and+ * wide. A note has no free size, since its height follows its text.+ */+export function tryStartStickyScale(+ cx: number,+ cy: number,+ editor: Editor+): DragStickyScale | null {+ if (editor.state.selectedIds.size !== 1) return null+ const node = editor.graph.getNode([...editor.state.selectedIds][0])+ if (node?.type !== 'STICKY' || node.locked) return null+ const hit = getHitHandleByMatrix(+ cx,+ cy,+ node,+ editor.graph,+ editor.renderer?.zoom,+ editor.state.rotationPreview+ )+ if (!hit) return null+ const wide = isWideSticky(editor.graph, node)+ const drag: DragStickyScale = {+ type: 'sticky-scale',+ mode: hit.handle === 'e' || hit.handle === 'w' ? 'wide' : 'scale',+ handle: hit.handle,+ startX: cx,+ startY: cy,+ nodeId: node.id,+ origRect: { x: node.x, y: node.y, width: node.width, height: node.height },+ originals: subtree(editor, node),+ scale: 1,+ position: { x: node.x, y: node.y },+ wide,+ commit: () => commitStickyScale(drag, editor),+ cancel: () => cancelStickyScale(drag, editor)+ }+ return drag+}++/** Shows a side drag's note at the width it snaps to, square or wide, whichever is nearer. */+function applyStickyWide(d: DragStickyScale, cx: number, editor: Editor) {+ const { origRect } = d+ const root = d.originals.get(d.nodeId)+ const scale = stickyScale(root && stickySublayers(editor.graph, root)?.author)+ const dragged = origRect.width + (d.handle === 'e' ? cx - d.startX : d.startX - cx)+ const square = stickyWidth(scale, false)+ const wide = stickyWidth(scale, true)+ d.wide = Math.abs(dragged - wide) < Math.abs(dragged - square)+ const width = d.wide ? wide : square+ const x = d.handle === 'w' ? origRect.x + origRect.width - width : origRect.x+ editor.graph.updateNodePreview(d.nodeId, { x, width })+ for (const [id, original] of d.originals) {+ if (id !== d.nodeId)+ editor.graph.updateNodePreview(id, { width: original.width + width - origRect.width })+ }+ editor.requestRepaint()+}++/** Shows the note as the handle has changed it; only the commit records it. */+export function applyStickyScale(drag: DragStickyScale, cx: number, cy: number, editor: Editor) {+ const d = toRaw(drag)+ if (d.mode === 'wide') {+ applyStickyWide(d, cx, editor)+ return+ }+ const { origRect } = d+ // The note keeps its proportions, anchored as a resize from the same handle would be.+ const rect = calculateResizeRect(+ d.handle,+ origRect,+ cx - d.startX,+ cy - d.startY,+ origRect.width / origRect.height+ )+ d.scale = Math.max(MIN_STICKY_SCALE, rect.width / origRect.width)+ d.position = { x: rect.x, y: rect.y }+ for (const [id, original] of d.originals) {+ const changes = scaleNodeChanges(original, d.scale, id !== d.nodeId)+ if (id === d.nodeId) Object.assign(changes, d.position)+ editor.graph.updateNodePreview(id, changes)+ }+ editor.requestRepaint()+}++function restoreStickyScale(d: DragStickyScale, editor: Editor) {+ for (const [id, original] of d.originals) {+ const changes = scaleNodeChanges(original, 1, id !== d.nodeId)+ if (id === d.nodeId) Object.assign(changes, { x: original.x, y: original.y })+ editor.graph.updateNodePreview(id, { ...changes, width: original.width })+ }+}++function commitStickyScale(drag: DragStickyScale, editor: Editor) {+ const d = toRaw(drag)+ restoreStickyScale(d, editor)+ if (d.mode === 'wide') editor.setStickyWide(d.nodeId, d.wide, d.handle === 'w' ? 'right' : 'left')+ else if (d.scale !== 1) editor.scaleStickyNote(d.nodeId, d.scale, d.position)+ editor.requestRender()+}++function cancelStickyScale(drag: DragStickyScale, editor: Editor) {+ restoreStickyScale(toRaw(drag), editor)+ editor.requestRender()+}diff --git a/packages/vue/src/shared/input/types.ts b/packages/vue/src/shared/input/types.tsindex 6a3f40a4c..91dd1d2ca 100644--- a/packages/vue/src/shared/input/types.ts+++ b/packages/vue/src/shared/input/types.ts@@ -32,6 +32,38 @@ export interface DragDraw {cancel: () => void}+/** A layer placed where the pointer is released, such as a sticky note. */+export interface DragPlace {+ type: 'place'+ /** Where the pointer is, in canvas coordinates. */+ x: number+ y: number+ commit: () => void+}++/**+ * A sticky note's handle dragged: a corner, top, or bottom scales the whole note, a side switches+ * it between square and wide, as in FigJam.+ */+export interface DragStickyScale {+ type: 'sticky-scale'+ mode: 'scale' | 'wide'+ handle: HandlePosition+ startX: number+ startY: number+ nodeId: string+ origRect: Rect+ /** The note and its sublayers as the drag found them. */+ originals: Map<string, SceneNode>+ /** The scale and top-left the latest step reached. */+ scale: number+ position: Vector+ /** Whether a side drag has reached the wide width. */+ wide: boolean+ commit: () => void+ cancel: () => void+}+export interface DragMove {type: 'move'startX: number@@ -205,10 +237,12 @@ export interface DragShapeHandle {export type DragState =| DragShapeHandle| DragDraw+ | DragPlace| DragGradient| DragMove| DragPan| DragResize+ | DragStickyScale| DragMarquee| DragRotate| DragPendiff --git a/src/app/editor/icons.ts b/src/app/editor/icons.tsindex 8e4242984..e698f6eba 100644--- a/src/app/editor/icons.ts+++ b/src/app/editor/icons.ts@@ -38,6 +38,7 @@ export const toolIcons: Record<Tool, Component> = {PEN: IconPenTool,PENCIL: IconPencil,TEXT: IconType,+ STICKY: IconStickyNote,HAND: IconHand,COMMENT: IconMessageCircle}diff --git a/src/app/editor/session/create.ts b/src/app/editor/session/create.tsindex a86d559bd..534fa3f5a 100644--- a/src/app/editor/session/create.ts+++ b/src/app/editor/session/create.ts@@ -5,6 +5,7 @@ import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'import { SceneGraph } from '@open-pencil/scene-graph'import { createShaderRasterizer } from '@open-pencil/vue'+import { useCollabIdentity } from '@/app/collab/identity'import { recordPreparationOutcome } from '@/app/diagnostics'import {getActiveEditorStore,@@ -51,6 +52,7 @@ function buildEditorStore(initialGraph?: SceneGraph) {shaderRasterizer: createShaderRasterizer(),resolveFigmaClipboardImages: IS_TAURI ? resolveFigmaClipboardImages : undefined,skipInitialGraphSetup: !!initialGraph,+ getUserName: () => useCollabIdentity().name.value,getViewportSize: () =>viewportSize.width > 0 && viewportSize.height > 0? viewportSizediff --git a/src/app/editor/toolbar/layout.ts b/src/app/editor/toolbar/layout.tsindex ebe3042f6..7effbcfb5 100644--- a/src/app/editor/toolbar/layout.ts+++ b/src/app/editor/toolbar/layout.ts@@ -19,12 +19,18 @@ export interface ToolbarLayout {/** The one entry the toolbar always shows, so it is never empty. */export const PINNED_TOOLBAR_ENTRY: ToolbarEntry = 'SELECT'+/**+ * Tools the toolbar keeps hidden until shown from Customize toolbar, such as FigJam's sticky+ * note, which Figma's own toolbar does not offer.+ */+const HIDDEN_BY_DEFAULT: readonly ToolbarEntry[] = ['STICKY']+export const DEFAULT_TOOLBAR_LAYOUT: Readonly<ToolbarLayout> = {groups: [...EDITOR_TOOLS.map((tool) => [...(tool.flyout ?? [tool.key])]),...TOOLBAR_ACTIONS.map((action) => [action])],- hidden: []+ hidden: [...HIDDEN_BY_DEFAULT]}const ENTRIES = DEFAULT_TOOLBAR_LAYOUT.groups.flat()@@ -65,7 +71,8 @@ function placeMissing(groups: ToolbarEntry[][], entry: ToolbarEntry) {/*** Reads a stored layout: unknown entries and repeats are dropped, actions stand alone, empty- * groups go, and entries it does not mention are placed as `placeMissing` describes.+ * groups go, and entries it does not mention are placed as `placeMissing` describes, hidden when+ * the default layout hides them.*/export function normalizeToolbarLayout(storedGroups: readonly (readonly unknown[])[],@@ -88,8 +95,10 @@ export function normalizeToolbarLayout(}if (group.length > 0) groups.push(group)}- for (const entry of ENTRIES) if (!placed.has(entry)) placeMissing(groups, entry)- const hidden = uniq(storedHidden.filter(isToolbarEntry)).filter(+ const missing = ENTRIES.filter((entry) => !placed.has(entry))+ for (const entry of missing) placeMissing(groups, entry)+ const hiddenMissing = missing.filter((entry) => HIDDEN_BY_DEFAULT.includes(entry))+ const hidden = uniq([...storedHidden.filter(isToolbarEntry), ...hiddenMissing]).filter((entry) => entry !== PINNED_TOOLBAR_ENTRY)return { groups, hidden }diff --git a/src/app/editor/toolbar/shortcuts.ts b/src/app/editor/toolbar/shortcuts.tsindex c66698eae..53f61a280 100644--- a/src/app/editor/toolbar/shortcuts.ts+++ b/src/app/editor/toolbar/shortcuts.ts@@ -16,6 +16,7 @@ const TOOL_SHORTCUT_KEYS: Readonly<Record<Tool, string>> = {PEN: 'P',PENCIL: 'SHIFT+P',TEXT: 'T',+ STICKY: '',HAND: 'H',COMMENT: 'C'}diff --git a/src/app/shell/keyboard/actions.ts b/src/app/shell/keyboard/actions.tsindex fc1280814..5a6fd2700 100644--- a/src/app/shell/keyboard/actions.ts+++ b/src/app/shell/keyboard/actions.ts@@ -1,6 +1,7 @@import type { Ref } from 'vue'import { opacityFromBuffer } from '@open-pencil/core/editor'+import { stickySublayers } from '@open-pencil/scene-graph'import type { useEditorCommands, useViewportKind } from '@open-pencil/vue'import type { PropertiesTab } from '@/app/ai/chat/use'@@ -54,9 +55,11 @@ export function createKeyboardActions({store.enterNodeEditMode(node.id)return}- if (node?.type === 'TEXT') {+ // A sticky note opens its body, all of it selected, keeping the note selected.+ const text = node?.type === 'STICKY' ? stickySublayers(store.graph, node)?.body : node+ if (text?.type === 'TEXT') {requestAnimationFrame(() => {- store.startTextEditing(node.id)+ store.startTextEditing(text.id)store.textEditor?.selectAll()store.requestRender()})diff --git a/src/components/DesignPanel.vue b/src/components/DesignPanel.vueindex 233029cd2..eb983123f 100644--- a/src/components/DesignPanel.vue+++ b/src/components/DesignPanel.vue@@ -40,6 +40,7 @@ import PositionSection from './properties/PositionSection.vue'import SelectionColorsSection from './properties/selection/SelectionColorsSection.vue'import SelectionLayoutSection from './properties/selection/SelectionLayoutSection.vue'import SelectionActionsControl from './properties/SelectionActionsControl.vue'+import StickySection from './properties/sticky/StickySection.vue'import StrokeSection from './properties/stroke/StrokeSection.vue'import TypographySection from './properties/TypographySection.vue'import VariablesSection from './properties/VariablesSection.vue'@@ -206,9 +207,11 @@ const { panels } = useI18n()<FramePresetSelect v-if="node.type === 'FRAME' && !readIcon(node)" /><IconSection />+ <StickySection /><PositionSection /><ConstraintsSection />- <LayoutSection />+ <!-- A sticky note's size follows its text and its scale; Figma leaves W and H read-only. -->+ <LayoutSection v-if="node.type !== 'STICKY'" /><AppearanceSection /><MaskSection /><TypographySection v-if="node.type === 'TEXT'" />diff --git a/src/components/properties/sticky/StickyControls.stories.ts b/src/components/properties/sticky/StickyControls.stories.tsnew file mode 100644index 000000000..0e6371a4f--- /dev/null+++ b/src/components/properties/sticky/StickyControls.stories.ts@@ -0,0 +1,68 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'+import { expect, userEvent, within } from 'storybook/test'+import { ref } from 'vue'++import { DEFAULT_STICKY_COLOR, type StickyTextSize } from '@open-pencil/scene-graph'+import type { Color } from '@open-pencil/scene-graph/primitives'++import StickyControls from './StickyControls.vue'++const meta = {+ title: 'App/Editor/Properties/Sticky Note',+ tags: ['autodocs'],+ parameters: {+ docs: {+ description: {+ component:+ "A selected sticky note's FigJam palette, body text size, and author line, as the Design panel shows them."+ }+ }+ },+ render: () => ({+ components: { StickyControls },+ setup() {+ const color = ref<Color>({ ...DEFAULT_STICKY_COLOR })+ const textSize = ref<StickyTextSize>('small')+ const authorVisible = ref(true)+ return { color, textSize, authorVisible }+ },+ template: `+ <div class="w-[240px] bg-panel p-4">+ <StickyControls+ :color="color"+ :text-size="textSize"+ :author-visible="authorVisible"+ @update:color="color = $event"+ @update:text-size="textSize = $event"+ @update:author-visible="authorVisible = $event"+ />+ </div>`+ })+} satisfies Meta+export default meta+type Story = StoryObj<typeof meta>++export const Default: Story = {}++export const PickColor: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ await expect(canvas.getByRole('radio', { name: 'Blue' })).toHaveAttribute(+ 'aria-checked',+ 'true'+ )+ await userEvent.click(canvas.getByRole('radio', { name: 'Yellow' }))+ await expect(canvas.getByRole('radio', { name: 'Yellow' })).toHaveAttribute(+ 'aria-checked',+ 'true'+ )+ }+}++export const HideAuthor: Story = {+ play: async ({ canvasElement }) => {+ const author = within(canvasElement).getByRole('switch', { name: 'Show author' })+ await userEvent.click(author)+ await expect(author).toHaveAttribute('aria-checked', 'false')+ }+}diff --git a/src/components/properties/sticky/StickyControls.vue b/src/components/properties/sticky/StickyControls.vuenew file mode 100644index 000000000..4e276efe2--- /dev/null+++ b/src/components/properties/sticky/StickyControls.vue@@ -0,0 +1,105 @@+<script setup lang="ts">+import { tv } from 'tailwind-variants'+import { computed } from 'vue'++import { STICKY_COLORS, type StickyTextSize } from '@open-pencil/scene-graph'+import { colorToHex } from '@open-pencil/scene-graph/color'+import type { Color } from '@open-pencil/scene-graph/primitives'+import { useI18n } from '@open-pencil/vue'++import PanelFieldGroup from '@/components/ui/panel/PanelFieldGroup.vue'+import AppSelect from '@/components/ui/select/AppSelect.vue'+import AppSwitch from '@/components/ui/toggle/AppSwitch.vue'+import stickyControlsTheme from '@/theme/sticky-controls'++type StickyColorName = keyof typeof STICKY_COLORS++const { color, textSize, authorVisible } = defineProps<{+ color: Color | null+ textSize: StickyTextSize | null+ authorVisible: boolean+}>()++const emit = defineEmits<{+ 'update:color': [value: Color]+ 'update:textSize': [value: StickyTextSize]+ 'update:authorVisible': [value: boolean]+}>()++const { panels } = useI18n()+const styles = tv(stickyControlsTheme)++const COLOR_LABEL_KEYS = {+ white: 'stickyColorWhite',+ gray: 'stickyColorGray',+ red: 'stickyColorRed',+ orange: 'stickyColorOrange',+ yellow: 'stickyColorYellow',+ green: 'stickyColorGreen',+ teal: 'stickyColorTeal',+ blue: 'stickyColorBlue',+ violet: 'stickyColorViolet',+ pink: 'stickyColorPink'+} as const satisfies Record<StickyColorName, string>++const swatches = computed(() =>+ (Object.entries(STICKY_COLORS) as [StickyColorName, Color][]).map(([name, value]) => ({+ name,+ value,+ hex: colorToHex(value),+ label: panels.value[COLOR_LABEL_KEYS[name]],+ active: color !== null && colorToHex(color) === colorToHex(value)+ }))+)++const sizeOptions = computed<Array<{ value: StickyTextSize; label: string }>>(() => [+ { value: 'small', label: panels.value.stickyTextSmall },+ { value: 'medium', label: panels.value.stickyTextMedium },+ { value: 'large', label: panels.value.stickyTextLarge },+ { value: 'extraLarge', label: panels.value.stickyTextExtraLarge },+ { value: 'huge', label: panels.value.stickyTextHuge }+])++const selectedSize = computed<StickyTextSize>({+ get: () => textSize ?? 'small',+ set: (value) => emit('update:textSize', value)+})+</script>++<template>+ <div :class="styles().root()">+ <PanelFieldGroup :label="panels.stickyColor">+ <div :class="styles().swatches()" role="radiogroup" :aria-label="panels.stickyColor">+ <button+ v-for="swatch in swatches"+ :key="swatch.name"+ type="button"+ role="radio"+ :aria-checked="swatch.active"+ :aria-label="swatch.label"+ :data-sticky-color="swatch.name"+ :class="styles({ active: swatch.active }).swatch()"+ :style="{ backgroundColor: swatch.hex }"+ @click="emit('update:color', swatch.value)"+ />+ </div>+ </PanelFieldGroup>+ <PanelFieldGroup :label="panels.stickyTextSize">+ <AppSelect+ v-model="selectedSize"+ :label="panels.stickyTextSize"+ :options="sizeOptions"+ data-property="sticky-text-size"+ />+ </PanelFieldGroup>+ <label :class="styles().option()">+ <span>{{ panels.stickyShowAuthor }}</span>+ <AppSwitch+ :model-value="authorVisible"+ :label="panels.stickyShowAuthor"+ data-property="sticky-show-author"+ @update:model-value="emit('update:authorVisible', $event)"+ />+ </label>+ </div>+</template>diff --git a/src/components/properties/sticky/StickySection.vue b/src/components/properties/sticky/StickySection.vuenew file mode 100644index 000000000..386a027a3--- /dev/null+++ b/src/components/properties/sticky/StickySection.vue@@ -0,0 +1,24 @@+<script setup lang="ts">+import { useI18n, useStickyNote } from '@open-pencil/vue'++import PanelSection from '@/components/ui/panel/PanelSection.vue'++import StickyControls from './StickyControls.vue'++const { panels } = useI18n()+const { active, color, textSize, authorVisible, setColor, setTextSize, setAuthorVisible } =+ useStickyNote()+</script>++<template>+ <PanelSection v-if="active" :label="panels.sticky">+ <StickyControls+ :color="color"+ :text-size="textSize"+ :author-visible="authorVisible"+ @update:color="setColor"+ @update:text-size="setTextSize"+ @update:author-visible="setAuthorVisible"+ />+ </PanelSection>+</template>diff --git a/src/components/toolbar/labels.ts b/src/components/toolbar/labels.tsindex 1e1f3c5dc..a2327ff4e 100644--- a/src/components/toolbar/labels.ts+++ b/src/components/toolbar/labels.ts@@ -21,6 +21,7 @@ export function useToolLabels() {PEN: tools.value.pen,PENCIL: tools.value.pencil,TEXT: tools.value.text,+ STICKY: tools.value.sticky,HAND: tools.value.hand,COMMENT: tools.value.comment}))diff --git a/src/theme/sticky-controls.ts b/src/theme/sticky-controls.tsnew file mode 100644index 000000000..5cff26292--- /dev/null+++ b/src/theme/sticky-controls.ts@@ -0,0 +1,21 @@+const stickyControlsTheme = {+ slots: {+ root: 'grid gap-2.5',+ swatches: 'flex flex-wrap gap-1',+ swatch:+ 'size-[18px] cursor-pointer rounded-full border border-border focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/50',+ option: 'flex items-center justify-between gap-1.5 text-[11px] text-muted'+ },+ variants: {+ active: {+ true: { swatch: 'ring-2 ring-accent ring-offset-1 ring-offset-panel' },+ false: { swatch: 'hover:border-muted' }+ }+ },+ defaultVariants: {+ active: false+ }+}++export type StickyControlsTheme = typeof stickyControlsTheme+export default stickyControlsThemediff --git a/tests/app/editor/toolbar/layout.test.ts b/tests/app/editor/toolbar/layout.test.tsindex 6cc0b2d10..b32ea1df3 100644--- a/tests/app/editor/toolbar/layout.test.ts+++ b/tests/app/editor/toolbar/layout.test.ts@@ -27,14 +27,17 @@ function layout(groups: ToolbarEntry[][], hidden: ToolbarEntry[] = []): ToolbarLdescribe('normalizeToolbarLayout', () => {test('keeps the default layout as it is', () => {- expect(layout(DEFAULT_TOOLBAR_LAYOUT.groups)).toEqual(DEFAULT_TOOLBAR_LAYOUT)+ expect(layout(DEFAULT_TOOLBAR_LAYOUT.groups, DEFAULT_TOOLBAR_LAYOUT.hidden)).toEqual(+ DEFAULT_TOOLBAR_LAYOUT+ )})test('drops unknown entries, repeats and empty groups', () => {const groups = [['SELECT', 'LASSO', 'SELECT'], [], ['FRAME', 'SECTION', 'FRAME']]const result = normalizeToolbarLayout(groups, ['HAND', 'HAND', 'GHOST'])expect(result.groups.slice(0, 2)).toEqual([['SELECT'], ['FRAME', 'SECTION']])- expect(result.hidden).toEqual(['HAND'])+ // The sticky tool is placed hidden, as the default layout keeps it.+ expect(result.hidden).toEqual(['HAND', 'STICKY'])})test('never hides Move', () => {@@ -43,7 +46,13 @@ describe('normalizeToolbarLayout', () => {test('keeps commands out of flyouts', () => {const result = layout([['SELECT', 'insert-icon', 'HAND'], ['COMMENT']])- expect(result.groups.slice(-4)).toEqual([['TEXT'], ['insert-icon'], ['HAND'], ['COMMENT']])+ expect(result.groups.slice(-5)).toEqual([+ ['TEXT'],+ ['STICKY'],+ ['insert-icon'],+ ['HAND'],+ ['COMMENT']+ ])})test('puts a tool the stored layout lacks into its default flyout', () => {@@ -56,6 +65,7 @@ describe('normalizeToolbarLayout', () => {const stored: ToolbarEntry[][] = [['TEXT'], ['SELECT'], SHAPES, ['HAND']]expect(layout(stored).groups).toEqual([['TEXT'],+ ['STICKY'],['SELECT'],['FRAME', 'SECTION'],SHAPES,@@ -67,6 +77,16 @@ describe('normalizeToolbarLayout', () => {})})+describe('tools hidden by default', () => {+ test('a layout stored before the sticky tool gets it hidden, and a shown one stays shown', () => {+ const before = DEFAULT_TOOLBAR_LAYOUT.groups.map((group) =>+ group.filter((entry) => entry !== 'STICKY')+ )+ expect(layout(before).hidden).toEqual(['STICKY'])+ expect(layout(DEFAULT_TOOLBAR_LAYOUT.groups, []).hidden).toEqual([])+ })+})+describe('toolbarItems', () => {test('makes a button of a single shown tool and a flyout keyed by the first shown member', () => {const items = toolbarItems(diff --git a/tests/e2e/canvas/sticky-visual.spec.ts b/tests/e2e/canvas/sticky-visual.spec.tsnew file mode 100644index 000000000..f5ec93b5e--- /dev/null+++ b/tests/e2e/canvas/sticky-visual.spec.ts@@ -0,0 +1,22 @@+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'+import { stickyDriver } from '#tests/helpers/canvas/sticky-driver'++const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')+const sticky = stickyDriver(() => editor.page)++test('sticky notes draw their colour, shadows, body, author, and the empty placeholder', async () => {+ await sticky.add([+ { x: 160, y: 160, author: 'Ada Lovelace' },+ { x: 440, y: 160, text: 'Ship sticky notes\nwith connectors next', author: 'Ada Lovelace' },+ {+ x: 720,+ y: 160,+ text: 'No author here',+ color: { r: 1, g: 226 / 255, b: 153 / 255, a: 1 },+ authorVisible: false+ }+ ])+ await editor.canvas.waitForRender()+ editor.canvas.assertNoErrors()+ expect(await editor.canvas.screenshotCanvasRegion()).toMatchSnapshot('sticky-notes.png')+})diff --git a/tests/e2e/canvas/sticky-visual.spec.ts-snapshots/sticky-notes-openpencil-darwin.png b/tests/e2e/canvas/sticky-visual.spec.ts-snapshots/sticky-notes-openpencil-darwin.pngnew file mode 100644index 000000000..5a818f8acBinary files /dev/null and b/tests/e2e/canvas/sticky-visual.spec.ts-snapshots/sticky-notes-openpencil-darwin.png differdiff --git a/tests/e2e/tools/sticky.spec.ts b/tests/e2e/tools/sticky.spec.tsnew file mode 100644index 000000000..b40ac78a2--- /dev/null+++ b/tests/e2e/tools/sticky.spec.ts@@ -0,0 +1,108 @@+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'+import { stickyDriver } from '#tests/helpers/canvas/sticky-driver'+import { toolbarToolTestId } from '#tests/helpers/test-ids'++const editor = useEditorSetupWithClear()+const sticky = stickyDriver(() => editor.page)++const YELLOW = { r: 1, g: 226 / 255, b: 153 / 255, a: 1 }++test.beforeEach(async () => {+ await editor.page.keyboard.press('Escape')+ await sticky.showOrigin()+})++/** The page's last note, which each test places or sets up itself. */+async function lastNote() {+ const note = (await sticky.notes()).at(-1)+ if (!note) throw new Error('Missing sticky note')+ return note+}++async function clickNote(x: number, y: number) {+ const point = sticky.point(x, y)+ await editor.canvas.click(point.x, point.y)+ await editor.canvas.waitForRender()+}++test('the toolbar keeps the sticky tool hidden, and S does not pick it', async () => {+ await expect(editor.page.getByTestId(toolbarToolTestId('STICKY'))).toHaveCount(0)+ await editor.page.keyboard.press('s')+ expect((await sticky.focus()).tool).toBe('SELECT')+})++test('the sticky tool places a note centred on the click to type into', async () => {+ await sticky.showTool()+ await sticky.pickTool()+ await clickNote(300, 200)+ const placed = await lastNote()+ expect(placed).toMatchObject({ x: 180, y: 80, width: 240, height: 240, body: { text: '' } })+ const focus = await sticky.focus()+ expect(focus.selected).toEqual([placed.id])+ expect(focus.editing).not.toBeNull()++ await editor.page.keyboard.type('Hello sticky')+ await editor.page.keyboard.press('Escape')+ await editor.canvas.waitForRender()+ expect(await lastNote()).toMatchObject({ name: 'Hello sticky', body: { text: 'Hello sticky' } })+ expect(await sticky.focus()).toMatchObject({+ tool: 'SELECT',+ selected: [placed.id],+ editing: null+ })+})++test('the Sticky note section recolours a note, sizes its text, and hides its author', async () => {+ await sticky.add([{ x: 300, y: 200, text: 'Panel', author: 'Ada' }])+ await clickNote(300, 200)+ const section = editor.page.getByRole('region', { name: 'Sticky note' })++ await section.getByRole('radio', { name: 'Yellow' }).click()+ await expect.poll(async () => (await lastNote()).fill).toBe('#ffe299')++ await section.getByRole('combobox', { name: 'Text size' }).click()+ await editor.page.getByRole('option', { name: 'Large', exact: true }).click()+ await expect.poll(async () => (await lastNote()).body.fontSize).toBe(40)++ await section.getByRole('switch', { name: 'Show author' }).click()+ await expect.poll(async () => (await lastNote()).author.visible).toBe(false)+})++test('the sticky tool places notes in the colour picked last', async () => {+ await sticky.add([{ x: 150, y: 150, text: 'First' }])+ await clickNote(150, 150)+ await editor.page+ .getByRole('region', { name: 'Sticky note' })+ .getByRole('radio', { name: 'Yellow' })+ .click()+ await sticky.showTool()+ await sticky.pickTool()+ await clickNote(600, 150)+ expect((await lastNote()).fill).toBe('#ffe299')+})++test('double-clicking a note edits its body with all of it selected', async () => {+ await sticky.add([{ x: 300, y: 200, text: 'Draft', color: YELLOW }])+ const point = sticky.point(300, 200)+ await editor.canvas.dblclick(point.x, point.y)+ await editor.canvas.waitForRender()+ expect((await sticky.focus()).editing).not.toBeNull()++ await editor.page.keyboard.type('Replaced')+ await editor.page.keyboard.press('Escape')+ await editor.canvas.waitForRender()+ const edited = await lastNote()+ expect(edited).toMatchObject({ body: { text: 'Replaced' }, name: 'Replaced' })+ expect((await sticky.focus()).selected).toEqual([edited.id])+})++test("dragging a note's side makes it wide, and back square, as in FigJam", async () => {+ await sticky.add([{ x: 300, y: 200, text: 'Wide' }])+ await clickNote(300, 200)+ // The note spans 180 to 420 across, centred on 200 down.+ const edge = sticky.point(420, 200)+ await editor.canvas.drag(edge.x, edge.y, edge.x + 150, edge.y)+ await expect.poll(async () => (await lastNote()).width).toBe(416)+ await editor.canvas.drag(edge.x + 176, edge.y, edge.x - 20, edge.y)+ await expect.poll(async () => (await lastNote()).width).toBe(240)+})diff --git a/tests/engine/text/edit-undo.test.ts b/tests/engine/text/edit-undo.test.tsindex 8fcc22165..200e225e7 100644--- a/tests/engine/text/edit-undo.test.ts+++ b/tests/engine/text/edit-undo.test.ts@@ -40,6 +40,7 @@ function setup() {requestRefresh: () => {state.sceneVersion++},+ getUserName: () => '',requestRepaint: () => {state.renderVersion++},diff --git a/tests/helpers/canvas/sticky-driver.ts b/tests/helpers/canvas/sticky-driver.tsnew file mode 100644index 000000000..c7cbc17b3--- /dev/null+++ b/tests/helpers/canvas/sticky-driver.ts@@ -0,0 +1,139 @@+import { expect, type Page } from '@playwright/test'++import type { Color } from '@open-pencil/scene-graph/primitives'++import { toolbarToolTestId } from '#tests/helpers/test-ids'++/** The canvas point the page's origin is shown at, at 100%. */+const ORIGIN = 100++export interface StickyNoteState {+ id: string+ name: string+ x: number+ y: number+ width: number+ height: number+ /** The note's colour as `#rrggbb`. */+ fill: string+ body: { text: string; fontSize: number }+ author: { text: string; visible: boolean }+}++export interface StickyFocus {+ tool: string+ selected: string[]+ /** The text being typed into, if any. */+ editing: string | null+}++export interface StickyNoteSetup {+ x: number+ y: number+ text?: string+ author?: string+ color?: Color+ authorVisible?: boolean+}++/** Sticky notes on a page shown at 100% with its origin 100 px into the canvas. */+export function stickyDriver(page: () => Page) {+ return {+ /** Setup: shows the page's origin at a known canvas point. */+ showOrigin() {+ return page().evaluate((origin) => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ store.state.zoom = 1+ store.state.panX = origin+ store.state.panY = origin+ store.requestRender()+ }, ORIGIN)+ },++ /** Setup: notes centred on page points, for specs whose subject is how notes look. */+ add(notes: StickyNoteSetup[]) {+ return page().evaluate((specs) => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ for (const spec of specs) {+ const note = store.createStickyNote(store.state.currentPageId, spec)+ const [body, author] = store.graph.getChildren(note.id)+ store.graph.updateNode(body.id, { text: spec.text ?? '' })+ store.graph.updateNode(author.id, { text: spec.author ?? '' })+ if (spec.color) store.setStickyColor([note.id], spec.color)+ if (spec.authorVisible === false) store.setStickyAuthorVisible([note.id], false)+ store.runLayoutForNode(note.id)+ }+ store.clearSelection()+ }, notes)+ },++ /** Probe: the page's notes, the last placed last. */+ notes(): Promise<StickyNoteState[]> {+ return page().evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const hex = (value = 0) =>+ Math.round(value * 255)+ .toString(16)+ .padStart(2, '0')+ return store.graph+ .getChildren(store.state.currentPageId)+ .filter((node) => node.type === 'STICKY')+ .map((sticky) => {+ const [body, author] = store.graph.getChildren(sticky.id)+ const color = sticky.fills[0]?.color+ return {+ id: sticky.id,+ name: sticky.name,+ x: sticky.x,+ y: sticky.y,+ width: sticky.width,+ height: sticky.height,+ fill: `#${hex(color?.r)}${hex(color?.g)}${hex(color?.b)}`,+ body: { text: body.text, fontSize: body.fontSize },+ author: { text: author.text, visible: author.visible }+ }+ })+ })+ },++ /** Probe: the active tool, the selection, and the text being typed into. */+ focus(): Promise<StickyFocus> {+ return page().evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ return {+ tool: store.state.activeTool,+ selected: [...store.state.selectedIds],+ editing: store.state.editingTextId+ }+ })+ },++ /** Canvas coordinates of a page point, under `showOrigin`. */+ point(x: number, y: number) {+ return { x: ORIGIN + x, y: ORIGIN + y }+ },++ /** Driver: shows the sticky tool from Customize toolbar, where it starts hidden. */+ async showTool() {+ const button = page().getByTestId(toolbarToolTestId('STICKY'))+ if ((await button.count()) > 0) return+ await page().getByTestId('toolbar').click({ button: 'right' })+ await page().getByRole('menuitem', { name: 'Customize toolbar…' }).click()+ await page()+ .getByTestId('settings-toolbar-panel')+ .getByRole('switch', { name: 'Show Sticky note', exact: true })+ .click()+ await page().getByTestId('app-settings-done').click()+ await expect(button).toBeVisible()+ },++ /** Driver: picks the sticky tool from the toolbar. */+ async pickTool() {+ await page().getByTestId(toolbarToolTestId('STICKY')).click()+ }+ }+}diff --git a/tools/checks/i18n/translation-baseline.txt b/tools/checks/i18n/translation-baseline.txtindex bcb66f319..27d21366f 100644--- a/tools/checks/i18n/translation-baseline.txt+++ b/tools/checks/i18n/translation-baseline.txt@@ -50,6 +50,7 @@ de:panels.minHeightShortde:panels.positionde:panels.radialGradientde:panels.radius+de:panels.stickyColorOrangede:panels.textCaseOriginalde:panels.slotsde:panels.behaviourTabs@@ -99,6 +100,7 @@ es:panels.framePresetCategoryFigmaCommunityes:panels.kerninges:panels.localLibrarieses:panels.radialGradient+es:panels.stickyColores:panels.textCaseOriginales:panels.variableses:panels.slots@@ -168,6 +170,8 @@ fr:panels.positionfr:panels.radialGradientfr:panels.rotationfr:panels.saturation+fr:panels.stickyColorOrange+fr:panels.stickyColorVioletfr:panels.variablesfr:panels.slotsfr:panels.slotDescription