Skip to content

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

feat(icons): show icons as icons and tell when one was edited (#995)

Danila Poyarkov551a9e602c12
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b914baeaf..6192e794a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -41,7 +41,7 @@
- Save the open document to cloud storage with **File → Save to storage…**. The tab stays bound to the stored copy, so Save and auto-save write to the bucket; before storage is configured, the command opens its settings. A new Cloud Storage guide covers connecting a bucket, CORS, syncing, and provider notes.
- Add a variant to a standalone component from the header's **Add variant** button, as in Figma (#847): it becomes a component set named after it, whose existing instances and properties carry over, with a `Property 1=Variant2` copy below. A set's variant properties are rows of its **Properties** list, each opening to rename it and add, rename, reorder, or remove its values; removing a value variants still use moves them to another value. Variants that share a combination of values are named in a notice that selects them.
- Create and edit a component's text, boolean, and instance swap properties from the properties panel, as in Figma (#847). A layer in a main component links its text content, visibility, or swapped component to a new or existing property from the Typography and Appearance sections and the instance header, and shows the linked property in place of the value. The component lists its properties, each opening to rename it, change its default, see and unlink the layers it drives, or delete it, and reorders them by dragging. Expose nested instances so their properties show, grouped under the instance's name, on instances of the component. Typing into text a property drives sets the property: its default in the main component, the instance's value in an instance.
-- An icon picker searches Iconify's open-source sets from the toolbar, the Object menu, and the command palette, and inserts the chosen icon at the middle of the view. It starts with the icons already in the file and the ones picked lately, and a set button in the search field narrows it to one set. Placed icons keep their name, so the Design panel's Icon section can swap the glyph or change its color in one undo step, and design JSX and HTML exports write them as icons.
+- An icon picker searches Iconify's open-source sets from the toolbar, the Object menu, and the command palette, and inserts the chosen icon at the middle of the view. It starts with the icons already in the file and the ones picked lately, and a set button in the search field narrows it to one set. Placed icons keep their name, so the Design panel's Icon section can swap the glyph or change its color in one undo step, and design JSX and HTML exports write them as icons. Icons show as icons in the layer tree, are named after the icon, such as `cat`, go without a frame title on the canvas, and scale their paths when resized. An icon whose paths were edited is marked Modified, exports as the paths it draws, can be reset to the original icon, and asks before a swap discards the edit; **Detach icon** in the Icon section, the canvas menu, and the Object menu makes any icon plain artwork.
- Attach images to an AI chat message by dropping them anywhere on the chat panel: an outline over the composer shows where they go, or why they cannot be attached while a reply is running or four images are already attached. SVG images are drawn as PNGs when dropped, pasted, or chosen. Documents dropped on the chat still open in a new tab.
- Share only the selected layers with MCP clients: **Share only the selection** under **Settings → MCP → Local server**, or `OPENPENCIL_MCP_SCOPE=selection` for a server you start yourself, limits clients to `get_selection`, `get_node`, `get_page_tree`, `describe`, and `export_image` on the selected layers and what they hold, enforced by the server for MCP sessions, stdio clients, and `/rpc` alike.
- Set up AI in a few steps with guided setup. On first launch OpenPencil asks what AI should help with and what you already use: a coding agent on this computer (Claude Code, Codex, Gemini CLI, or Pi, in the desktop app), an API account (Anthropic, OpenAI, Google AI, OpenRouter, DeepSeek, Z.ai, or MiniMax), or a local or company server such as Ollama or LM Studio. Sign in to OpenRouter from the browser or the desktop app instead of pasting a key. In the desktop app, setup checks whether the agent, its OpenPencil adapter, OpenPencil's MCP server, and Pi's Harness companion are installed and match the app, installs or updates them with one click through npm, and links a [setup guide](https://openpencil.dev/programmable/coding-agents) or copies a prompt that asks the agent to set itself up. Setup tests each connection, proposes a model for each role that you can change, and keeps anything configured by hand. Skip it to start designing, or run it again from **Settings → AI & agents**.
diff --git a/desktop/generated/menu.json b/desktop/generated/menu.json
index 542ea88d9..da650df4b 100644
--- a/desktop/generated/menu.json
+++ b/desktop/generated/menu.json
@@ -406,6 +406,10 @@
"label": "Detach Instance",
"accelerator": "CmdOrCtrl+Alt+B"
},
+ {
+ "id": "selection.detachIcon",
+ "label": "Detach Icon"
+ },
{
"type": "separator"
},
diff --git a/packages/core/src/canvas/labels/cache.ts b/packages/core/src/canvas/labels/cache.ts
index c2fcfec65..32368dcf4 100644
--- a/packages/core/src/canvas/labels/cache.ts
+++ b/packages/core/src/canvas/labels/cache.ts
@@ -3,6 +3,8 @@ import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import type { RenderOverlays } from '#core/canvas/renderer'
import { createSceneGeometry } from '#core/geometry'
+import { hasFrameTitle } from './layout'
+
export interface CachedSection {
nodeId: string
absX: number
@@ -32,7 +34,6 @@ interface Viewport {
}
const LABEL_TYPES = new Set(['COMPONENT', 'COMPONENT_SET'])
-const FRAME_TITLE_PARENT_TYPES = new Set(['CANVAS', 'SECTION'])
const COMPONENT_LABEL_PARENT_TYPES = new Set(['CANVAS', 'SECTION', 'COMPONENT_SET'])
function isInViewport(absX: number, absY: number, w: number, h: number, vp: Viewport): boolean {
@@ -204,7 +205,7 @@ export class LabelCache {
this.walkChildren(graph, childId, insideSection)
}
} else {
- if (child.type === 'FRAME' && FRAME_TITLE_PARENT_TYPES.has(parentType)) {
+ if (hasFrameTitle(child, parentType)) {
const origin = graph.getAbsolutePosition(childId)
this.frames.push({ nodeId: childId, absX: origin.x, absY: origin.y })
}
diff --git a/packages/core/src/canvas/labels/layout.ts b/packages/core/src/canvas/labels/layout.ts
index 6ed74ddd9..e316b050b 100644
--- a/packages/core/src/canvas/labels/layout.ts
+++ b/packages/core/src/canvas/labels/layout.ts
@@ -1,4 +1,4 @@
-import type { SceneNode } from '@open-pencil/scene-graph'
+import { readIcon, type SceneNode } from '@open-pencil/scene-graph'
import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'
import {
@@ -28,8 +28,18 @@ export interface LabelLayout {
maxTextWidth: number
}
-export function hasFrameTitle(node: SceneNode, parent?: SceneNode | null): boolean {
- return node.type === 'FRAME' && (!parent || parent.type === 'CANVAS' || parent.type === 'SECTION')
+const FRAME_TITLE_PARENT_TYPES = new Set(['CANVAS', 'SECTION'])
+
+/**
+ * Whether a frame shows its name above it: a frame on the page or in a section, as Figma titles
+ * them. An icon is a glyph rather than an artboard, so it goes untitled like a vector.
+ */
+export function hasFrameTitle(node: SceneNode, parentType: string | undefined): boolean {
+ return (
+ node.type === 'FRAME' &&
+ (parentType === undefined || FRAME_TITLE_PARENT_TYPES.has(parentType)) &&
+ !readIcon(node)
+ )
}
function sectionLabelLayout(
diff --git a/packages/core/src/editor/icons.ts b/packages/core/src/editor/icons.ts
index 36010891e..1b901c74e 100644
--- a/packages/core/src/editor/icons.ts
+++ b/packages/core/src/editor/icons.ts
@@ -4,7 +4,7 @@ import type { Color } from '@open-pencil/scene-graph/primitives'
import { restoreSubtree, snapshotSubtree } from '#core/editor/clipboard/subtree-history'
import type { EditorContext } from '#core/editor/types'
-import { placeIcon, recolorIcon, swapIcon } from '#core/icons/render'
+import { detachIcon, placeIcon, recolorIcon, swapIcon } from '#core/icons/render'
import type { IconData } from '#core/icons/types'
/** The size a picked icon is placed at, as Iconify sets draw them. */
@@ -85,15 +85,34 @@ export function createIconActions(ctx: EditorContext) {
return frame.id
}
- /** Draws the icon `name` in the icon `frameId`, keeping its size, position, and color. */
- async function swapIconGlyph(frameId: string, name: string) {
+ /** Draws the icon `name` fresh in the icon `frameId`, as one step called `label`. */
+ async function drawIcon(label: string, frameId: string, name: string) {
const graph = ctx.graph
const frame = graph.getNode(frameId)
if (!frame || !readIcon(frame)) return
const icon = await fetchIcon(name, Math.min(frame.width, frame.height))
// The document or the frame may have been replaced while the icon loaded.
if (ctx.graph !== graph || graph.getNode(frameId) !== frame) return
- changeIcon('Swap icon', frameId, () => swapIcon(graph, frameId, icon))
+ changeIcon(label, frameId, () => swapIcon(graph, frameId, icon))
+ }
+
+ /** Draws the icon `name` in the icon `frameId`, keeping its size, position, and color. */
+ async function swapIconGlyph(frameId: string, name: string) {
+ await drawIcon('Swap icon', frameId, name)
+ }
+
+ /** Draws the icon `frameId` was placed as afresh, undoing edits to its paths. */
+ async function resetIcon(frameId: string) {
+ const frame = ctx.graph.getNode(frameId)
+ const icon = frame && readIcon(frame)
+ if (icon) await drawIcon('Reset icon', frameId, icon.name)
+ }
+
+ /** Makes the icon `frameId` plain artwork that keeps its paths; see `detachIcon`. */
+ function detachIconFrame(frameId: string) {
+ const frame = ctx.graph.getNode(frameId)
+ if (!frame || !readIcon(frame)) return
+ changeIcon('Detach icon', frameId, () => detachIcon(ctx.graph, frameId))
}
/**
@@ -119,6 +138,8 @@ export function createIconActions(ctx: EditorContext) {
iconProvider: ctx.icons,
insertIcon,
swapIconGlyph,
+ resetIcon,
+ detachIcon: detachIconFrame,
setIconColor
}
}
diff --git a/packages/core/src/icons/index.ts b/packages/core/src/icons/index.ts
index a63d949ad..8b039460c 100644
--- a/packages/core/src/icons/index.ts
+++ b/packages/core/src/icons/index.ts
@@ -6,7 +6,14 @@ export {
type IconProvider,
type IconSearchOptions
} from './provider'
-export { iconColor, placeIcon, recolorIcon, swapIcon, type PlaceIconOptions } from './render'
+export {
+ detachIcon,
+ iconColor,
+ placeIcon,
+ recolorIcon,
+ swapIcon,
+ type PlaceIconOptions
+} from './render'
export type { IconCollection, IconData, IconPath, IconSearchResult } from './types'
/** The Iconify icons hosts use unless they pass a provider of their own. */
diff --git a/packages/core/src/icons/render.ts b/packages/core/src/icons/render.ts
index a4047367f..67372ec38 100644
--- a/packages/core/src/icons/render.ts
+++ b/packages/core/src/icons/render.ts
@@ -1,4 +1,7 @@
import {
+ iconGlyph,
+ iconLayerName,
+ isPlacedIconName,
readIcon,
readIconTint,
withIcon,
@@ -10,6 +13,11 @@ import {
import { parseColor } from '@open-pencil/scene-graph/color'
import { BLACK } from '@open-pencil/scene-graph/constants'
import type { Color } from '@open-pencil/scene-graph/primitives'
+import {
+ createResizeSnapshot,
+ scaledChildRect,
+ scaledGeometryChanges
+} from '@open-pencil/scene-graph/resize'
import { createPathStroke, pathStrokeLineStyle } from '#core/icons/path-style'
@@ -50,6 +58,9 @@ function addPath(graph: SceneGraph, frameId: string, path: IconPath, size: numbe
width: size,
height: size,
vectorNetwork: path.vectorNetwork,
+ // Resizing the icon resizes its glyph, as the frame is the icon.
+ horizontalConstraint: 'SCALE',
+ verticalConstraint: 'SCALE',
fills: path.fill ? solid(paint(path.fill, 'fill')) : []
})
if (path.stroke) {
@@ -79,17 +90,38 @@ export function placeIcon(
): SceneNode {
const name = `${icon.prefix}:${icon.name}`
const frame = graph.createNode('FRAME', parentId, {
- name: identity ? `Icon / ${name}` : icon.name,
+ name: identity ? iconLayerName(name) : icon.name,
width: size,
height: size,
fills: [],
...overrides
})
- if (identity) graph.updateNode(frame.id, { pluginData: withIcon(frame, { name }) })
for (const path of icon.paths) addPath(graph, frame.id, path, size, color)
+ if (identity) recordIcon(graph, frame.id, name)
return graph.getNode(frame.id) ?? frame
}
+/** Writes the icon `name` on its frame with a fingerprint of the paths it draws now. */
+function recordIcon(graph: SceneGraph, frameId: string, name: string): void {
+ const frame = graph.getNode(frameId)
+ if (!frame) return
+ const glyph = iconGlyph(graph, frame)
+ graph.updateNode(frameId, { pluginData: withIcon(frame, { name, glyph }) })
+}
+
+/**
+ * Makes an icon plain artwork: its frame forgets the icon and its paths their tint, so it is
+ * no longer swapped, recolored as one, or exported as `<Icon>`. The paths stay as drawn.
+ */
+export function detachIcon(graph: SceneGraph, frameId: string): void {
+ const frame = graph.getNode(frameId)
+ if (!frame || !readIcon(frame)) return
+ graph.updateNode(frameId, { pluginData: withIcon(frame, null) })
+ for (const path of graph.getChildren(frameId))
+ if (readIconTint(path).length > 0)
+ graph.updateNode(path.id, { pluginData: withIconTint(path, []) })
+}
+
/** The color an icon's tinted paths have, or null when none takes the icon's color. */
export function iconColor(graph: SceneGraph, frame: SceneNode): Color | null {
for (const path of graph.getChildren(frame.id)) {
@@ -113,8 +145,8 @@ export function recolorIcon(graph: SceneGraph, frameId: string, color: Color): v
/**
* Draws another icon in an icon's frame, keeping its position and color, so the swap reads as
- * a change of glyph. `icon` is drawn at the size it was built for, which should be the frame's.
- * Does nothing to a frame that is not an icon.
+ * a change of glyph. `icon` is built square, at the frame's shorter side, and stretched to the
+ * frame. Does nothing to a frame that is not an icon.
*/
export function swapIcon(graph: SceneGraph, frameId: string, icon: IconData): void {
const frame = graph.getNode(frameId)
@@ -124,9 +156,35 @@ export function swapIcon(graph: SceneGraph, frameId: string, icon: IconData): vo
const size = icon.width
for (const child of graph.getChildren(frameId)) graph.deleteNode(child.id)
const name = `${icon.prefix}:${icon.name}`
+ const previous = readIcon(frame)
graph.updateNode(frameId, {
- name: frame.name.startsWith('Icon / ') ? `Icon / ${name}` : frame.name,
- pluginData: withIcon(frame, { name })
+ // A layer still named after its icon takes the new icon's name; a name someone gave stays.
+ name: previous && isPlacedIconName(frame.name, previous.name) ? iconLayerName(name) : frame.name
})
for (const path of icon.paths) addPath(graph, frameId, path, size, color)
+ fitPaths(graph, frameId, size)
+ recordIcon(graph, frameId, name)
+}
+
+/**
+ * Stretches paths drawn in a `size` square to their frame, as a resize would, so an icon that
+ * was resized unevenly is swapped or reset at the shape it has rather than as a square.
+ */
+function fitPaths(graph: SceneGraph, frameId: string, size: number): void {
+ const frame = graph.getNode(frameId)
+ if (!frame || (frame.width === size && frame.height === size)) return
+ const square = { width: size, height: size }
+ for (const path of graph.getChildren(frameId)) {
+ const rect = scaledChildRect(path, square, frame)
+ graph.updateNode(path.id, {
+ ...rect,
+ ...scaledGeometryChanges(
+ createResizeSnapshot(path),
+ path.width,
+ path.height,
+ rect.width,
+ rect.height
+ )
+ })
+ }
}
diff --git a/packages/core/src/io/formats/html/vectors.ts b/packages/core/src/io/formats/html/vectors.ts
index fd8e911fd..ababbc3fc 100644
--- a/packages/core/src/io/formats/html/vectors.ts
+++ b/packages/core/src/io/formats/html/vectors.ts
@@ -1,5 +1,5 @@
import type { DesignElement, DesignNode, VectorElementRenderer } from '@open-pencil/dom-css/export'
-import { readIcon, readIconTint } from '@open-pencil/scene-graph'
+import { isIconModified, readIcon, readIconTint } from '@open-pencil/scene-graph'
import { colorToHex } from '@open-pencil/scene-graph/color'
import { iconColor } from '#core/icons/render'
@@ -28,9 +28,10 @@ function idPart(id: string): string {
/**
* Vector layers and icons in HTML exports as inline SVG from the SVG export, so paths,
- * gradients, and shadows draw as they do there. An icon is one SVG named by `data-icon`, whose
- * tinted paths take `currentColor`, so a page recolors it with CSS `color`. Def ids start with
- * the layer's id, so several SVGs on one page never pick up each other's gradients or filters.
+ * gradients, and shadows draw as they do there. An icon is one SVG whose tinted paths take
+ * `currentColor`, so a page recolors it with CSS `color`, named by `data-icon` unless its paths
+ * were edited. Def ids start with the layer's id, so several SVGs on one page never pick up each
+ * other's gradients or filters.
*/
export const vectorElement: VectorElementRenderer = (graph, node) => {
const idPrefix = `${idPart(node.id)}-`
@@ -45,7 +46,11 @@ export const vectorElement: VectorElementRenderer = (graph, node) => {
const color = icon ? iconColor(graph, node) : null
return {
...element,
- attrs: icon ? { ...element.attrs, 'data-icon': icon.name } : element.attrs,
+ // An icon whose paths were edited no longer draws the named icon, so it goes unnamed.
+ attrs:
+ icon && !isIconModified(graph, node)
+ ? { ...element.attrs, 'data-icon': icon.name }
+ : element.attrs,
// Strokes and shadows can reach past the layer's box, which an inline SVG would clip.
inlineStyle: { overflow: 'visible', ...(color ? { color: colorToHex(color) } : {}) }
} satisfies DesignElement
diff --git a/packages/core/tests/canvas/labels/cache.test.ts b/packages/core/tests/canvas/labels/cache.test.ts
new file mode 100644
index 000000000..6f0f357d3
--- /dev/null
+++ b/packages/core/tests/canvas/labels/cache.test.ts
@@ -0,0 +1,18 @@
+import { expect, test } from 'bun:test'
+
+import { SceneGraph, withIcon } from '@open-pencil/scene-graph'
+
+import { LabelCache } from '#core/canvas/labels/cache'
+
+test('icons on the page go untitled, while frames beside them keep their names', () => {
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ const frame = graph.createNode('FRAME', pageId, { name: 'Card', width: 200, height: 100 })
+ const icon = graph.createNode('FRAME', pageId, { name: 'cat', x: 300, width: 24, height: 24 })
+ graph.updateNode(icon.id, { pluginData: withIcon(icon, { name: 'mdi:cat' }) })
+
+ const cache = new LabelCache()
+ cache.update(graph, pageId, 1)
+
+ expect(cache.getAllFrames().map(({ nodeId }) => nodeId)).toEqual([frame.id])
+})
diff --git a/packages/core/tests/editor/icons.test.ts b/packages/core/tests/editor/icons.test.ts
index 557b9bad3..02ad5662b 100644
--- a/packages/core/tests/editor/icons.test.ts
+++ b/packages/core/tests/editor/icons.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, test } from 'bun:test'
import { createEditor } from '@open-pencil/core/editor'
import { parseIconName, type IconProvider } from '@open-pencil/core/icons'
-import { readIcon, SceneGraph } from '@open-pencil/scene-graph'
+import { isIconModified, readIcon, SceneGraph } from '@open-pencil/scene-graph'
import type { Color } from '@open-pencil/scene-graph/primitives'
import { buildIconData } from '#core/icons/svg'
@@ -61,7 +61,7 @@ describe('icon commands', () => {
expect(frame).toMatchObject({ x: 188, y: 163, width: 24, height: 24 })
expect(frame.parentId).toBe(editor.state.currentPageId)
- expect(readIcon(frame)).toEqual({ name: 'test:square' })
+ expect(readIcon(frame)).toMatchObject({ name: 'test:square' })
expect(editor.state.selectedIds).toEqual(new Set([id]))
editor.undo.undo()
@@ -69,7 +69,7 @@ describe('icon commands', () => {
expect(editor.state.selectedIds).toEqual(new Set())
editor.undo.redo()
- expect(readIcon(getNodeOrThrow(editor.graph, id))).toEqual({ name: 'test:square' })
+ expect(readIcon(getNodeOrThrow(editor.graph, id))).toMatchObject({ name: 'test:square' })
expect(editor.graph.getChildren(id)).toHaveLength(1)
})
@@ -95,16 +95,16 @@ describe('icon commands', () => {
await editor.swapIconGlyph(id, 'test:lines')
const frame = getNodeOrThrow(editor.graph, id)
- expect(readIcon(frame)).toEqual({ name: 'test:lines' })
- expect(frame).toMatchObject({ x: 188, y: 163, name: 'Icon / test:lines' })
+ expect(readIcon(frame)).toMatchObject({ name: 'test:lines' })
+ expect(frame).toMatchObject({ x: 188, y: 163, name: 'lines' })
expect(editor.graph.getChildren(id)[0]?.strokes[0]?.color).toEqual(RED)
editor.undo.undo()
- expect(readIcon(getNodeOrThrow(editor.graph, id))).toEqual({ name: 'test:square' })
+ expect(readIcon(getNodeOrThrow(editor.graph, id))).toMatchObject({ name: 'test:square' })
expect(editor.graph.getChildren(id).map((path) => path.id)).toEqual(before)
editor.undo.redo()
- expect(readIcon(getNodeOrThrow(editor.graph, id))).toEqual({ name: 'test:lines' })
+ expect(readIcon(getNodeOrThrow(editor.graph, id))).toMatchObject({ name: 'test:lines' })
})
test('swap keeps the icon at its place among its siblings', async () => {
@@ -154,3 +154,47 @@ describe('icon commands across a document change', () => {
expect([...replacement.getAllNodes()].some((node) => readIcon(node))).toBe(false)
})
})
+
+describe('icon layer names', () => {
+ test('a swap renames a layer named after its icon, old style or new, but keeps a given name', async () => {
+ const editor = setup()
+ const named = await insert(editor, 'test:square')
+ const oldStyle = await insert(editor, 'test:square')
+ const renamed = await insert(editor, 'test:square')
+ editor.graph.updateNode(oldStyle, { name: 'Icon / test:square' })
+ editor.graph.updateNode(renamed, { name: 'Close button' })
+
+ for (const id of [named, oldStyle, renamed]) await editor.swapIconGlyph(id, 'test:lines')
+
+ expect(getNodeOrThrow(editor.graph, named).name).toBe('lines')
+ expect(getNodeOrThrow(editor.graph, oldStyle).name).toBe('lines')
+ expect(getNodeOrThrow(editor.graph, renamed).name).toBe('Close button')
+ })
+})
+
+describe('editing an icon', () => {
+ test('reset draws the placed glyph again, in one undo step', async () => {
+ const editor = setup()
+ const id = await insert(editor, 'test:square', RED)
+ editor.graph.createNode('RECTANGLE', id, { width: 4, height: 4 })
+ expect(isIconModified(editor.graph, getNodeOrThrow(editor.graph, id))).toBe(true)
+
+ await editor.resetIcon(id)
+ expect(isIconModified(editor.graph, getNodeOrThrow(editor.graph, id))).toBe(false)
+ expect(editor.graph.getChildren(id)).toHaveLength(1)
+ expect(editor.graph.getChildren(id)[0]?.fills[0]?.color).toEqual(RED)
+
+ editor.undo.undo()
+ expect(editor.graph.getChildren(id)).toHaveLength(2)
+ })
+
+ test('detach makes the icon artwork, in one undo step', async () => {
+ const editor = setup()
+ const id = await insert(editor, 'test:square')
+ editor.detachIcon(id)
+ expect(readIcon(getNodeOrThrow(editor.graph, id))).toBeNull()
+
+ editor.undo.undo()
+ expect(readIcon(getNodeOrThrow(editor.graph, id))).toMatchObject({ name: 'test:square' })
+ })
+})
diff --git a/packages/core/tests/icons/glyph.test.ts b/packages/core/tests/icons/glyph.test.ts
new file mode 100644
index 000000000..8d3d16054
--- /dev/null
+++ b/packages/core/tests/icons/glyph.test.ts
@@ -0,0 +1,131 @@
+import { describe, expect, test } from 'bun:test'
+
+import { isIconModified, readIcon, readIconTint, SceneGraph, withIcon } from '@open-pencil/scene-graph'
+import { parseColor } from '@open-pencil/scene-graph/color'
+import {
+ collectResizeDescendants,
+ computeConstrainedResizeChanges
+} from '@open-pencil/scene-graph/resize'
+
+import { detachIcon, placeIcon, recolorIcon, swapIcon } from '#core/icons/render'
+import { buildIconData } from '#core/icons/svg'
+
+const BLACK = parseColor('#000000')
+const OUTLINE = '<path fill="none" stroke="currentColor" stroke-width="2" d="M4 4h16v16H4z"/>'
+const LOGO = '<path fill="#e11d48" d="M2 2h20v20H2z"/><path fill="currentColor" d="M8 8h8v8H8z"/>'
+
+function placed(body: string) {
+ const graph = new SceneGraph()
+ const icon = buildIconData({ body }, 'test', 'icon', 24, 24, 24)
+ const frame = placeIcon(graph, graph.getPages()[0].id, icon, { size: 24, color: BLACK })
+ const modified = () => isIconModified(graph, graph.getNode(frame.id) ?? frame)
+ return { graph, frame, modified }
+}
+
+/** Resizes the icon as the canvas handles do, its paths following their constraints. */
+function resize(graph: SceneGraph, id: string, width: number, height: number) {
+ const node = graph.getNode(id)
+ if (!node) throw new Error('Expected the icon')
+ // Nodes change in place, so the size before is copied out.
+ const before = { width: node.width, height: node.height }
+ const originals = collectResizeDescendants(graph, id)
+ graph.updateNode(id, { width, height })
+ if (!originals) return
+ const changes = computeConstrainedResizeChanges(graph, id, before, { width, height }, originals)
+ for (const [childId, change] of changes) graph.updateNode(childId, change)
+}
+
+describe('icon glyphs', () => {
+ test('a placed icon is as placed, and stays so when recolored or resized, unevenly too', () => {
+ const { graph, frame, modified } = placed(OUTLINE)
+ expect(readIcon(graph.getNode(frame.id) ?? frame)?.glyph).toMatch(/^[0-9a-f]{8}$/)
+ expect(modified()).toBe(false)
+
+ recolorIcon(graph, frame.id, parseColor('#4f46e5'))
+ resize(graph, frame.id, 37, 37)
+ expect(modified()).toBe(false)
+ resize(graph, frame.id, 40, 20)
+ expect(modified()).toBe(false)
+ })
+
+ test('resizing scales the glyph with its frame', () => {
+ const { graph, frame } = placed(OUTLINE)
+ resize(graph, frame.id, 48, 48)
+ expect(graph.getChildren(frame.id)[0]).toMatchObject({ width: 48, height: 48 })
+ })
+
+ test('moving a point, adding a path, or changing a color of its own is an edit', () => {
+ const point = placed(OUTLINE)
+ const path = point.graph.getChildren(point.frame.id)[0]
+ const network = path?.vectorNetwork
+ if (!path || !network) throw new Error('Expected a path')
+ point.graph.updateNode(path.id, {
+ vectorNetwork: {
+ ...network,
+ vertices: network.vertices.map((vertex, index) =>
+ index === 0 ? { ...vertex, x: vertex.x + 3 } : vertex
+ )
+ }
+ })
+ expect(point.modified()).toBe(true)
+
+ const added = placed(OUTLINE)
+ added.graph.createNode('RECTANGLE', added.frame.id, { width: 4, height: 4 })
+ expect(added.modified()).toBe(true)
+
+ const logo = placed(LOGO)
+ const own = logo.graph.getChildren(logo.frame.id).find((child) => readIconTint(child).length === 0)
+ if (!own) throw new Error('Expected a path with its own color')
+ logo.graph.updateNode(own.id, {
+ fills: own.fills.map((fill) => ({ ...fill, color: parseColor('#16a34a') }))
+ })
+ expect(logo.modified()).toBe(true)
+ })
+
+ test('a swap draws a fresh glyph, so an edited icon is as placed again', () => {
+ const { graph, frame, modified } = placed(OUTLINE)
+ graph.createNode('RECTANGLE', frame.id, { width: 4, height: 4 })
+ swapIcon(graph, frame.id, buildIconData({ body: OUTLINE }, 'test', 'other', 24, 24, 24))
+ expect(modified()).toBe(false)
+ })
+
+ test('rotating or fading a path is an edit', () => {
+ for (const change of [{ rotation: 15 }, { opacity: 0.5 }]) {
+ const { graph, frame, modified } = placed(OUTLINE)
+ const path = graph.getChildren(frame.id)[0]
+ if (!path) throw new Error('Expected a path')
+ graph.updateNode(path.id, change)
+ expect(modified()).toBe(true)
+ }
+ })
+
+ test('a swap into an unevenly resized icon stretches the glyph to it', () => {
+ const { graph, frame, modified } = placed(OUTLINE)
+ resize(graph, frame.id, 40, 20)
+ swapIcon(graph, frame.id, buildIconData({ body: OUTLINE }, 'test', 'other', 24, 24, 20))
+
+ expect(graph.getChildren(frame.id)[0]).toMatchObject({ width: 40, height: 20 })
+ expect(modified()).toBe(false)
+ })
+
+ test('an icon placed before glyphs were recorded counts as unedited', () => {
+ const { graph, frame, modified } = placed(OUTLINE)
+ const node = graph.getNode(frame.id) ?? frame
+ const icon = readIcon(node)
+ if (!icon) throw new Error('Expected an icon')
+ graph.updateNode(frame.id, { pluginData: withIcon(node, { name: icon.name }) })
+ graph.createNode('RECTANGLE', frame.id, { width: 4, height: 4 })
+ expect(modified()).toBe(false)
+ })
+
+ test('detaching leaves the paths as drawn, with no icon or tint left', () => {
+ const { graph, frame } = placed(OUTLINE)
+ const before = graph.getChildren(frame.id).map((path) => path.vectorNetwork)
+ detachIcon(graph, frame.id)
+
+ expect(readIcon(graph.getNode(frame.id) ?? frame)).toBeNull()
+ const paths = graph.getChildren(frame.id)
+ expect(paths.map((path) => readIconTint(path))).toEqual([[]])
+ expect(paths.map((path) => path.vectorNetwork)).toEqual(before)
+ })
+})
diff --git a/packages/core/tests/icons/render.test.ts b/packages/core/tests/icons/render.test.ts
index d69b27e01..0253e0f37 100644
--- a/packages/core/tests/icons/render.test.ts
+++ b/packages/core/tests/icons/render.test.ts
@@ -97,12 +97,12 @@ describe('icon identity', () => {
test('records the icon and which paints its color sets, and survives a .fig round trip', async () => {
const graph = new SceneGraph()
const { frame, vectors } = insertIcon(graph, BODY)
- expect(readIcon(frame)).toEqual({ name: 'test:icon' })
+ expect(readIcon(frame)).toMatchObject({ name: 'test:icon' })
expect(vectors.map(readIconTint)).toEqual([['fill'], []])
const reopened = await parseFigFile((await exportFigFile(graph)).buffer as ArrayBuffer)
const icon = [...reopened.nodes.values()].find((node) => readIcon(node))
- expect(icon && readIcon(icon)).toEqual({ name: 'test:icon' })
+ expect(icon && readIcon(icon)).toMatchObject({ name: 'test:icon' })
})
test("recolors only the paths drawn in the icon's color", () => {
@@ -125,7 +125,7 @@ describe('icon identity', () => {
swapIcon(graph, frame.id, other)
const swapped = expectDefined(graph.getNode(frame.id), 'swapped icon')
- expect(readIcon(swapped)).toEqual({ name: 'test:square' })
+ expect(readIcon(swapped)).toMatchObject({ name: 'test:square' })
expect([swapped.width, swapped.height]).toEqual([32, 32])
const paths = graph.getChildren(frame.id)
expect(paths).toHaveLength(1)
diff --git a/packages/core/tests/io/formats/html/vectors.test.ts b/packages/core/tests/io/formats/html/vectors.test.ts
index 24773123e..a698123a6 100644
--- a/packages/core/tests/io/formats/html/vectors.test.ts
+++ b/packages/core/tests/io/formats/html/vectors.test.ts
@@ -83,4 +83,23 @@ describe('icons in HTML export', () => {
expect(html).toContain('fill="currentColor"')
expect(html).toContain('fill="#FF0000"')
})
+
+ test('an icon whose paths were edited draws its paths, no longer named as the icon', async () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const icon = buildIconData({ body: '<path fill="currentColor" d="M0 0h24v24H0z"/>' }, 'test', 'icon', 24, 24, 24)
+ const frame = placeIcon(graph, page, icon, { size: 24, color: parseColor('#000000') })
+ graph.createNode('RECTANGLE', frame.id, {
+ width: 4,
+ height: 4,
+ fills: [{ type: 'SOLID', color: parseColor('#16a34a'), opacity: 1, visible: true }]
+ })
+
+ const { html } = await renderNodesToHTML(graph, [frame.id])
+ expect(html).not.toContain('data-icon')
+ expect(html.match(/<svg/g)?.length).toBe(1)
+ // The added layer is drawn with the icon's own path.
+ expect(html).toContain('fill="#16A34A"')
+ expect(html).toContain('fill="currentColor"')
+ })
})
diff --git a/packages/design-jsx/src/export/icons.ts b/packages/design-jsx/src/export/icons.ts
index fccadb0d3..102fa02e8 100644
--- a/packages/design-jsx/src/export/icons.ts
+++ b/packages/design-jsx/src/export/icons.ts
@@ -1,11 +1,15 @@
-import { readIcon, readIconTint, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
+import {
+ isIconModified,
+ isPlacedIconName,
+ readIcon,
+ readIconTint,
+ type SceneGraph,
+ type SceneNode
+} from '@open-pencil/scene-graph'
import { colorToHex } from '@open-pencil/scene-graph/color'
import type { JSXProp } from './props'
-/** The frame name icons are placed with, which the export leaves to `<Icon>` to give again. */
-const placedName = (name: string) => `Icon / ${name}`
-
/** The color an icon's tinted paths have, as `<Icon color>` takes it. */
function tintColor(graph: SceneGraph, frame: SceneNode): string | null {
for (const path of graph.getChildren(frame.id)) {
@@ -20,16 +24,18 @@ function tintColor(graph: SceneGraph, frame: SceneNode): string | null {
/**
* An icon frame as `<Icon>` props: its name and size, its color when it is not black, and its
- * layer name when someone renamed it. `null` for a layer that is not an icon.
+ * layer name when someone renamed it. `null` for a layer that is not an icon, or no longer draws
+ * one because its paths were edited.
*/
export function iconProps(node: SceneNode, graph: SceneGraph): JSXProp[] | null {
const icon = readIcon(node)
- if (!icon) return null
+ // An icon whose paths were edited exports as the paths it draws, which <Icon> would lose.
+ if (!icon || isIconModified(graph, node)) return null
const color = tintColor(graph, node)
return [
['name', icon.name],
['size', Math.round(Math.min(node.width, node.height))],
...(color && color.toLowerCase() !== '#000000' ? [['color', color] as JSXProp] : []),
- ...(node.name !== placedName(icon.name) ? [['label', node.name] as JSXProp] : [])
+ ...(isPlacedIconName(node.name, icon.name) ? [] : [['label', node.name] as JSXProp])
]
}
diff --git a/packages/design-jsx/tests/export/icons.test.ts b/packages/design-jsx/tests/export/icons.test.ts
index edc1fcc87..f9f0c0c66 100644
--- a/packages/design-jsx/tests/export/icons.test.ts
+++ b/packages/design-jsx/tests/export/icons.test.ts
@@ -2,14 +2,14 @@ import { describe, expect, test } from 'bun:test'
import { sceneNodeToJSX } from '#design-jsx/export/index'
-import { SceneGraph, withIcon, withIconTint } from '@open-pencil/scene-graph'
+import { iconGlyph, SceneGraph, withIcon, withIconTint } from '@open-pencil/scene-graph'
import type { Color } from '@open-pencil/scene-graph/primitives'
/** An icon frame as placing one leaves it: its name on the frame, its tinted path inside. */
function iconFrame(color: Color, name?: string) {
const graph = new SceneGraph()
const frame = graph.createNode('FRAME', graph.getPages()[0].id, {
- name: name ?? 'Icon / lucide:home',
+ name: name ?? 'home',
width: 20,
height: 20
})
@@ -38,4 +38,23 @@ describe('icons in design JSX export', () => {
'<Icon name="lucide:home" size={20} label="Home" />'
)
})
+
+ test('write an icon whose paths were edited as the paths it draws', () => {
+ const { graph, frame } = iconFrame({ r: 0, g: 0, b: 0, a: 1 })
+ const node = graph.getNode(frame.id) ?? frame
+ graph.updateNode(frame.id, {
+ pluginData: withIcon(node, { name: 'lucide:home', glyph: iconGlyph(graph, node) })
+ })
+ graph.createNode('RECTANGLE', frame.id, { name: 'Badge', width: 4, height: 4 })
+ const jsx = sceneNodeToJSX(frame.id, graph)
+ expect(jsx).not.toContain('<Icon')
+ // Both the icon's path and the added badge are written out.
+ expect(jsx).toContain('name="path"')
+ expect(jsx).toContain('name="Badge"')
+ })
+
+ test('leave out the name an icon was placed with, in the old style too', () => {
+ const { graph, frame } = iconFrame({ r: 0, g: 0, b: 0, a: 1 }, 'Icon / lucide:home')
+ expect(sceneNodeToJSX(frame.id, graph)).toBe('<Icon name="lucide:home" size={20} />')
+ })
})
diff --git a/packages/docs/user-guide/icons.md b/packages/docs/user-guide/icons.md
index 9fc942e8e..b07f35fb9 100644
--- a/packages/docs/user-guide/icons.md
+++ b/packages/docs/user-guide/icons.md
@@ -36,7 +36,19 @@ Selecting a placed icon adds an **Icon** section to the Design panel.
Each swap or color change is one undo step; dragging in the color picker undoes as a single change.
-An icon is a frame of vector paths, so its layers, constraints, effects, and the rest of the Design panel work as they do for any frame. Swapping replaces the paths, including any you edited by hand.
+An icon is a frame of vector paths, named after the icon, such as `cat`, and marked with a smiley in the layer tree. Unlike other frames on the page, it has no title on the canvas, and resizing it scales its paths. Its layers, constraints, effects, and the rest of the Design panel work as they do for any frame.
+
+## Editing an Icon's Paths
+
+You can edit an icon's paths like any vector. Once its points, paths, or own colors change, the Icon section says **Modified**:
+
+- The icon exports as the paths it now draws rather than by its name, so the edit is kept.
+- **Reset** (the circular arrow) draws the original icon again, at the same size and color.
+- Swapping asks first, since a swap draws a new icon and discards the edit.
+
+Resizing the icon or changing its color doesn't count as an edit.
+
+**Detach icon**, in the Icon section, the canvas menu, or **Object → Detach Icon**, makes an icon plain artwork: it keeps its paths but is no longer swapped, recolored, or exported as an icon. Like every icon command, it's one undo step.
## Icons in Exports
diff --git a/packages/scene-graph/src/icons/glyph.ts b/packages/scene-graph/src/icons/glyph.ts
new file mode 100644
index 000000000..e4def4fb3
--- /dev/null
+++ b/packages/scene-graph/src/icons/glyph.ts
@@ -0,0 +1,99 @@
+import { omit } from 'es-toolkit'
+
+import type { Fill, SceneNode, Stroke, VectorNetwork } from '../types'
+import { readIcon, readIconTint } from './model'
+
+/** What reading an icon's paths needs of a graph. */
+interface IconGraph {
+ getChildren(id: string): SceneNode[]
+}
+
+/** Digits kept of each proportion, so float noise does not read as an edit. */
+const PRECISION = 1000
+
+const round = (value: number) => Math.round(value * PRECISION) / PRECISION
+
+/**
+ * A path's points in proportion to their own bounds on each axis. Resizing scales vertices by
+ * exact factors, so these proportions survive any resize, while the path boxes around them are
+ * rounded to pixels and are left out.
+ */
+function shape(network: VectorNetwork | null | undefined) {
+ if (!network) return null
+ const xs = network.vertices.map((vertex) => vertex.x)
+ const ys = network.vertices.map((vertex) => vertex.y)
+ const minX = Math.min(...xs)
+ const minY = Math.min(...ys)
+ const sx = 1 / (Math.max(...xs) - minX || 1)
+ const sy = 1 / (Math.max(...ys) - minY || 1)
+ return {
+ vertices: network.vertices.map((vertex) => [
+ round((vertex.x - minX) * sx),
+ round((vertex.y - minY) * sy),
+ vertex.strokeCap ?? null,
+ vertex.strokeJoin ?? null
+ ]),
+ segments: network.segments.map((segment) => [
+ segment.start,
+ segment.end,
+ round(segment.tangentStart.x * sx),
+ round(segment.tangentStart.y * sy),
+ round(segment.tangentEnd.x * sx),
+ round(segment.tangentEnd.y * sy)
+ ]),
+ regions: network.regions
+ }
+}
+
+/**
+ * A paint as it looks, leaving out the color when the icon's color sets it, and a stroke's
+ * weight, which resizing scales.
+ */
+function paint(fill: Fill | Stroke, tinted: boolean) {
+ const { color, ...rest } = 'weight' in fill ? omit(fill, ['weight']) : fill
+ return tinted ? rest : { ...rest, color }
+}
+
+/** FNV-1a, enough to tell one glyph from another without keeping the whole description. */
+function hash(text: string): string {
+ let value = 0x811c9dc5
+ for (let index = 0; index < text.length; index++) {
+ value ^= text.charCodeAt(index)
+ value = Math.imul(value, 0x01000193)
+ }
+ return (value >>> 0).toString(16).padStart(8, '0')
+}
+
+/**
+ * A fingerprint of what an icon frame draws: which paths it holds and their shapes, stroke ends,
+ * and paints. Resizing the icon, however unevenly, or changing its color leaves it unchanged;
+ * editing points, rotating or fading a path, adding or removing one, or changing a color of the
+ * icon's own changes it. Moving a whole path or changing its stroke weight does not count, since
+ * resizing changes those by rounded amounts too.
+ */
+export function iconGlyph(graph: IconGraph, frame: SceneNode): string {
+ const description = graph.getChildren(frame.id).map((path) => {
+ const tint = readIconTint(path)
+ return {
+ type: path.type,
+ shape: shape(path.vectorNetwork),
+ fills: path.fills.map((fill) => paint(fill, tint.includes('fill'))),
+ strokes: path.strokes.map((stroke) => paint(stroke, tint.includes('stroke'))),
+ ends: [path.strokeCap, path.strokeJoin],
+ // Resizing leaves these alone, so they count, unlike a path's place and stroke weight.
+ rotation: round(path.rotation),
+ opacity: round(path.opacity),
+ visible: path.visible
+ }
+ })
+ return hash(JSON.stringify(description))
+}
+
+/**
+ * Whether an icon frame no longer draws the glyph it was placed with: its paths were edited,
+ * added, or removed. An icon placed before glyphs were recorded counts as unedited.
+ */
+export function isIconModified(graph: IconGraph, frame: SceneNode): boolean {
+ const glyph = readIcon(frame)?.glyph
+ return glyph !== undefined && iconGlyph(graph, frame) !== glyph
+}
diff --git a/packages/scene-graph/src/icons/model.ts b/packages/scene-graph/src/icons/model.ts
index ebc015626..28ec345cd 100644
--- a/packages/scene-graph/src/icons/model.ts
+++ b/packages/scene-graph/src/icons/model.ts
@@ -13,6 +13,19 @@ export function withIcon(node: SceneNode, icon: Icon | null): SceneNode['pluginD
return withPluginData(node.pluginData, OPEN_PENCIL_PLUGIN_DATA.icon, icon ?? undefined)
}
+/** The layer name an icon is placed with: its name in the set, such as `cat` for `mdi:cat`. */
+export function iconLayerName(name: string): string {
+ return name.slice(name.indexOf(':') + 1)
+}
+
+/**
+ * Whether `layerName` is the name an icon `name` was placed with, rather than one someone gave
+ * it: `cat`, or `Icon / mdi:cat` as icons were named before.
+ */
+export function isPlacedIconName(layerName: string, name: string): boolean {
+ return layerName === iconLayerName(name) || layerName === `Icon / ${name}`
+}
+
/** The names of the icons among `nodes`, each once, in the order they are first met. */
export function iconNames(nodes: Iterable<SceneNode>): string[] {
const names = new Set<string>()
diff --git a/packages/scene-graph/src/icons/schema.ts b/packages/scene-graph/src/icons/schema.ts
index 63c7670bd..e5704d434 100644
--- a/packages/scene-graph/src/icons/schema.ts
+++ b/packages/scene-graph/src/icons/schema.ts
@@ -3,7 +3,11 @@ import * as v from 'valibot'
/** An icon's name in its set, `prefix:name`, as Iconify names icons. */
export const ICON_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*:[a-z0-9]+(?:[-_][a-z0-9]+)*$/
-export const iconSchema = v.object({ name: v.pipe(v.string(), v.regex(ICON_NAME)) })
+export const iconSchema = v.object({
+ name: v.pipe(v.string(), v.regex(ICON_NAME)),
+ /** A fingerprint of the glyph as placed, to tell when its paths were edited; see `iconGlyph`. */
+ glyph: v.optional(v.string())
+})
/** An icon a frame draws. */
export type Icon = v.InferOutput<typeof iconSchema>
diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.ts
index 3b39085ca..0a9883a9d 100644
--- a/packages/scene-graph/src/index.ts
+++ b/packages/scene-graph/src/index.ts
@@ -29,6 +29,7 @@ export * from './slots/limits'
export * from './behaviours/kinds'
export * from './icons/schema'
export * from './icons/model'
+export * from './icons/glyph'
export * from './behaviours/layers'
export * from './behaviours/model'
export * from './behaviours/spec'
diff --git a/packages/vue/src/controls/icon/use.ts b/packages/vue/src/controls/icon/use.ts
index 6d2eeca04..c48a49896 100644
--- a/packages/vue/src/controls/icon/use.ts
+++ b/packages/vue/src/controls/icon/use.ts
@@ -1,8 +1,8 @@
import { watchImmediate } from '@vueuse/core'
-import { ref } from 'vue'
+import { computed, ref } from 'vue'
import { iconColor } from '@open-pencil/core/icons'
-import { readIcon } from '@open-pencil/scene-graph'
+import { isIconModified, readIcon } from '@open-pencil/scene-graph'
import type { Color } from '@open-pencil/scene-graph/primitives'
import { useUndoBatch } from '#vue/controls/undo-batch/use'
@@ -45,6 +45,32 @@ export function useIcon() {
setName.value = sets.find((info) => info.prefix === prefix)?.name ?? null
})
+ /** The selected icon's layer, so a question asked about it can be dropped if it changes. */
+ const frameId = computed(() => (name.value ? (selectedNode.value?.id ?? null) : null))
+
+ /** The icon's paths were edited since it was placed; see `isIconModified`. */
+ const modified = useSceneComputed(() => {
+ const node = selectedNode.value
+ const frame = node && name.value ? editor.graph.getNode(node.id) : undefined
+ return frame ? isIconModified(editor.graph, frame) : false
+ })
+
+ /** Draws the icon as it was placed, discarding edits to its paths. */
+ async function reset() {
+ const node = selectedNode.value
+ if (!node || !name.value) return
+ batch.flush()
+ await editor.resetIcon(node.id)
+ }
+
+ /** Makes the icon plain artwork that keeps its paths. */
+ function detach() {
+ const node = selectedNode.value
+ if (!node || !name.value) return
+ batch.flush()
+ editor.detachIcon(node.id)
+ }
+
async function swap(next: string) {
const node = selectedNode.value
if (!node || !name.value || name.value === next) return
@@ -67,5 +93,17 @@ export function useIcon() {
editor.setIconColor(node.id, next)
}
- return { name, color, preview, setName, swap, setColor, setColorPicking }
+ return {
+ frameId,
+ name,
+ color,
+ preview,
+ setName,
+ modified,
+ swap,
+ reset,
+ detach,
+ setColor,
+ setColorPicking
+ }
}
diff --git a/packages/vue/src/editor/commands/registry.ts b/packages/vue/src/editor/commands/registry.ts
index 70283ae61..2d1daa58e 100644
--- a/packages/vue/src/editor/commands/registry.ts
+++ b/packages/vue/src/editor/commands/registry.ts
@@ -31,6 +31,7 @@ export const EDITOR_COMMAND_METADATA = {
},
'selection.createComponentSet': { shortcut: 'MOD+SHIFT+K', keybinding: '$mod+Shift+KeyK' },
'selection.detachInstance': { shortcut: 'MOD+ALT+B', keybinding: '$mod+Alt+KeyB' },
+ 'selection.detachIcon': {},
'selection.goToMainComponent': {},
'selection.createInstance': {},
'selection.createSlot': { contextTestId: 'context-create-slot' },
diff --git a/packages/vue/src/editor/commands/selection.ts b/packages/vue/src/editor/commands/selection.ts
index 6b0dd8b62..ed7f22d8d 100644
--- a/packages/vue/src/editor/commands/selection.ts
+++ b/packages/vue/src/editor/commands/selection.ts
@@ -1,4 +1,4 @@
-import type { SceneNode } from '@open-pencil/scene-graph'
+import { readIcon, type SceneNode } from '@open-pencil/scene-graph'
import type { EditorCommandMapOptions } from './context'
import type { EditorCommand, EditorCommandId } from './types'
@@ -124,6 +124,19 @@ export function createSelectionCommands({
enabled: capabilities.canDetachInstance,
run: () => editor.detachInstance()
},
+ 'selection.detachIcon': {
+ id: 'selection.detachIcon',
+ get label() {
+ return t.value.detachIcon
+ },
+ enabled: capabilities.canDetachIcon,
+ run: () => {
+ const icons = editor.getSelectedNodes().filter((node) => readIcon(node))
+ editor.undo.runBatch('Detach icon', () => {
+ for (const icon of icons) editor.detachIcon(icon.id)
+ })
+ }
+ },
'selection.goToMainComponent': {
id: 'selection.goToMainComponent',
get label() {
diff --git a/packages/vue/src/editor/commands/types.ts b/packages/vue/src/editor/commands/types.ts
index 60b328f72..4bacacb62 100644
--- a/packages/vue/src/editor/commands/types.ts
+++ b/packages/vue/src/editor/commands/types.ts
@@ -14,6 +14,7 @@ export type EditorCommandId =
| 'selection.createComponentSet'
| 'selection.createInstance'
| 'selection.detachInstance'
+ | 'selection.detachIcon'
| 'selection.goToMainComponent'
| 'selection.createSlot'
| 'selection.wrapInAutoLayout'
diff --git a/packages/vue/src/editor/menu-model/canvas.ts b/packages/vue/src/editor/menu-model/canvas.ts
index 3175fb291..f954aa999 100644
--- a/packages/vue/src/editor/menu-model/canvas.ts
+++ b/packages/vue/src/editor/menu-model/canvas.ts
@@ -11,6 +11,7 @@ type CanvasMenuCommand =
| 'selection.componentAction'
| 'selection.componentSetAction'
| 'selection.instanceActions'
+ | 'selection.iconActions'
| 'selection.ungroupWhenGroup'
| 'selection.moveToPageWhenAvailable'
@@ -47,7 +48,12 @@ const CANVAS_MENU_GROUPS = [
'selection.outlineText',
'selection.outlineStroke'
],
- ['selection.componentAction', 'selection.componentSetAction', 'selection.instanceActions'],
+ [
+ 'selection.componentAction',
+ 'selection.componentSetAction',
+ 'selection.instanceActions',
+ 'selection.iconActions'
+ ],
['selection.toggleVisibility', 'selection.toggleLock'],
['selection.flipHorizontal', 'selection.flipVertical']
] satisfies readonly CanvasMenuGroup[]
@@ -86,6 +92,10 @@ function instanceItems({ commandMenuItem, selection }: CanvasMenuOptions): MenuE
: []
}
+function iconItems({ commandMenuItem, selection }: CanvasMenuOptions): MenuEntry[] {
+ return selection.isIcon.value ? [commandMenuItem('selection.detachIcon')] : []
+}
+
function conditionalCommand(command: CanvasMenuCommand, options: CanvasMenuOptions): MenuEntry[] {
switch (command) {
case 'selection.moveToPageWhenAvailable':
@@ -96,6 +106,8 @@ function conditionalCommand(command: CanvasMenuCommand, options: CanvasMenuOptio
return componentSetItems(options)
case 'selection.instanceActions':
return instanceItems(options)
+ case 'selection.iconActions':
+ return iconItems(options)
case 'selection.ungroupWhenGroup':
return options.selection.isGroup.value ? [options.commandMenuItem('selection.ungroup')] : []
default:
diff --git a/packages/vue/src/editor/menu-model/command-groups.ts b/packages/vue/src/editor/menu-model/command-groups.ts
index b514990e4..b8486ab23 100644
--- a/packages/vue/src/editor/menu-model/command-groups.ts
+++ b/packages/vue/src/editor/menu-model/command-groups.ts
@@ -14,6 +14,11 @@ export const VIEW_MENU_COMMANDS = [
export const OBJECT_MENU_COMMAND_GROUPS = [
['selection.group', 'selection.ungroup'],
- ['selection.createComponent', 'selection.createComponentSet', 'selection.detachInstance'],
+ [
+ 'selection.createComponent',
+ 'selection.createComponentSet',
+ 'selection.detachInstance',
+ 'selection.detachIcon'
+ ],
['selection.bringToFront', 'selection.sendToBack']
] satisfies ReadonlyArray<ReadonlyArray<EditorCommandId>>
diff --git a/packages/vue/src/editor/selection-capabilities/use.ts b/packages/vue/src/editor/selection-capabilities/use.ts
index 0dfdcbb3f..301d7b0d9 100644
--- a/packages/vue/src/editor/selection-capabilities/use.ts
+++ b/packages/vue/src/editor/selection-capabilities/use.ts
@@ -43,6 +43,7 @@ export function useSelectionCapabilities() {
canCreateComponent: computed(() => hasSelection.value),
canCreateComponentSet: selection.canCreateComponentSet,
canDetachInstance: computed(() => selection.isInstance.value),
+ canDetachIcon: computed(() => selection.isIcon.value),
canWrapInAutoLayout: computed(() => hasSelection.value),
canToggleMask: computed(() => hasSelection.value),
canBringToFront: computed(() => hasSelection.value),
diff --git a/packages/vue/src/editor/selection-state/use.ts b/packages/vue/src/editor/selection-state/use.ts
index c356c5a4f..8593562ba 100644
--- a/packages/vue/src/editor/selection-state/use.ts
+++ b/packages/vue/src/editor/selection-state/use.ts
@@ -1,6 +1,11 @@
import { computed } from 'vue'
-import { canCreateSlot as canBecomeSlot, slotOwner, slotPropertyId } from '@open-pencil/scene-graph'
+import {
+ canCreateSlot as canBecomeSlot,
+ readIcon,
+ slotOwner,
+ slotPropertyId
+} from '@open-pencil/scene-graph'
import { useEditor } from '#vue/editor/context'
import { useSelectedNodeState } from '#vue/editor/selection-state/nodes'
@@ -26,6 +31,8 @@ export function useSelectionState() {
const selectedNodeType = computed(() => selectedNode.value?.type ?? null)
const isInstance = computed(() => selectedNodeType.value === 'INSTANCE')
+ /** Whether the selection holds an icon, which can be detached into plain artwork. */
+ const isIcon = useSceneComputed(() => editor.getSelectedNodes().some((node) => readIcon(node)))
const isComponent = computed(() => selectedNodeType.value === 'COMPONENT')
const isGroup = computed(() => selectedNodeType.value === 'GROUP')
@@ -55,6 +62,7 @@ export function useSelectionState() {
selectedCount,
selectedNodeType,
isInstance,
+ isIcon,
isComponent,
isGroup,
canCreateComponentSet,
diff --git a/packages/vue/src/i18n/locales/de/commands.json b/packages/vue/src/i18n/locales/de/commands.json
index 5e1bb852f..be7725572 100644
--- a/packages/vue/src/i18n/locales/de/commands.json
+++ b/packages/vue/src/i18n/locales/de/commands.json
@@ -11,6 +11,7 @@
"createComponentSet": "Komponentensatz erstellen",
"createInstance": "Instanz erstellen",
"detachInstance": "Instanz lösen",
+ "detachIcon": "Symbol lösen",
"goToMainComponent": "Zur Hauptkomponente",
"addAutoLayout": "Auto-Layout hinzufügen",
"bringToFront": "In den Vordergrund",
diff --git a/packages/vue/src/i18n/locales/de/panels.json b/packages/vue/src/i18n/locales/de/panels.json
index 4ddbab11e..10b202810 100644
--- a/packages/vue/src/i18n/locales/de/panels.json
+++ b/packages/vue/src/i18n/locales/de/panels.json
@@ -392,6 +392,11 @@
"iconColor": "Symbolfarbe",
"swapIcon": "Symbol austauschen",
"insertIcon": "Symbol einfügen",
+ "iconModified": "Geändert",
+ "resetIcon": "Auf das ursprüngliche Symbol zurücksetzen",
+ "detachIcon": "Symbol lösen",
+ "swapEditedIconHeading": "Änderungen verwerfen?",
+ "swapEditedIconDescription": "Der Austausch zeichnet {name} anstelle dieses Symbols und verwirft die Änderungen an seinen Pfaden.",
"maskType": "Maskentyp",
"maskTypeAlpha": "Alpha",
"maskTypeVector": "Vektor",
diff --git a/packages/vue/src/i18n/locales/es/commands.json b/packages/vue/src/i18n/locales/es/commands.json
index b2b4539e7..8d259285c 100644
--- a/packages/vue/src/i18n/locales/es/commands.json
+++ b/packages/vue/src/i18n/locales/es/commands.json
@@ -11,6 +11,7 @@
"createComponentSet": "Crear conjunto de componentes",
"createInstance": "Crear instancia",
"detachInstance": "Separar instancia",
+ "detachIcon": "Desvincular icono",
"goToMainComponent": "Ir al componente principal",
"addAutoLayout": "Añadir auto-layout",
"bringToFront": "Traer al frente",
diff --git a/packages/vue/src/i18n/locales/es/panels.json b/packages/vue/src/i18n/locales/es/panels.json
index e0beee1a9..582d8da51 100644
--- a/packages/vue/src/i18n/locales/es/panels.json
+++ b/packages/vue/src/i18n/locales/es/panels.json
@@ -392,6 +392,11 @@
"iconColor": "Color del icono",
"swapIcon": "Cambiar icono",
"insertIcon": "Insertar icono",
+ "iconModified": "Modificado",
+ "resetIcon": "Restablecer el icono original",
+ "detachIcon": "Desvincular icono",
+ "swapEditedIconHeading": "¿Descartar los cambios?",
+ "swapEditedIconDescription": "Al cambiarlo se dibuja {name} en lugar de este icono y se descartan los cambios hechos en sus trazados.",
"maskType": "Tipo de máscara",
"maskTypeAlpha": "Alfa",
"maskTypeVector": "Vectorial",
diff --git a/packages/vue/src/i18n/locales/fr/commands.json b/packages/vue/src/i18n/locales/fr/commands.json
index 2f3ed8e41..ae12af3fb 100644
--- a/packages/vue/src/i18n/locales/fr/commands.json
+++ b/packages/vue/src/i18n/locales/fr/commands.json
@@ -11,6 +11,7 @@
"createComponentSet": "Créer un jeu de composants",
"createInstance": "Créer une instance",
"detachInstance": "Détacher l'instance",
+ "detachIcon": "Détacher l'icône",
"goToMainComponent": "Aller au composant principal",
"addAutoLayout": "Ajouter un auto-layout",
"bringToFront": "Mettre au premier plan",
diff --git a/packages/vue/src/i18n/locales/fr/panels.json b/packages/vue/src/i18n/locales/fr/panels.json
index 48134d2bc..82094138c 100644
--- a/packages/vue/src/i18n/locales/fr/panels.json
+++ b/packages/vue/src/i18n/locales/fr/panels.json
@@ -392,6 +392,11 @@
"iconColor": "Couleur de l'icône",
"swapIcon": "Changer d'icône",
"insertIcon": "Insérer une icône",
+ "iconModified": "Modifiée",
+ "resetIcon": "Rétablir l'icône d'origine",
+ "detachIcon": "Détacher l'icône",
+ "swapEditedIconHeading": "Abandonner vos modifications ?",
+ "swapEditedIconDescription": "Le remplacement dessine {name} à la place de cette icône et abandonne les modifications de ses tracés.",
"maskType": "Type de masque",
"maskTypeAlpha": "Alpha",
"maskTypeVector": "Vectoriel",
diff --git a/packages/vue/src/i18n/locales/it/commands.json b/packages/vue/src/i18n/locales/it/commands.json
index a886df13f..1479747e3 100644
--- a/packages/vue/src/i18n/locales/it/commands.json
+++ b/packages/vue/src/i18n/locales/it/commands.json
@@ -11,6 +11,7 @@
"createComponentSet": "Crea set di componenti",
"createInstance": "Crea istanza",
"detachInstance": "Scollega istanza",
+ "detachIcon": "Scollega icona",
"goToMainComponent": "Vai al componente principale",
"addAutoLayout": "Aggiungi auto-layout",
"bringToFront": "Porta in primo piano",
diff --git a/packages/vue/src/i18n/locales/it/panels.json b/packages/vue/src/i18n/locales/it/panels.json
index cb2be2635..dc4483d87 100644
--- a/packages/vue/src/i18n/locales/it/panels.json
+++ b/packages/vue/src/i18n/locales/it/panels.json
@@ -392,6 +392,11 @@
"iconColor": "Colore dell'icona",
"swapIcon": "Sostituisci icona",
"insertIcon": "Inserisci icona",
+ "iconModified": "Modificata",
+ "resetIcon": "Ripristina l'icona originale",
+ "detachIcon": "Scollega icona",
+ "swapEditedIconHeading": "Annullare le modifiche?",
+ "swapEditedIconDescription": "La sostituzione disegna {name} al posto di questa icona e annulla le modifiche ai suoi tracciati.",
"maskType": "Tipo di maschera",
"maskTypeAlpha": "Alfa",
"maskTypeVector": "Vettore",
diff --git a/packages/vue/src/i18n/locales/ja/commands.json b/packages/vue/src/i18n/locales/ja/commands.json
index b908ca159..f33ab878e 100644
--- a/packages/vue/src/i18n/locales/ja/commands.json
+++ b/packages/vue/src/i18n/locales/ja/commands.json
@@ -11,6 +11,7 @@
"createComponentSet": "コンポーネントセットを作成",
"createInstance": "インスタンスを作成",
"detachInstance": "インスタンスの切り離し",
+ "detachIcon": "アイコンを切り離す",
"goToMainComponent": "メインコンポーネントに移動",
"addAutoLayout": "オートレイアウトを追加",
"bringToFront": "最前面へ移動",
diff --git a/packages/vue/src/i18n/locales/ja/panels.json b/packages/vue/src/i18n/locales/ja/panels.json
index 81bb30a45..30b7b0642 100644
--- a/packages/vue/src/i18n/locales/ja/panels.json
+++ b/packages/vue/src/i18n/locales/ja/panels.json
@@ -386,6 +386,11 @@
"iconColor": "アイコンの色",
"swapIcon": "アイコンを入れ替え",
"insertIcon": "アイコンを挿入",
+ "iconModified": "変更済み",
+ "resetIcon": "元のアイコンに戻す",
+ "detachIcon": "アイコンを切り離す",
+ "swapEditedIconHeading": "編集を破棄しますか?",
+ "swapEditedIconDescription": "入れ替えると、このアイコンの代わりに {name} を描画し、パスへの変更は破棄されます。",
"maskType": "マスクの種類",
"maskTypeAlpha": "アルファ",
"maskTypeVector": "ベクター",
diff --git a/packages/vue/src/i18n/locales/pl/commands.json b/packages/vue/src/i18n/locales/pl/commands.json
index a733c8029..9cdddf6d9 100644
--- a/packages/vue/src/i18n/locales/pl/commands.json
+++ b/packages/vue/src/i18n/locales/pl/commands.json
@@ -11,6 +11,7 @@
"createComponentSet": "Utwórz zestaw komponentów",
"createInstance": "Utwórz instancję",
"detachInstance": "Odłącz instancję",
+ "detachIcon": "Odłącz ikonę",
"goToMainComponent": "Przejdź do komponentu",
"addAutoLayout": "Dodaj auto-layout",
"bringToFront": "Przenieś na wierzch",
diff --git a/packages/vue/src/i18n/locales/pl/panels.json b/packages/vue/src/i18n/locales/pl/panels.json
index 1da2d7d65..b25deabb2 100644
--- a/packages/vue/src/i18n/locales/pl/panels.json
+++ b/packages/vue/src/i18n/locales/pl/panels.json
@@ -398,6 +398,11 @@
"iconColor": "Kolor ikony",
"swapIcon": "Zamień ikonę",
"insertIcon": "Wstaw ikonę",
+ "iconModified": "Zmieniona",
+ "resetIcon": "Przywróć oryginalną ikonę",
+ "detachIcon": "Odłącz ikonę",
+ "swapEditedIconHeading": "Odrzucić zmiany?",
+ "swapEditedIconDescription": "Zamiana narysuje {name} w miejscu tej ikony i odrzuci zmiany wprowadzone w jej ścieżkach.",
"maskType": "Typ maski",
"maskTypeAlpha": "Alfa",
"maskTypeVector": "Wektorowa",
diff --git a/packages/vue/src/i18n/locales/ru/commands.json b/packages/vue/src/i18n/locales/ru/commands.json
index 74f8ab294..d5f7b8167 100644
--- a/packages/vue/src/i18n/locales/ru/commands.json
+++ b/packages/vue/src/i18n/locales/ru/commands.json
@@ -11,6 +11,7 @@
"createComponentSet": "Создать набор компонентов",
"createInstance": "Создать экземпляр",
"detachInstance": "Отвязать экземпляр",
+ "detachIcon": "Отсоединить иконку",
"goToMainComponent": "Перейти к компоненту",
"addAutoLayout": "Добавить авто-раскладку",
"bringToFront": "На передний план",
diff --git a/packages/vue/src/i18n/locales/ru/panels.json b/packages/vue/src/i18n/locales/ru/panels.json
index 550edd5bf..6b39a6431 100644
--- a/packages/vue/src/i18n/locales/ru/panels.json
+++ b/packages/vue/src/i18n/locales/ru/panels.json
@@ -398,6 +398,11 @@
"iconColor": "Цвет иконки",
"swapIcon": "Заменить иконку",
"insertIcon": "Вставить иконку",
+ "iconModified": "Изменена",
+ "resetIcon": "Вернуть исходную иконку",
+ "detachIcon": "Отсоединить иконку",
+ "swapEditedIconHeading": "Отменить изменения?",
+ "swapEditedIconDescription": "Замена нарисует {name} вместо этой иконки, а изменения её контуров будут потеряны.",
"maskType": "Тип маски",
"maskTypeAlpha": "Альфа-канал",
"maskTypeVector": "Вектор",
diff --git a/packages/vue/src/i18n/locales/zh-cn/commands.json b/packages/vue/src/i18n/locales/zh-cn/commands.json
index 859e0a998..ff87e2584 100644
--- a/packages/vue/src/i18n/locales/zh-cn/commands.json
+++ b/packages/vue/src/i18n/locales/zh-cn/commands.json
@@ -11,6 +11,7 @@
"createComponentSet": "创建组件集",
"createInstance": "创建实例",
"detachInstance": "分离实例",
+ "detachIcon": "分离图标",
"goToMainComponent": "转到主组件",
"addAutoLayout": "添加自动布局",
"bringToFront": "置于顶层",
diff --git a/packages/vue/src/i18n/locales/zh-cn/panels.json b/packages/vue/src/i18n/locales/zh-cn/panels.json
index 8cadb92d0..cf2f3dc61 100644
--- a/packages/vue/src/i18n/locales/zh-cn/panels.json
+++ b/packages/vue/src/i18n/locales/zh-cn/panels.json
@@ -386,6 +386,11 @@
"iconColor": "图标颜色",
"swapIcon": "替换图标",
"insertIcon": "插入图标",
+ "iconModified": "已修改",
+ "resetIcon": "恢复为原始图标",
+ "detachIcon": "分离图标",
+ "swapEditedIconHeading": "放弃修改?",
+ "swapEditedIconDescription": "替换会在此处绘制 {name},并放弃对其路径所做的修改。",
"maskType": "蒙版类型",
"maskTypeAlpha": "Alpha",
"maskTypeVector": "矢量",
diff --git a/packages/vue/src/i18n/messages/commands.ts b/packages/vue/src/i18n/messages/commands.ts
index 204b7ff5a..90732a102 100644
--- a/packages/vue/src/i18n/messages/commands.ts
+++ b/packages/vue/src/i18n/messages/commands.ts
@@ -16,6 +16,7 @@ export const commandMessageDefaults = {
createComponentSet: 'Create component set',
createInstance: 'Create instance',
detachInstance: 'Detach instance',
+ detachIcon: 'Detach icon',
goToMainComponent: 'Go to main component',
addAutoLayout: 'Add auto layout',
useAsMask: 'Use as mask',
diff --git a/packages/vue/src/i18n/messages/panels.ts b/packages/vue/src/i18n/messages/panels.ts
index 66749af48..ee5e909cb 100644
--- a/packages/vue/src/i18n/messages/panels.ts
+++ b/packages/vue/src/i18n/messages/panels.ts
@@ -156,6 +156,13 @@ export const panelMessageDefaults = {
iconColor: 'Icon color',
swapIcon: 'Swap icon',
insertIcon: 'Insert icon',
+ iconModified: 'Modified',
+ resetIcon: 'Reset to the original icon',
+ detachIcon: 'Detach icon',
+ swapEditedIconHeading: 'Discard your edits?',
+ swapEditedIconDescription: params(
+ 'Swapping draws {name} in place of this icon and discards the changes made to its paths.'
+ ),
export: 'Export',
typography: 'Typography',
fontFamily: 'Font family',
diff --git a/packages/vue/src/primitives/LayerTree/context.ts b/packages/vue/src/primitives/LayerTree/context.ts
index b166640ee..b621d58c1 100644
--- a/packages/vue/src/primitives/LayerTree/context.ts
+++ b/packages/vue/src/primitives/LayerTree/context.ts
@@ -9,6 +9,8 @@ export interface LayerNode {
layoutMode: string
/** Whether the layer is a slot frame holding a slot property's content. */
slot?: boolean
+ /** Whether the layer is an icon from a set, which keeps its name to be swapped or exported. */
+ icon?: boolean
visible: boolean
locked: boolean
children?: LayerNode[]
diff --git a/packages/vue/src/primitives/LayerTree/model.ts b/packages/vue/src/primitives/LayerTree/model.ts
index af003c9f7..dd708eb22 100644
--- a/packages/vue/src/primitives/LayerTree/model.ts
+++ b/packages/vue/src/primitives/LayerTree/model.ts
@@ -1,4 +1,4 @@
-import { slotPropertyId } from '@open-pencil/scene-graph'
+import { readIcon, slotPropertyId } from '@open-pencil/scene-graph'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import type { LayerNode, LayerRow, LayerSelectionMode } from '#vue/primitives/LayerTree/context'
@@ -10,6 +10,7 @@ function nodeToLayerNode(node: SceneNode): LayerNode {
type: node.type,
layoutMode: node.layoutMode,
slot: !!slotPropertyId(node),
+ icon: !!readIcon(node),
visible: node.visible,
locked: node.locked
}
@@ -59,6 +60,7 @@ export function patchLayerNode(target: LayerNode, source: SceneNode): boolean {
target.type !== source.type ||
target.layoutMode !== source.layoutMode ||
target.slot !== !!slotPropertyId(source) ||
+ target.icon !== !!readIcon(source) ||
target.visible !== source.visible ||
target.locked !== source.locked
if (!changed) return false
@@ -66,6 +68,7 @@ export function patchLayerNode(target: LayerNode, source: SceneNode): boolean {
target.type = source.type
target.layoutMode = source.layoutMode
target.slot = !!slotPropertyId(source)
+ target.icon = !!readIcon(source)
target.visible = source.visible
target.locked = source.locked
return true
diff --git a/packages/vue/tests/editor/menu-model/canvas.test.ts b/packages/vue/tests/editor/menu-model/canvas.test.ts
new file mode 100644
index 000000000..def44d8a0
--- /dev/null
+++ b/packages/vue/tests/editor/menu-model/canvas.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, test } from 'bun:test'
+
+import { ref } from 'vue'
+
+import type { EditorCommandId } from '@open-pencil/vue'
+
+import { buildCanvasContextMenu } from '#vue/editor/menu-model/canvas'
+import type { CanvasMenuOptions } from '#vue/editor/menu-model/canvas'
+
+/** The canvas menu's command ids for a selection that is an icon or not. */
+function menuIds(isIcon: boolean) {
+ const menu = buildCanvasContextMenu({
+ commandMenuItem: (id: EditorCommandId) => ({ id, label: id }),
+ otherPages: [],
+ moveSelectionToPage: (pageId: string) => pageId,
+ selection: {
+ hasSelection: ref(true),
+ isGroup: ref(false),
+ isComponent: ref(false),
+ isInstance: ref(false),
+ isIcon: ref(isIcon),
+ canCreateComponentSet: ref(false),
+ canCreateSlot: ref(false)
+ } as CanvasMenuOptions['selection'],
+ t: { moveToPage: 'Move to page' }
+ })
+ return menu.flatMap((item) => (item.separator ? [] : [item.id]))
+}
+
+describe('canvas menu for icons', () => {
+ test('offers Detach icon only for icons', () => {
+ expect(menuIds(true)).toContain('selection.detachIcon')
+ expect(menuIds(false)).not.toContain('selection.detachIcon')
+ })
+})
diff --git a/packages/vue/tests/primitives/LayerTree/model.test.ts b/packages/vue/tests/primitives/LayerTree/model.test.ts
new file mode 100644
index 000000000..f8eb52c2f
--- /dev/null
+++ b/packages/vue/tests/primitives/LayerTree/model.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, test } from 'bun:test'
+
+import { SceneGraph, withIcon } from '@open-pencil/scene-graph'
+import { buildLayerTreeModel, patchLayerNode } from '@open-pencil/vue'
+
+describe('layer tree model', () => {
+ test('marks icon frames, so rows can show them as icons', () => {
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ const frame = graph.createNode('FRAME', pageId, { name: 'Frame' })
+ const icon = graph.createNode('FRAME', pageId, { name: 'cat' })
+ graph.updateNode(icon.id, { pluginData: withIcon(icon, { name: 'mdi:cat' }) })
+
+ const model = buildLayerTreeModel(graph, pageId)
+ expect(model.byId.get(icon.id)?.icon).toBe(true)
+ expect(model.byId.get(frame.id)?.icon).toBe(false)
+
+ const row = model.byId.get(frame.id)
+ if (!row) throw new Error('Expected the frame in the model')
+ graph.updateNode(frame.id, { pluginData: withIcon(frame, { name: 'mdi:home' }) })
+ expect(patchLayerNode(row, frame)).toBe(true)
+ expect(row.icon).toBe(true)
+ })
+})
diff --git a/src/app/editor/icons.ts b/src/app/editor/icons.ts
index 74b561e41..a9c69544b 100644
--- a/src/app/editor/icons.ts
+++ b/src/app/editor/icons.ts
@@ -12,12 +12,15 @@ import IconMinus from '~icons/lucide/minus'
import IconMousePointer from '~icons/lucide/mouse-pointer'
import IconPenTool from '~icons/lucide/pen-tool'
import IconRows from '~icons/lucide/rows-3'
+import IconSmile from '~icons/lucide/smile'
import IconSquare from '~icons/lucide/square'
import IconSlot from '~icons/lucide/square-dashed'
import IconStar from '~icons/lucide/star'
import IconTriangle from '~icons/lucide/triangle'
import IconType from '~icons/lucide/type'
+import { readIcon, slotPropertyId, type SceneNode } from '@open-pencil/scene-graph'
+
import type { Tool } from '@/app/editor/session'
export const toolIcons: Record<Tool, Component> = {
@@ -58,9 +61,21 @@ export const COMPONENT_TYPES = new Set(['COMPONENT', 'COMPONENT_SET', 'INSTANCE'
export { IconFrame, IconSquare }
-export function nodeIcon(node: { type: string; layoutMode: string; slot?: boolean }) {
+/** The glyph for a layer: its kind, or a slot or icon frame. A component keeps its own glyph. */
+export function nodeIcon(node: {
+ type: string
+ layoutMode: string
+ slot?: boolean
+ icon?: boolean
+}) {
if (node.slot) return IconSlot
+ if (node.icon && node.type === 'FRAME') return IconSmile
if (node.type === 'FRAME' && node.layoutMode !== 'NONE')
return AUTO_LAYOUT_ICONS[node.layoutMode] ?? IconFrame
return NODE_ICONS[node.type] ?? IconSquare
}
+
+/** `nodeIcon` for a scene node, which carries slot and icon identity in its data. */
+export function sceneNodeIcon(node: SceneNode) {
+ return nodeIcon({ ...node, slot: !!slotPropertyId(node), icon: !!readIcon(node) })
+}
diff --git a/src/app/shell/menu/schema.ts b/src/app/shell/menu/schema.ts
index 8b522f7d0..e03e36f7e 100644
--- a/src/app/shell/menu/schema.ts
+++ b/src/app/shell/menu/schema.ts
@@ -364,6 +364,11 @@ export const APP_MENU_SCHEMA = [
label: 'Detach Instance',
command: 'selection.detachInstance'
},
+ {
+ id: 'selection.detachIcon',
+ label: 'Detach Icon',
+ command: 'selection.detachIcon'
+ },
{ type: 'separator' },
{
id: 'selection.moveToPage',
diff --git a/src/components/DesignPanel.vue b/src/components/DesignPanel.vue
index f5fde349e..d7a735ab0 100644
--- a/src/components/DesignPanel.vue
+++ b/src/components/DesignPanel.vue
@@ -2,10 +2,11 @@
import { computed } from 'vue'
import { getNodeEditCapability } from '@open-pencil/core/editor'
+import { readIcon } from '@open-pencil/scene-graph'
import { useI18n, useSelectionState, useEditorCommands } from '@open-pencil/vue'
import { useEditorStore } from '@/app/editor/active-store'
-import { COMPONENT_TYPES, nodeIcon } from '@/app/editor/icons'
+import { COMPONENT_TYPES, sceneNodeIcon } from '@/app/editor/icons'
import { openVariablesDialog } from '@/app/editor/tokens/dialog'
import { openLibraryReview, useLibraryService } from '@/app/libraries'
import IconButton from '@/components/ui/button/IconButton.vue'
@@ -58,7 +59,7 @@ const isComponentType = computed(() => {
const canAddVariant = computed(
() => !!node.value && getNodeEditCapability(store.graph, node.value.id).editable
)
-const selectedIcon = computed(() => (node.value ? nodeIcon(node.value) : undefined))
+const selectedIcon = computed(() => (node.value ? sceneNodeIcon(node.value) : undefined))
function openSelectedInstanceReview() {
const instance = node.value
if (instance?.type !== 'INSTANCE' || !instance.componentId) return
@@ -187,7 +188,8 @@ const { panels } = useI18n()
<SlotAuthoringSection />
<BehaviourPanel v-if="node.type === 'COMPONENT' || node.type === 'COMPONENT_SET'" />
- <FramePresetSelect v-if="node.type === 'FRAME'" />
+ <!-- Presets size artboards; an icon is a glyph. -->
+ <FramePresetSelect v-if="node.type === 'FRAME' && !readIcon(node)" />
<IconSection />
<PositionSection />
diff --git a/src/components/design-check/IssueMarkerTooltip.vue b/src/components/design-check/IssueMarkerTooltip.vue
index 5775feba8..e127ec807 100644
--- a/src/components/design-check/IssueMarkerTooltip.vue
+++ b/src/components/design-check/IssueMarkerTooltip.vue
@@ -15,7 +15,7 @@ import { useDesignCheckMessages } from '@open-pencil/vue'
import { useEditorStore } from '@/app/editor/active-store'
import { issueDetail, ruleTitle } from '@/app/editor/design-check/format'
import { compareIssueSeverity, type DesignIssue } from '@/app/editor/design-check/issues'
-import { nodeIcon } from '@/app/editor/icons'
+import { sceneNodeIcon } from '@/app/editor/icons'
import SeverityIcon from '@/components/ui/feedback/SeverityIcon.vue'
import { issueTooltip } from '@/theme/design-check'
@@ -124,7 +124,7 @@ const edgeHeading = computed(() => {
<span v-if="edgeHeading" :class="styles.headerText()">{{ edgeHeading }}</span>
<template v-else-if="singleNode">
<component
- :is="nodeIcon(singleNode)"
+ :is="sceneNodeIcon(singleNode)"
:class="styles.headerIcon()"
aria-hidden="true"
/>
diff --git a/src/components/design-check/useDesignCheckPanel.ts b/src/components/design-check/useDesignCheckPanel.ts
index d1d2caee6..9c02e41dd 100644
--- a/src/components/design-check/useDesignCheckPanel.ts
+++ b/src/components/design-check/useDesignCheckPanel.ts
@@ -19,7 +19,7 @@ import {
type DesignIssue,
type DesignIssueSeverity
} from '@/app/editor/design-check/issues'
-import { nodeIcon } from '@/app/editor/icons'
+import { IconFrame, sceneNodeIcon } from '@/app/editor/icons'
import { appPreferences } from '@/app/settings/preferences/store'
import type { IssueGroupView, IssueRowView } from './types'
@@ -94,7 +94,7 @@ export function useDesignCheckPanel(options: {
return {
issue,
layerName: node?.name ?? issue.nodeName,
- layerIcon: nodeIcon(node ?? { type: 'FRAME', layoutMode: 'NONE' }),
+ layerIcon: node ? sceneNodeIcon(node) : IconFrame,
detail: issueDetail(issue, messages.value),
swatch: issueSwatch(issue),
action: node ? issueAction(issue, messages.value) : null,
diff --git a/src/components/properties/IconSection.vue b/src/components/properties/IconSection.vue
index d07e12aef..f69ae11e7 100644
--- a/src/components/properties/IconSection.vue
+++ b/src/components/properties/IconSection.vue
@@ -1,28 +1,75 @@
<script setup lang="ts">
import { tv } from 'tailwind-variants'
+import { ref, watch } from 'vue'
-import { useIcon, usePanelMessages } from '@open-pencil/vue'
+import { iconLayerName } from '@open-pencil/scene-graph'
+import { useCommonMessages, useIcon, usePanelMessages } from '@open-pencil/vue'
import ColorInput from '@/components/ColorPicker/ColorInput.vue'
import IconPicker from '@/components/icon-picker/IconPicker.vue'
import IconPreview from '@/components/icon-picker/IconPreview.vue'
+import IconButton from '@/components/ui/button/IconButton.vue'
+import { AppConfirmationDialog } from '@/components/ui/dialog'
import PanelFieldGroup from '@/components/ui/panel/PanelFieldGroup.vue'
import PanelSection from '@/components/ui/panel/PanelSection.vue'
import theme from '@/theme/select/app'
const panels = usePanelMessages()
-const { name, color, preview, setName, swap, setColor, setColorPicking } = useIcon()
+const common = useCommonMessages()
+const {
+ frameId,
+ name,
+ color,
+ preview,
+ setName,
+ modified,
+ swap,
+ reset,
+ detach,
+ setColor,
+ setColorPicking
+} = useIcon()
const styles = tv(theme)()
+
+/** An icon picked to replace an edited one, waiting for the edits to be given up. */
+const pendingSwap = ref<string | null>(null)
+// The question is about the icon selected when it was asked; another selection drops it, so a
+// confirmation never swaps an icon it did not describe.
+watch(frameId, () => {
+ pendingSwap.value = null
+})
+
+function pick(next: string) {
+ if (modified.value) pendingSwap.value = next
+ else void swap(next)
+}
+
+function confirmSwap() {
+ const next = pendingSwap.value
+ pendingSwap.value = null
+ if (next) void swap(next)
+}
</script>
<template>
<PanelSection v-if="name" :label="panels.icon">
+ <template #actions>
+ <span v-if="modified" class="mr-1 text-[11px] text-muted" data-property="icon-modified">
+ {{ panels.iconModified }}
+ </span>
+ <IconButton v-if="modified" :label="panels.resetIcon" @click="reset">
+ <icon-lucide-rotate-ccw class="size-3.5" />
+ </IconButton>
+ <IconButton :label="panels.detachIcon" @click="detach">
+ <icon-lucide-unlink class="size-3.5" />
+ </IconButton>
+ </template>
<PanelFieldGroup :label="panels.swapIcon">
<IconPicker
:heading="panels.swapIcon"
:selected="name"
:set="name.slice(0, name.indexOf(':'))"
- @select="swap"
+ @select="pick"
>
<template #trigger>
<button
@@ -34,7 +81,7 @@ const styles = tv(theme)()
>
<IconPreview :svg="preview" class="mr-1.5 size-3.5 text-surface" />
<span :class="styles.value()">
- {{ name.slice(name.indexOf(':') + 1) }}
+ {{ iconLayerName(name) }}
<span class="text-muted">{{ setName ?? name.slice(0, name.indexOf(':')) }}</span>
</span>
<icon-lucide-chevron-down class="ml-1 size-3 shrink-0 text-muted" />
@@ -51,5 +98,15 @@ const styles = tv(theme)()
@open-change="setColorPicking"
/>
</PanelFieldGroup>
+ <AppConfirmationDialog
+ :open="pendingSwap !== null"
+ :heading="panels.swapEditedIconHeading"
+ :description="panels.swapEditedIconDescription({ name: iconLayerName(pendingSwap ?? '') })"
+ :cancel-label="common.cancel"
+ :confirm-label="panels.swapIcon"
+ tone="warning"
+ @update:open="(open: boolean) => !open && (pendingSwap = null)"
+ @confirm="confirmSwap"
+ />
</PanelSection>
</template>
diff --git a/src/components/properties/component-properties/PropertyBindingRow.vue b/src/components/properties/component-properties/PropertyBindingRow.vue
index 02e40691f..543b1e0f7 100644
--- a/src/components/properties/component-properties/PropertyBindingRow.vue
+++ b/src/components/properties/component-properties/PropertyBindingRow.vue
@@ -2,7 +2,7 @@
import type { ComponentBinding } from '@open-pencil/vue'
import { usePanelMessages } from '@open-pencil/vue'
-import { nodeIcon } from '@/app/editor/icons'
+import { sceneNodeIcon } from '@/app/editor/icons'
import AppButton from '@/components/ui/button/AppButton.vue'
import IconButton from '@/components/ui/button/IconButton.vue'
@@ -20,7 +20,7 @@ const panels = usePanelMessages()
:aria-label="binding.variantName ? `${binding.variantName}: ${binding.name}` : binding.name"
@click="$emit('select', binding.nodeId)"
>
- <component :is="nodeIcon(binding.node)" class="size-3.5 shrink-0" aria-hidden="true" />
+ <component :is="sceneNodeIcon(binding.node)" class="size-3.5 shrink-0" aria-hidden="true" />
<span class="min-w-0 truncate text-left"
>{{ binding.variantName ? `${binding.variantName} / ` : '' }}{{ binding.name }}</span
>
diff --git a/src/components/properties/component-properties/PropertyBindings.vue b/src/components/properties/component-properties/PropertyBindings.vue
index 4c9795e6b..9d359b640 100644
--- a/src/components/properties/component-properties/PropertyBindings.vue
+++ b/src/components/properties/component-properties/PropertyBindings.vue
@@ -7,7 +7,7 @@ import {
type ComponentBindingGroup
} from '@open-pencil/vue'
-import { nodeIcon } from '@/app/editor/icons'
+import { sceneNodeIcon } from '@/app/editor/icons'
import AppButton from '@/components/ui/button/AppButton.vue'
import { collapsibleContentMotion } from '@/theme/collapsible/collapsible'
@@ -31,7 +31,7 @@ const panels = usePanelMessages()
class="size-3.5 shrink-0 transition-transform data-[open]:rotate-90 motion-reduce:transition-none"
:data-open="open || undefined"
/>
- <component :is="nodeIcon(group.node)" class="size-3.5 shrink-0" aria-hidden="true" />
+ <component :is="sceneNodeIcon(group.node)" class="size-3.5 shrink-0" aria-hidden="true" />
<span class="min-w-0 truncate">{{ group.name }}</span>
<span class="ml-auto text-[10px] text-muted">{{
group.bindings.length === totalVariants
diff --git a/tests/e2e/design/icons.spec.ts b/tests/e2e/design/icons.spec.ts
index 3a2dee2fc..c8b31e310 100644
--- a/tests/e2e/design/icons.spec.ts
+++ b/tests/e2e/design/icons.spec.ts
@@ -60,6 +60,11 @@ async function pick(page: Page, picker: string, query: string, icon: string) {
await expect(dialog).toBeHidden()
}
+/** The layer tree row named `name`. */
+function layerRow(page: Page, name: string) {
+ return page.locator('[data-node-id]').filter({ hasText: name }).first()
+}
+
async function insertSquare(page: Page) {
await page.getByRole('button', { name: 'Insert icon' }).click()
await pick(page, 'Insert icon', 'shape', 'square')
@@ -71,7 +76,7 @@ test('the toolbar inserts a picked icon, selected, as one undo step', async () =
await insertSquare(page)
const icon = await getSelectedNode(page)
- expect(icon).toMatchObject({ type: 'FRAME', name: 'Icon / test:square', width: 24 })
+ expect(icon).toMatchObject({ type: 'FRAME', name: 'square', width: 24 })
expect(icon?.childIds).toHaveLength(1)
// The search previews and the placed icon load the set once between them.
expect(requests).toMatchObject({ search: 1, sets: 1 })
@@ -86,7 +91,7 @@ test('the Object menu opens the same picker', async () => {
await menu.getByRole('menuitem', { name: 'Insert Icon…' }).click()
await pick(page, 'Insert icon', 'shape', 'ring')
- expect(await getSelectedNode(page)).toMatchObject({ name: 'Icon / test:ring' })
+ expect(await getSelectedNode(page)).toMatchObject({ name: 'ring' })
})
test('the Icon section swaps the glyph in place, undoably', async () => {
@@ -102,7 +107,7 @@ test('the Icon section swaps the glyph in place, undoably', async () => {
id: before?.id,
x: before?.x,
y: before?.y,
- name: 'Icon / test:ring'
+ name: 'ring'
})
await canvas.undo()
@@ -171,3 +176,36 @@ test('icons in the file and picked lately come first', async () => {
await page.keyboard.press('Escape')
await expect(dialog).toBeHidden()
})
+
+test('an edited icon says so, asks before a swap discards the edit, and resets or detaches', async () => {
+ const { page } = ctx
+ await insertSquare(page)
+ // Rotate the icon's path, as someone editing its artwork would, then select the icon again.
+ const iconRow = layerRow(page, 'square')
+ await iconRow.locator('[data-slot="disclosure"]').click()
+ await layerRow(page, 'path').click()
+ const rotationField = propertyField(page, 'rotation')
+ await rotationField.click()
+ const rotation = rotationField.getByRole('spinbutton', { name: 'Rotation' })
+ await rotation.fill('15')
+ await rotation.press('Enter')
+ await iconRow.click()
+ const section = propertySection(page, 'Icon')
+ await expect(propertyField(page, 'icon-modified')).toBeVisible()
+
+ await section.getByRole('button', { name: 'Swap icon' }).click()
+ const swap = page.getByRole('dialog', { name: 'Swap icon' })
+ await swap.getByRole('textbox').fill('shape')
+ await swap.getByRole('option', { name: 'ring' }).click()
+ const confirm = page.getByRole('alertdialog')
+ await expect(confirm).toBeVisible()
+ await confirm.getByRole('button', { name: 'Cancel' }).click()
+ await expect(propertyField(page, 'icon-name')).toContainText('square')
+
+ await section.getByRole('button', { name: 'Reset to the original icon' }).click()
+ await expect(propertyField(page, 'icon-modified')).toBeHidden()
+ expect((await getSelectedNode(page))?.childIds).toHaveLength(1)
+
+ await section.getByRole('button', { name: 'Detach icon' }).click()
+ await expect(section).toBeHidden()
+})
diff --git a/tests/engine/vue/editor/menu-model/canvas.test.ts b/tests/engine/vue/editor/menu-model/canvas.test.ts
index c4d39ec05..c4edfee47 100644
--- a/tests/engine/vue/editor/menu-model/canvas.test.ts
+++ b/tests/engine/vue/editor/menu-model/canvas.test.ts
@@ -13,6 +13,7 @@ function selection(overrides: Partial<CanvasMenuOptions['selection']> = {}) {
isGroup: ref(false),
isComponent: ref(false),
isInstance: ref(false),
+ isIcon: ref(false),
canCreateComponentSet: ref(false),
canCreateSlot: ref(false),
...overrides