AI-native design editor. Open-source Figma alternative.
feat(icons): pick, insert, swap, and recolor icons (#987)
Danila Poyarkov33712b6b4674
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c312e8d7f..e4ec32b62 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -34,11 +34,13 @@- `SceneNode.primaryAxisSizing` and `counterAxisSizing` are `AxisSizingMode` (`'FIXED' | 'HUG'`) instead of `LayoutSizing`: fill is stored only on the child, as `layoutGrow` along its parent's primary axis and `layoutAlignSelf: 'STRETCH'` across it, as Figma stores it. Read and change a node's per-axis sizing with `layoutSizing`, `layoutSizingOptions`, and `layoutSizingUpdates` from `@open-pencil/scene-graph`. A frame that an earlier version stored as filling through its own sizing, which `.fig` files never kept, is fixed until it is set to fill again.- `buildDerivedTextDataV4` is removed from `@open-pencil/core`, and `sceneNodeToKiwi` no longer writes glyph outlines by itself: pass the `runtime` that `withFigExportRuntime(graph, canvasKit, write)` hands its callback. In `@open-pencil/fig/node-change`, `FigNodeChangeExportRuntime` takes `shapeText(node)` instead of `getGlyphOutlineMetrics`, `buildDerivedTextData` takes the `baselines` it writes, and `convertFigmaDerivedTextGlyphs` takes the text's characters.- The `updates` messages from `@open-pencil/vue` no longer include `availableTitle`, `installPrompt`, `installedTitle`, and `downloading`, which only the system update dialogs and download toast used; `installed` now takes only `{ version }`, and `install` reads "Install Update". The Software Update window uses the new `windowTitle`, `currentVersion`, `whatsNew`, `installAndRestart`, `restartNow`, and related messages.+- `fetchIcon`, `fetchIcons`, `searchIcons`, `searchIconsBatch`, and `clearIconCache` are removed from `@open-pencil/core`. Icons come from an `IconProvider` instead: `iconify` is the default Iconify provider, `createIconifyProvider()` makes one with its own cache, and `placeIcon` places an icon that keeps its name. A custom provider also implements `previews()`, `collections()`, and `browse()`, which give pickers each icon's SVG markup, the sets, and a set's icons.### Added- 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.- 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.jsonindex 8269aac86..5ff702a31 100644--- a/desktop/generated/menu.json+++ b/desktop/generated/menu.json@@ -301,6 +301,13 @@{"type": "separator"},+ {+ "id": "insert-icon",+ "label": "Insert Icon…"+ },+ {+ "type": "separator"+ },{"id": "selection.toggleMask","label": "Use as Mask",diff --git a/packages/core/src/design-jsx/index.ts b/packages/core/src/design-jsx/index.tsindex fffd75cf4..f1f9b400a 100644--- a/packages/core/src/design-jsx/index.ts+++ b/packages/core/src/design-jsx/index.ts@@ -1,4 +1,4 @@-export { renderJSX, renderTree } from './renderer'+export { designJSXRenderer, renderJSX, renderTree } from './renderer'export {finishRenderPlacement,resolveRenderPlacement,diff --git a/packages/core/src/design-jsx/renderer.ts b/packages/core/src/design-jsx/renderer.tsindex d58138cc0..38b8b32b7 100644--- a/packages/core/src/design-jsx/renderer.ts+++ b/packages/core/src/design-jsx/renderer.ts@@ -1,7 +1,6 @@import { createDesignJSXRenderer, type SVGSource } from '@open-pencil/design-jsx'-import { fetchIcons } from '#core/icons'-import { createIconFromPaths } from '#core/icons/render'+import { iconify, placeIcon, type IconProvider } from '#core/icons'import { extractPaths, extractPathsFromElements, scalePathInfos } from '#core/icons/svg'import type { IconData } from '#core/icons/types'import { computeAllLayouts } from '#core/layout'@@ -15,6 +14,9 @@ function parseViewBox(viewBox: string | undefined): { w: number; h: number } {return { w: parts[2] ?? 0, h: parts[3] ?? 0 }}+/** The set inline SVG artwork is reported in, which no icon provider has. */+const INLINE_SVG = 'svg'+/** Inline SVG through the same path pipeline as Iconify icons, scaled from its viewBox. */function svgIconData({ body, elements, props }: SVGSource, size: number): IconData | null {// Children may arrive as parsed SVG elements rather than markup; both use the same shapes.@@ -23,7 +25,7 @@ function svgIconData({ body, elements, props }: SVGSource, size: number): IconDaif (pathInfos.length === 0) return nullconst viewBox = parseViewBox(props.viewBox as string | undefined)return {- prefix: 'svg',+ prefix: INLINE_SVG,name: (props.name as string | undefined) ?? 'custom',width: size,height: size,@@ -35,14 +37,39 @@ function svgIconData({ body, elements, props }: SVGSource, size: number): IconDa}}-/** Design JSX rendering with OpenPencil's icons, SVG conversion, and layout. */-export const { renderJSX, renderTree } = createDesignJSXRenderer<IconData>({- async icon(name, size) {- const icon = (await fetchIcons([name], size)).get(name)- return icon && icon.paths.length > 0 ? icon : null- },- svg: svgIconData,- createArtwork: (graph, icon, { parentId, size, color, overrides }) =>- createIconFromPaths(graph, icon, icon.name, size, color, parentId, overrides),- layout: computeAllLayouts-})+function createRenderer(icons: IconProvider) {+ return createDesignJSXRenderer<IconData>({+ async icon(name, size) {+ const icon = (await icons.icons([name], size)).get(name)+ return icon && icon.paths.length > 0 ? icon : null+ },+ svg: svgIconData,+ createArtwork: (graph, icon, { parentId, size, color, overrides }) =>+ placeIcon(graph, parentId, icon, {+ size,+ color,+ overrides,+ // Inline SVG is artwork, not an icon from a set.+ identity: icon.prefix !== INLINE_SVG+ }),+ layout: computeAllLayouts+ })+}++const renderers = new WeakMap<IconProvider, ReturnType<typeof createRenderer>>()++/**+ * Design JSX rendering with OpenPencil's SVG conversion and layout, drawing `<Icon>` from+ * `icons`, such as the `FigmaAPI`'s provider, so a host's own icons render too.+ */+export function designJSXRenderer(icons: IconProvider = iconify) {+ let renderer = renderers.get(icons)+ if (!renderer) {+ renderer = createRenderer(icons)+ renderers.set(icons, renderer)+ }+ return renderer+}++/** Design JSX rendering with Iconify's icons. */+export const { renderJSX, renderTree } = designJSXRenderer()diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.tsindex b0d24c2b1..93b63b173 100644--- a/packages/core/src/editor/create.ts+++ b/packages/core/src/editor/create.ts@@ -13,6 +13,7 @@ import {hasStoredBackground,setDefaultPageBackground} from '#core/figma-api/page-backgrounds'+import { iconify } from '#core/icons'import { releaseFigPopulationWorker } from '#core/kiwi/fig/population/client'import { releaseOriginalFigArchive } from '#core/kiwi/fig/session/original-archive'import { installTextMeasurer } from '#core/layout'@@ -36,6 +37,7 @@ import { createDesignTokenActions } from './design-tokens'import { createGraphEventSubscription } from './graph-events'import { createGraphReadActions } from './graph-reads'import { createGuideActions } from './guides'+import { createIconActions } from './icons'import { createDesignIssueActions } from './issues'import { createNodeActions } from './nodes'import { createPageActions } from './pages'@@ -219,6 +221,7 @@ export function createEditor(options?: EditorOptions) {loadFont: _loadFont,resolveFigmaClipboardImages: options?.resolveFigmaClipboardImages ?? null,getViewportSize: _getViewportSize,+ icons: options?.icons ?? iconify,getCk: () => _ck,getRenderer: () => _renderer,getTextEditor: () => _textEditor,@@ -253,6 +256,7 @@ export function createEditor(options?: EditorOptions) {const variables = createVariableActions(ctx)const designTokens = createDesignTokenActions(ctx, variables, nodes)const vectorize = createVectorizeActions(ctx)+ const icons = createIconActions(ctx)const alignment = createAlignmentActions(ctx)const preview = createPlayActions(ctx)const clipboardBridge = createClipboardBridge(clipboard, selection)@@ -386,6 +390,7 @@ export function createEditor(options?: EditorOptions) {// Bitmap-to-vector replacement...vectorize,+ ...icons,// Variables...variables,diff --git a/packages/core/src/editor/icons.ts b/packages/core/src/editor/icons.tsnew file mode 100644index 000000000..36010891e--- /dev/null+++ b/packages/core/src/editor/icons.ts@@ -0,0 +1,124 @@+import { readIcon, type SceneNode } from '@open-pencil/scene-graph'+import { BLACK } from '@open-pencil/scene-graph/constants'+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 type { IconData } from '#core/icons/types'++/** The size a picked icon is placed at, as Iconify sets draw them. */+const ICON_SIZE = 24++/**+ * Icon commands: insert, swap, and recolor, each one undo step. An icon is a frame of paths,+ * so inserting and swapping record the frame's whole subtree and swap between the copies.+ */+export function createIconActions(ctx: EditorContext) {+ async function fetchIcon(name: string, size: number): Promise<IconData> {+ const icon = (await ctx.icons.icons([name], size)).get(name)+ if (!icon || icon.paths.length === 0) throw new Error(`Icon "${name}" not found`)+ return icon+ }++ /** Runs `change` on the icon `frameId`, undoably, putting back the subtree it had before. */+ function changeIcon(label: string, frameId: string, change: () => void): void {+ const frame = ctx.graph.getNode(frameId)+ const parentId = frame?.parentId+ if (!frame || !parentId) return+ const index = ctx.graph.getNode(parentId)?.childIds.indexOf(frameId) ?? -1+ const before = snapshotSubtree(ctx.graph, frameId)+ change()+ const after = snapshotSubtree(ctx.graph, frameId)+ const show = (snapshot: Map<string, SceneNode>) => () => {+ const root = snapshot.get(frameId)+ if (!root) return+ if (ctx.graph.getNode(frameId)) ctx.graph.deleteNode(frameId)+ restoreSubtree(ctx.graph, root, parentId, snapshot)+ if (index !== -1) ctx.graph.insertChildAt(frameId, parentId, index)+ ctx.requestRender()+ }+ ctx.undo.push({ label, forward: show(after), inverse: show(before) })+ ctx.requestRender()+ }++ /**+ * Places the icon `name` at the middle of the view, in the container being edited or the+ * page, and selects it; null when the document was replaced while the icon loaded.+ */+ async function insertIcon(name: string, color: Color = BLACK): Promise<string | null> {+ const graph = ctx.graph+ const icon = await fetchIcon(name, ICON_SIZE)+ // Opening another document while the icon loaded leaves nothing to insert it into.+ if (ctx.graph !== graph) return null+ const { width, height } = ctx.getViewportSize()+ const parentId = ctx.state.enteredContainerId ?? ctx.state.currentPageId+ const origin =+ parentId === ctx.state.currentPageId+ ? { x: 0, y: 0 }+ : ctx.graph.getAbsolutePosition(parentId)+ const x = (width / 2 - ctx.state.panX) / ctx.state.zoom - origin.x - ICON_SIZE / 2+ const y = (height / 2 - ctx.state.panY) / ctx.state.zoom - origin.y - ICON_SIZE / 2+ const previousSelection = new Set(ctx.state.selectedIds)+ const frame = placeIcon(ctx.graph, parentId, icon, {+ size: ICON_SIZE,+ color,+ overrides: { x: Math.round(x), y: Math.round(y) }+ })+ const created = snapshotSubtree(ctx.graph, frame.id)+ ctx.undo.push({+ label: 'Insert icon',+ forward: () => {+ const root = created.get(frame.id)+ if (root && !ctx.graph.getNode(frame.id)) restoreSubtree(ctx.graph, root, parentId, created)+ ctx.setSelectedIds(new Set([frame.id]))+ ctx.requestRender()+ },+ inverse: () => {+ if (ctx.graph.getNode(frame.id)) ctx.graph.deleteNode(frame.id)+ ctx.setSelectedIds(previousSelection)+ ctx.requestRender()+ }+ })+ ctx.setSelectedIds(new Set([frame.id]))+ ctx.requestRender()+ return frame.id+ }++ /** Draws the icon `name` in the icon `frameId`, keeping its size, position, and color. */+ async function swapIconGlyph(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))+ }++ /**+ * Sets the color of the icon `frameId`'s tinted paths. Only their paints are recorded, so a+ * color drag batched into one step stays cheap.+ */+ function setIconColor(frameId: string, color: Color) {+ const paints = () =>+ ctx.graph.getChildren(frameId).map(({ id, fills, strokes }) => ({ id, fills, strokes }))+ const before = paints()+ recolorIcon(ctx.graph, frameId, color)+ const after = paints()+ const apply = (state: typeof before) => () => {+ for (const { id, ...rest } of state) ctx.graph.updateNode(id, rest)+ ctx.requestRender()+ }+ ctx.undo.push({ label: 'Change icon color', forward: apply(after), inverse: apply(before) })+ ctx.requestRender()+ }++ return {+ /** Where the editor's icons come from, for pickers to search and preview. */+ iconProvider: ctx.icons,+ insertIcon,+ swapIconGlyph,+ setIconColor+ }+}diff --git a/packages/core/src/editor/types.ts b/packages/core/src/editor/types.tsindex 31543e6e6..81a0c349c 100644--- a/packages/core/src/editor/types.ts+++ b/packages/core/src/editor/types.ts@@ -21,6 +21,7 @@ import type { InterfaceTheme } from '#core/constants'import type { PlayState } from '#core/editor/play/actions'import type { SnappingPreferences } from '#core/editor/preferences'import type { RotationPreview } from '#core/geometry'+import type { IconProvider } from '#core/icons/provider'import type { TextEditor } from '#core/text/editor'import type { FontResolutionEvent, FontResolutionSnapshot } from '#core/text/resolver'@@ -166,6 +167,8 @@ export interface EditorOptions {) => Promise<ArrayBuffer | null>resolveFigmaClipboardImages?: FigmaClipboardImageResolvergetViewportSize?: () => { width: number; height: number }+ /** Where icons are searched and fetched; defaults to Iconify. */+ icons?: IconProviderskipInitialGraphSetup?: boolean}@@ -182,6 +185,7 @@ export interface EditorContext {) => Promise<ArrayBuffer | null>resolveFigmaClipboardImages: FigmaClipboardImageResolver | nullgetViewportSize: () => { width: number; height: number }+ icons: IconProvidergetCk: () => CanvasKit | nullgetRenderer: () => SkiaRenderer | nullgetTextEditor: () => TextEditor | nulldiff --git a/packages/core/src/figma-api/index.ts b/packages/core/src/figma-api/index.tsindex 7d007d282..97738cad3 100644--- a/packages/core/src/figma-api/index.ts+++ b/packages/core/src/figma-api/index.ts@@ -25,6 +25,7 @@ import { wrapNodes } from '#core/editor/structure/container-wrap'import { ungroupNode } from '#core/editor/structure/group'import { textAutoResizeChanges } from '#core/editor/text/auto-resize'import { setDefaultPageBackground } from '#core/figma-api/page-backgrounds'+import { iconify, type IconProvider } from '#core/icons'import type { RasterCodec } from '#core/io/formats/raster'import { reconcileVariableLayouts } from '#core/layout/variables'import { documentFontStatus, type DocumentFontStatus } from '#core/text/font/status'@@ -574,6 +575,8 @@ export class FigmaAPI implements NodeProxyHost {}exportImage?: (nodeIds: string[], options: ExportImageOptions) => Promise<Uint8Array | null>+ /** Where icon tools search and fetch icons; hosts may pass a self-hosted or bundled set. */+ icons: IconProvider = iconifyrasterCodec?: RasterCodec/** The document as it was before the current AI run first edited `pageId`, or null if unedited. */changeBaseline?: (pageId: string) => SceneGraph | nulldiff --git a/packages/core/src/icons/api.ts b/packages/core/src/icons/api.tsindex ed24e6a3d..3d10da8b6 100644--- a/packages/core/src/icons/api.ts+++ b/packages/core/src/icons/api.ts@@ -1,6 +1,9 @@+import { uniq } from 'es-toolkit'import { createFetch } from 'ofetch'+import * as v from 'valibot'-import type { IconifyResponse, IconSearchResult } from './types'+import { CollectionListJSON, CollectionsJSON } from './schema'+import type { IconCollection, IconifyResponse, IconSearchResult } from './types'const ICONIFY_API = 'https://api.iconify.design'const FETCH_TIMEOUT_MS = 10_000@@ -15,6 +18,17 @@ export function createIconifyAPIClient(timeout: FETCH_TIMEOUT_MS})+ /** A response body as text, so callers validate what the API sent rather than trust it. */+ async function text(path: string, query?: Record<string, string>): Promise<string> {+ const response = await iconifyAPI.raw<string, 'text'>(path, {+ ignoreResponseError: true,+ responseType: 'text',+ query+ })+ if (!response.ok) throw new Error(`Iconify API error: ${response.status} for ${path}`)+ return response._data ?? ''+ }+return {async fetchCollection(prefix: string, iconNames: string[]): Promise<IconifyResponse> {const response = await iconifyAPI.raw<IconifyResponse>(`/${prefix}.json`, {@@ -27,6 +41,32 @@ export function createIconifyAPIClient(return response._data as IconifyResponse},+ /** Every icon set the API serves, retired ones left out. */+ async collections(): Promise<IconCollection[]> {+ const parsed = v.safeParse(CollectionsJSON, await text('/collections'))+ if (!parsed.success) throw new Error('Iconify API returned an unexpected set list')+ return Object.entries(parsed.output)+ .filter(([, info]) => !info.hidden)+ .map(([prefix, info]) => ({+ prefix,+ name: info.name,+ total: info.total,+ category: info.category ?? null,+ license: info.license?.title ?? null,+ multicolor: info.palette === true+ }))+ },++ /** Every icon in the set `prefix`, as `prefix:name`, in the set's own order. */+ async collectionIcons(prefix: string): Promise<string[]> {+ const parsed = v.safeParse(CollectionListJSON, await text('/collection', { prefix }))+ if (!parsed.success)+ throw new Error(`Iconify API returned an unexpected list for "${prefix}"`)+ const { uncategorized = [], categories = {} } = parsed.output+ const names = uniq([...uncategorized, ...Object.values(categories).flat()])+ return names.map((name) => `${prefix}:${name}`)+ },+async search(query: string,options?: { limit?: number; prefix?: string }@@ -47,19 +87,3 @@ export function createIconifyAPIClient(}}}--const iconifyAPIClient = createIconifyAPIClient()--export function fetchIconifyCollection(- prefix: string,- iconNames: string[]-): Promise<IconifyResponse> {- return iconifyAPIClient.fetchCollection(prefix, iconNames)-}--export function searchIconify(- query: string,- options?: { limit?: number; prefix?: string }-): Promise<IconSearchResult> {- return iconifyAPIClient.search(query, options)-}diff --git a/packages/core/src/icons/index.ts b/packages/core/src/icons/index.tsindex bc9e2286a..a63d949ad 100644--- a/packages/core/src/icons/index.ts+++ b/packages/core/src/icons/index.ts@@ -1,88 +1,13 @@-import { fetchIconifyCollection, searchIconify } from './api'-import { buildIconData } from './svg'-import type { IconData, IconSearchResult } from './types'--export type { IconData, IconPath, IconSearchResult } from './types'--const iconCache = new Map<string, IconData>()--export function clearIconCache(): void {- iconCache.clear()-}--function parseIconName(name: string): { prefix: string; iconName: string } {- const colonIdx = name.indexOf(':')- if (colonIdx === -1) {- throw new Error(- `Invalid icon name "${name}". Use prefix:name format (e.g. lucide:heart, mdi:home)`- )- }- return { prefix: name.slice(0, colonIdx), iconName: name.slice(colonIdx + 1) }-}--export async function fetchIcon(name: string, size = 24): Promise<IconData> {- const results = await fetchIcons([name], size)- const result = results.get(name)- if (!result)- throw new Error(`Icon "${name}" not found. Check the name at https://icon-sets.iconify.design/`)- return result-}--export async function fetchIcons(names: string[], size = 24): Promise<Map<string, IconData>> {- const results = new Map<string, IconData>()- const toFetch = new Map<string, string[]>()-- for (const name of names) {- const cacheKey = `${name}@${size}`- const cached = iconCache.get(cacheKey)- if (cached) {- results.set(name, cached)- continue- }- const { prefix, iconName } = parseIconName(name)- const group = toFetch.get(prefix) ?? []- group.push(iconName)- toFetch.set(prefix, group)- }-- const fetches = [...toFetch.entries()].map(async ([prefix, iconNames]) => {- const data = await fetchIconifyCollection(prefix, iconNames)- const defaultW = data.width ?? 24- const defaultH = data.height ?? 24-- for (const iconName of iconNames) {- const fullName = `${prefix}:${iconName}`- let entry = data.icons[iconName]- if (!entry) {- const alias = data.aliases?.[iconName]- if (alias) entry = data.icons[alias.parent]- }- if (!entry) continue- const iconData = buildIconData(entry, prefix, iconName, defaultW, defaultH, size)- iconCache.set(`${fullName}@${size}`, iconData)- results.set(fullName, iconData)- }- })-- await Promise.all(fetches)- return results-}--export { searchIconify as searchIcons }--export async function searchIconsBatch(- queries: string[],- options?: {- limit?: number- prefix?: string- }-): Promise<Map<string, IconSearchResult>> {- const results = new Map<string, IconSearchResult>()- await Promise.all(- queries.map(async (query) => {- const result = await searchIconify(query, options)- results.set(query, result)- })- )- return results-}+import { createIconifyProvider, type IconProvider } from './provider'++export {+ createIconifyProvider,+ parseIconName,+ type IconProvider,+ type IconSearchOptions+} from './provider'+export { 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. */+export const iconify: IconProvider = createIconifyProvider()diff --git a/packages/core/src/icons/provider.ts b/packages/core/src/icons/provider.tsnew file mode 100644index 000000000..130633586--- /dev/null+++ b/packages/core/src/icons/provider.ts@@ -0,0 +1,166 @@+import { iconToHTML, iconToSVG } from '@iconify/utils'+import { chunk } from 'es-toolkit'++import { createIconifyAPIClient } from './api'+import { buildIconData } from './svg'+import type { IconCollection, IconData, IconifyIconEntry, IconSearchResult } from './types'++export interface IconSearchOptions {+ limit?: number+ /** Only icons from this set, such as `lucide`. */+ prefix?: string+}++/**+ * Where icons come from: their search, their paths, and their previews. Hosts pass one to the+ * renderer, tools, and the app, so another source, such as a bundled or self-hosted set, can+ * stand in for Iconify. A provider owns its cache.+ */+export interface IconProvider {+ search(query: string, options?: IconSearchOptions): Promise<IconSearchResult>+ /** Each named icon at `size`, by name; names the source lacks are left out. */+ icons(names: readonly string[], size: number): Promise<Map<string, IconData>>+ /**+ * Each named icon as SVG markup for pickers to show, painted in `currentColor` where the icon+ * takes its color; names the source lacks are left out.+ */+ previews(names: readonly string[]): Promise<Map<string, string>>+ /** The icon sets to choose from, for filtering a search or browsing one set. */+ collections(): Promise<IconCollection[]>+ /** Every icon in the set `prefix`, as `prefix:name`, for browsing without a query. */+ browse(prefix: string): Promise<string[]>+}++/** `prefix:name` split, or null when the name has no set. */+export function parseIconName(name: string): { prefix: string; iconName: string } | null {+ const colon = name.indexOf(':')+ if (colon <= 0 || colon === name.length - 1) return null+ return { prefix: name.slice(0, colon), iconName: name.slice(colon + 1) }+}++/** Names per request, so the query string of a long list stays well within URL limits. */+const NAMES_PER_REQUEST = 100++/** An icon's body and box, with the set's default box filled in. */+type IconEntry = Required<IconifyIconEntry>++/**+ * Icons from the Iconify API, fetched one request per set and cached by name, so search+ * previews and placed icons share what was loaded.+ */+export function createIconifyProvider(client = createIconifyAPIClient()): IconProvider {+ const entries = new Map<string, IconEntry>()+ const built = new Map<string, IconData>()+ // Shared answers; a failed one is dropped so the next call asks again.+ let catalogue: Promise<IconCollection[]> | null = null+ const sets = new Map<string, Promise<string[]>>()++ function remember<T>(promise: Promise<T>, forget: () => void): Promise<T> {+ void promise.catch(forget)+ return promise+ }++ /** Names the source answered without, so they are not asked for again. */+ const absent = new Set<string>()+ /** Requests on their way, by the names they ask for, so overlapping calls share them. */+ const loading = new Map<string, Promise<void>>()++ async function request(prefix: string, iconNames: string[]): Promise<void> {+ const collection = await client.fetchCollection(prefix, iconNames)+ for (const iconName of iconNames) {+ const parent = collection.aliases?.[iconName]?.parent+ const entry = collection.icons[iconName] ?? (parent ? collection.icons[parent] : undefined)+ const name = `${prefix}:${iconName}`+ if (!entry) {+ absent.add(name)+ continue+ }+ entries.set(name, {+ body: entry.body,+ width: entry.width ?? collection.width ?? 24,+ height: entry.height ?? collection.height ?? 24+ })+ }+ }++ async function load(names: readonly string[]): Promise<void> {+ const waiting = new Set<Promise<void>>()+ const needed = new Map<string, string[]>()+ for (const name of names) {+ if (entries.has(name) || absent.has(name)) continue+ const pending = loading.get(name)+ if (pending) {+ waiting.add(pending)+ continue+ }+ const parsed = parseIconName(name)+ if (!parsed)+ throw new Error(+ `Invalid icon name "${name}". Use prefix:name format (e.g. lucide:heart, mdi:home)`+ )+ needed.set(parsed.prefix, [...(needed.get(parsed.prefix) ?? []), parsed.iconName])+ }+ for (const [prefix, iconNames] of needed) {+ for (const part of chunk(iconNames, NAMES_PER_REQUEST)) {+ const pending = request(prefix, part)+ const keys = part.map((iconName) => `${prefix}:${iconName}`)+ for (const key of keys) loading.set(key, pending)+ // Settled either way, the names leave the queue; a failure can be asked for again.+ const settle = () => {+ for (const key of keys) if (loading.get(key) === pending) loading.delete(key)+ }+ void pending.then(settle, settle)+ waiting.add(pending)+ }+ }+ await Promise.all(waiting)+ }++ return {+ search: (query, options) => client.search(query, options),++ async icons(names, size) {+ await load(names)+ const found = new Map<string, IconData>()+ for (const name of names) {+ const entry = entries.get(name)+ const parsed = parseIconName(name)+ if (!entry || !parsed) continue+ const key = `${name}@${size}`+ const icon =+ built.get(key) ??+ buildIconData(entry, parsed.prefix, parsed.iconName, entry.width, entry.height, size)+ built.set(key, icon)+ found.set(name, icon)+ }+ return found+ },++ collections() {+ catalogue ??= remember(client.collections(), () => {+ catalogue = null+ })+ return catalogue+ },++ browse(prefix) {+ const cached = sets.get(prefix)+ if (cached) return cached+ const listed = remember(client.collectionIcons(prefix), () => sets.delete(prefix))+ sets.set(prefix, listed)+ return listed+ },++ async previews(names) {+ await load(names)+ const found = new Map<string, string>()+ for (const name of names) {+ const entry = entries.get(name)+ if (!entry) continue+ const { attributes, body } = iconToSVG(entry)+ found.set(name, iconToHTML(body, attributes))+ }+ return found+ }+ }+}diff --git a/packages/core/src/icons/render.ts b/packages/core/src/icons/render.tsindex 46226ca4b..a4047367f 100644--- a/packages/core/src/icons/render.ts+++ b/packages/core/src/icons/render.ts@@ -1,58 +1,132 @@-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import {+ readIcon,+ readIconTint,+ withIcon,+ withIconTint,+ type IconPaint,+ type SceneGraph,+ type SceneNode+} from '@open-pencil/scene-graph'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 { createPathStroke, pathStrokeLineStyle } from '#core/icons/path-style'-import type { IconData } from './types'+import type { IconData, IconPath } from './types'-export function createIconFromPaths(+/** The paint an SVG uses for the icon's own color. */+const CURRENT_COLOR = 'currentColor'++export interface PlaceIconOptions {+ size: number+ /** What `currentColor` paints become; paths with their own colors keep them. */+ color: Color+ /** Fields of the icon's frame, such as its position or name. */+ overrides?: Partial<SceneNode>+ /**+ * Record the icon's name on its frame, so it can be swapped and exported as that icon. Off for+ * artwork that has no name in a set, such as inline SVG.+ */+ identity?: boolean+}++function solid(color: Color) {+ return [{ type: 'SOLID' as const, color, opacity: 1, visible: true }]+}++/** One path of an icon as a vector filling the icon's box, marked where the icon's color paints. */+function addPath(graph: SceneGraph, frameId: string, path: IconPath, size: number, color: Color) {+ const tint: IconPaint[] = []+ const paint = (value: string, kind: IconPaint) => {+ if (value !== CURRENT_COLOR) return parseColor(value)+ tint.push(kind)+ return color+ }+ const vector = graph.createNode('VECTOR', frameId, {+ name: 'path',+ x: 0,+ y: 0,+ width: size,+ height: size,+ vectorNetwork: path.vectorNetwork,+ fills: path.fill ? solid(paint(path.fill, 'fill')) : []+ })+ if (path.stroke) {+ const stroke = createPathStroke(+ paint(path.stroke, 'stroke'),+ path.strokeWidth,+ path.strokeCap,+ path.strokeJoin+ )+ graph.updateNode(vector.id, { strokes: [stroke], ...pathStrokeLineStyle(stroke) })+ }+ if (tint.length > 0)+ graph.updateNode(vector.id, {+ pluginData: withIconTint(graph.getNode(vector.id) ?? vector, tint)+ })+}++/**+ * An icon as a frame of vector paths that keeps the icon's name, so it can be swapped,+ * recolored, and exported as an icon rather than as anonymous paths.+ */+export function placeIcon(graph: SceneGraph,- icon: IconData,- name: string,- size: number,- color: Color,parentId: string,- overrides?: Partial<SceneNode>+ icon: IconData,+ { size, color, overrides, identity = true }: PlaceIconOptions): SceneNode {+ const name = `${icon.prefix}:${icon.name}`const frame = graph.createNode('FRAME', parentId, {- name: `Icon / ${name}`,+ name: identity ? `Icon / ${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)+ return graph.getNode(frame.id) ?? frame+}- for (const path of icon.paths) {- const vector = graph.createNode('VECTOR', frame.id, {- name: 'path',- width: size,- height: size,- vectorNetwork: path.vectorNetwork- })- vector.x = 0- vector.y = 0-- if (path.fill) {- const fillColor = path.fill === 'currentColor' ? color : parseColor(path.fill)- graph.updateNode(vector.id, {- fills: [{ type: 'SOLID', color: fillColor, opacity: 1, visible: true }]- })- } else {- graph.updateNode(vector.id, { fills: [] })- }-- if (path.stroke) {- const strokeColor = path.stroke === 'currentColor' ? color : parseColor(path.stroke)- const stroke = createPathStroke(- strokeColor,- path.strokeWidth,- path.strokeCap,- path.strokeJoin- )- graph.updateNode(vector.id, { strokes: [stroke], ...pathStrokeLineStyle(stroke) })- }+/** 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)) {+ const tint = readIconTint(path)+ if (tint.includes('fill') && path.fills[0]) return path.fills[0].color+ if (tint.includes('stroke') && path.strokes[0]) return path.strokes[0].color+ }+ return null+}++/** Sets the color of an icon's tinted paints; paths with colors of their own keep them. */+export function recolorIcon(graph: SceneGraph, frameId: string, color: Color): void {+ for (const path of graph.getChildren(frameId)) {+ const tint = readIconTint(path)+ if (tint.includes('fill'))+ graph.updateNode(path.id, { fills: path.fills.map((fill) => ({ ...fill, color })) })+ if (tint.includes('stroke'))+ graph.updateNode(path.id, { strokes: path.strokes.map((stroke) => ({ ...stroke, color })) })}+}- return frame+/**+ * 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.+ */+export function swapIcon(graph: SceneGraph, frameId: string, icon: IconData): void {+ const frame = graph.getNode(frameId)+ if (!frame || !readIcon(frame)) return+ const color = iconColor(graph, frame) ?? BLACK+ // The paths are scaled to the size the icon was built at; their boxes must match it.+ const size = icon.width+ for (const child of graph.getChildren(frameId)) graph.deleteNode(child.id)+ const name = `${icon.prefix}:${icon.name}`+ graph.updateNode(frameId, {+ name: frame.name.startsWith('Icon / ') ? `Icon / ${name}` : frame.name,+ pluginData: withIcon(frame, { name })+ })+ for (const path of icon.paths) addPath(graph, frameId, path, size, color)}diff --git a/packages/core/src/icons/schema.ts b/packages/core/src/icons/schema.tsnew file mode 100644index 000000000..610db3662--- /dev/null+++ b/packages/core/src/icons/schema.ts@@ -0,0 +1,31 @@+import * as v from 'valibot'++/** One icon set in the Iconify catalogue, keeping only what pickers show. */+const CollectionInfo = v.object({+ name: v.string(),+ total: v.number(),+ category: v.optional(v.string()),+ license: v.optional(v.object({ title: v.string() })),+ /** True for sets drawn in their own colors, which an icon color cannot change. */+ palette: v.optional(v.boolean()),+ /** Iconify lists retired sets for old links; pickers leave them out. */+ hidden: v.optional(v.boolean())+})++/** `GET /collections`: every set by prefix. */+export const CollectionsJSON = v.pipe(+ v.string(),+ v.parseJson(),+ v.record(v.string(), CollectionInfo)+)++/** `GET /collection?prefix=…`: the names in one set, loose or by category. */+export const CollectionListJSON = v.pipe(+ v.string(),+ v.parseJson(),+ v.object({+ uncategorized: v.optional(v.array(v.string())),+ categories: v.optional(v.record(v.string(), v.array(v.string()))),+ hidden: v.optional(v.array(v.string()))+ })+)diff --git a/packages/core/src/icons/types.ts b/packages/core/src/icons/types.tsindex e2c1471f5..dfdb84225 100644--- a/packages/core/src/icons/types.ts+++ b/packages/core/src/icons/types.ts@@ -37,6 +37,19 @@ export interface IconSearchResult {collections: Record<string, { name: string; total: number; category?: string }>}+/** An icon set: what a picker shows to choose one. */+export interface IconCollection {+ /** The set's part of an icon name, such as `lucide`. */+ prefix: string+ name: string+ total: number+ category: string | null+ /** The license's title, such as `MIT`. */+ license: string | null+ /** Drawn in the set's own colors, which an icon color does not change. */+ multicolor: boolean+}+export interface IconPathInfo {d: stringfill: string | nulldiff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex bf9d95829..b80a0d5da 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -282,14 +282,19 @@ export {export { svg, renderSVGNode, type SVGNode } from './io/formats/svg/node'export { parseSVGPath } from '@open-pencil/scene-graph/parse-path'export {- fetchIcon,- fetchIcons,- searchIcons,- searchIconsBatch,- clearIconCache,+ createIconifyProvider,+ iconColor,+ iconify,+ parseIconName,+ placeIcon,+ recolorIcon,+ swapIcon,type IconData,type IconPath,- type IconSearchResult+ type IconProvider,+ type IconSearchOptions,+ type IconSearchResult,+ type PlaceIconOptions} from './icons'export { exportFigFile, compressFigData, compressFigDataSync } from './io/formats/fig/export'export {diff --git a/packages/core/src/io/formats/html/vectors.ts b/packages/core/src/io/formats/html/vectors.tsindex de7c94186..fd8e911fd 100644--- a/packages/core/src/io/formats/html/vectors.ts+++ b/packages/core/src/io/formats/html/vectors.ts@@ -1,5 +1,8 @@import type { DesignElement, DesignNode, VectorElementRenderer } from '@open-pencil/dom-css/export'+import { readIcon, readIconTint } from '@open-pencil/scene-graph'+import { colorToHex } from '@open-pencil/scene-graph/color'+import { iconColor } from '#core/icons/render'import { renderNodeSVGElement } from '#core/io/formats/svg/export'import type { SVGNode } from '#core/io/formats/svg/node'@@ -24,18 +27,26 @@ function idPart(id: string): string {}/**- * Vector layers in HTML exports as inline SVG from the SVG export, so paths, gradients, and- * shadows draw as they do there. Def ids start with the layer's id, so several SVGs on one page- * never pick up each other's gradients or filters.+ * 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.*/export const vectorElement: VectorElementRenderer = (graph, node) => {const idPrefix = `${idPart(node.id)}-`+ const icon = readIcon(node)const drawn = renderNodeSVGElement(graph, node, {idPrefix,- colorSpace: graph.documentColorSpace+ colorSpace: graph.documentColorSpace,+ tint: icon ? readIconTint : undefined})const element = drawn && designNode(drawn)if (element?.type !== 'element') return null- // Strokes and shadows can reach past the layer's box, which an inline SVG would clip.- return { ...element, inlineStyle: { overflow: 'visible' } } satisfies DesignElement+ const color = icon ? iconColor(graph, node) : null+ return {+ ...element,+ attrs: icon ? { ...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/src/io/formats/svg/defs.ts b/packages/core/src/io/formats/svg/defs.tsindex eeddbc025..504e5e1bd 100644--- a/packages/core/src/io/formats/svg/defs.ts+++ b/packages/core/src/io/formats/svg/defs.ts@@ -19,6 +19,8 @@ export interface SVGExportContext {colorSpace: RenderColorSpace/** Starts every def id, so SVGs inlined on one page cannot reference each other's defs. */idPrefix?: string+ /** Paints drawn in `currentColor`, such as an icon's tinted paths, so CSS `color` sets them. */+ tint?: (node: SceneNode) => readonly ('fill' | 'stroke')[]}export function nextDefId(ctx: SVGExportContext, prefix: string): string {diff --git a/packages/core/src/io/formats/svg/export.ts b/packages/core/src/io/formats/svg/export.tsindex f8e8577fe..88a59ecbc 100644--- a/packages/core/src/io/formats/svg/export.ts+++ b/packages/core/src/io/formats/svg/export.ts@@ -382,6 +382,9 @@ function buildShapeChildren(return []}+/** The paint CSS `color` sets, for a tinted icon path. */+const CURRENT_COLOR = 'currentColor'+function renderNode(node: SceneNode, ctx: SVGExportContext): SVGNode | null {if (!node.visible) return null@@ -396,11 +399,17 @@ function renderNode(node: SceneNode, ctx: SVGExportContext): SVGNode | null {const visibleFills = node.fills.filter((f) => f.visible)const visibleStrokes = node.strokes.filter((s) => s.visible)- const fillAttr =+ const tint = ctx.tint?.(node) ?? []+ const ownFill =visibleFills.length > 0 && !hasPathLevelFills(node)? resolveFill(visibleFills[0], node, ctx): null- const strokeAttrs = buildSVGStrokeAttrs(visibleStrokes, ctx.colorSpace)+ const fillAttr = ownFill && tint.includes('fill') ? CURRENT_COLOR : ownFill+ const ownStrokes = buildSVGStrokeAttrs(visibleStrokes, ctx.colorSpace)+ const strokeAttrs =+ ownStrokes.stroke && tint.includes('stroke')+ ? { ...ownStrokes, stroke: CURRENT_COLOR }+ : ownStrokesconst children: (SVGNode | null)[] = buildShapeChildren(node,@@ -520,9 +529,13 @@ export function renderNodesToSVG(export function renderNodeSVGElement(graph: SceneGraph,node: SceneNode,- { idPrefix, colorSpace = 'srgb' }: { idPrefix: string; colorSpace?: RenderColorSpace }+ {+ idPrefix,+ colorSpace = 'srgb',+ tint+ }: Pick<SVGExportContext, 'tint'> & { idPrefix: string; colorSpace?: RenderColorSpace }): SVGNode | null {- const ctx: SVGExportContext = { defs: [], defIdCounter: 0, graph, colorSpace, idPrefix }+ const ctx: SVGExportContext = { defs: [], defIdCounter: 0, graph, colorSpace, idPrefix, tint }const drawn = renderNode({ ...node, x: 0, y: 0, rotation: 0, opacity: 1 }, ctx)if (!drawn) return null// A straight line has no height or width, but its stroke still needs a viewport to draw in.diff --git a/packages/core/src/tools/analyze/diff/apply.ts b/packages/core/src/tools/analyze/diff/apply.tsindex b9209a090..61ed4cf81 100644--- a/packages/core/src/tools/analyze/diff/apply.ts+++ b/packages/core/src/tools/analyze/diff/apply.ts@@ -219,7 +219,8 @@ type Placed = Plan & { place: Placement }* is committed, so a patch never half-applies.*/async function renderAdditions(figma: FigmaAPI, plans: Placed[]): Promise<boolean> {- const { renderJSX } = await import('#core/design-jsx')+ const { designJSXRenderer } = await import('#core/design-jsx')+ const { renderJSX } = designJSXRenderer(figma.icons)const rendered: string[] = []for (const plan of plans) {const { jsx, parentId } = plan.placediff --git a/packages/core/src/tools/create/icons.ts b/packages/core/src/tools/create/icons.tsindex 1ac5156cc..eb3875281 100644--- a/packages/core/src/tools/create/icons.ts+++ b/packages/core/src/tools/create/icons.ts@@ -2,8 +2,7 @@ import * as v from 'valibot'import { parseColor } from '@open-pencil/scene-graph/color'-import { fetchIcons, searchIconsBatch } from '#core/icons'-import { createIconFromPaths } from '#core/icons/render'+import { placeIcon } from '#core/icons'import { toolNumber } from '#core/tools/input'import { defineTool } from '#core/tools/schema'@@ -24,10 +23,10 @@ export const fetchIconsTool = defineTool({toolNumber(v.pipe(v.number(), v.description('Icon size in pixels (default: 24)'))))}),- execute: async (_figma, args) => {+ execute: async (figma, args) => {const size = args.size ?? 24try {- const icons = await fetchIcons(args.names, size)+ const icons = await figma.icons.icons(args.names, size)const fetched = [...icons.keys()]const notFound = args.names.filter((name) => !icons.has(name))const result: Record<string, unknown> = { fetched, count: fetched.length }@@ -77,7 +76,7 @@ export const insertIcon = defineTool({let iconstry {- icons = await fetchIcons(names, size)+ icons = await figma.icons.icons(names, size)} catch (e) {return { error: (e as Error).message }}@@ -92,7 +91,7 @@ export const insertIcon = defineTool({continue}const parentId = args.parent_id ?? figma.currentPage.id- const frame = createIconFromPaths(figma.graph, icon, name, size, parsedColor, parentId)+ const frame = placeIcon(figma.graph, parentId, icon, { size, color: parsedColor })inserted.push({ id: frame.id, name: frame.name, icon: name })}@@ -126,17 +125,17 @@ export const searchIconsTool = defineTool({v.pipe(v.string(), v.description('Filter by icon set prefix (e.g. "lucide", "mdi")')))}),- execute: async (_figma, args) => {+ execute: async (figma, args) => {try {- const results = await searchIconsBatch(args.queries, {- limit: args.limit ?? 5,- prefix: args.prefix- })- const output: Record<string, { icons: string[]; total: number }> = {}- for (const [query, result] of results) {- output[query] = { icons: result.icons, total: result.total }- }- return output+ const options = { limit: args.limit ?? 5, prefix: args.prefix }+ const results = await Promise.all(+ args.queries.map(+ async (query) => [query, await figma.icons.search(query, options)] as const+ )+ )+ return Object.fromEntries(+ results.map(([query, result]) => [query, { icons: result.icons, total: result.total }])+ )} catch (e) {return { error: (e as Error).message }}diff --git a/packages/core/src/tools/create/render.ts b/packages/core/src/tools/create/render.tsindex 98198b93f..f1a565e75 100644--- a/packages/core/src/tools/create/render.ts+++ b/packages/core/src/tools/create/render.ts@@ -33,7 +33,8 @@ export const render = defineTool({jsx: v.pipe(v.string(), v.description('JSX string to render'))}),execute: async (figma, args) => {- const { renderJSX } = await import('#core/design-jsx')+ const { designJSXRenderer } = await import('#core/design-jsx')+ const { renderJSX } = designJSXRenderer(figma.icons)const placement = resolveRenderPlacement(figma.graph, args, figma.currentPageId)const results = await renderJSX(figma.graph, args.jsx, placement)diff --git a/packages/core/src/tools/structure/replace.ts b/packages/core/src/tools/structure/replace.tsindex b6c184178..9e9fa61f2 100644--- a/packages/core/src/tools/structure/replace.ts+++ b/packages/core/src/tools/structure/replace.ts@@ -18,7 +18,8 @@ export const nodeReplaceWith = defineTool({const x = node.xconst y = node.ynode.remove()- const { renderJSX } = await import('#core/design-jsx')+ const { designJSXRenderer } = await import('#core/design-jsx')+ const { renderJSX } = designJSXRenderer(figma.icons)const results = await renderJSX(figma.graph, args.jsx, { parentId, x, y })const result = results[0]return {diff --git a/packages/core/tests/editor/icons.test.ts b/packages/core/tests/editor/icons.test.tsnew file mode 100644index 000000000..557b9bad3--- /dev/null+++ b/packages/core/tests/editor/icons.test.ts@@ -0,0 +1,156 @@+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 type { Color } from '@open-pencil/scene-graph/primitives'++import { buildIconData } from '#core/icons/svg'++import { getNodeOrThrow } from '../helpers/assert'++const RED: Color = { r: 1, g: 0, b: 0, a: 1 }++const BODIES: Record<string, string> = {+ 'test:square': '<path fill="currentColor" d="M2 2h20v20H2z"/>',+ 'test:lines': '<path fill="none" stroke="currentColor" d="M4 4h16M4 12h16"/>'+}++/** Icons drawn from fixed bodies, so the commands run without the network. */+const provider: IconProvider = {+ search: async () => ({ icons: Object.keys(BODIES), total: 2, collections: {} }),+ collections: async () => [],+ browse: async () => Object.keys(BODIES),+ previews: async (names) =>+ new Map(names.flatMap((name) => (BODIES[name] ? [[name, `<svg>${BODIES[name]}</svg>`]] : []))),+ async icons(names, size) {+ const found = new Map()+ for (const name of names) {+ const parsed = parseIconName(name)+ const body = BODIES[name]+ if (parsed && body)+ found.set(name, buildIconData({ body }, parsed.prefix, parsed.iconName, 24, 24, size))+ }+ return found+ }+}++function setup() {+ const editor = createEditor({+ getViewportSize: () => ({ width: 1000, height: 800 }),+ icons: provider+ })+ editor.state.panX = 100+ editor.state.panY = 50+ editor.state.zoom = 2+ return editor+}++/** Inserts an icon that must be placed, as it is when the document stays the same. */+async function insert(editor: ReturnType<typeof setup>, name: string, color?: Color) {+ const id = await editor.insertIcon(name, color)+ if (!id) throw new Error(`Icon "${name}" was not inserted`)+ return id+}++describe('icon commands', () => {+ test('insert places the icon at the middle of the view, selected, in one undo step', async () => {+ const editor = setup()+ const id = await insert(editor, 'test:square')+ const frame = getNodeOrThrow(editor.graph, id)++ 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(editor.state.selectedIds).toEqual(new Set([id]))++ editor.undo.undo()+ expect(editor.graph.getNode(id)).toBeUndefined()+ expect(editor.state.selectedIds).toEqual(new Set())++ editor.undo.redo()+ expect(readIcon(getNodeOrThrow(editor.graph, id))).toEqual({ name: 'test:square' })+ expect(editor.graph.getChildren(id)).toHaveLength(1)+ })++ test('insert places the icon inside the container being edited', async () => {+ const editor = setup()+ const containerId = editor.createShape('FRAME', 100, 100, 400, 400)+ editor.state.enteredContainerId = containerId+ const frame = getNodeOrThrow(editor.graph, await insert(editor, 'test:square'))++ expect(frame.parentId).toBe(containerId)+ expect(frame).toMatchObject({ x: 88, y: 63 })+ })++ test('insert rejects a name the provider lacks', async () => {+ const editor = setup()+ await expect(editor.insertIcon('test:missing')).rejects.toThrow('not found')+ })++ test('swap draws another glyph in place and undo brings the old one back', async () => {+ const editor = setup()+ const id = await insert(editor, 'test:square', RED)+ const before = editor.graph.getChildren(id).map((path) => path.id)++ 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(editor.graph.getChildren(id)[0]?.strokes[0]?.color).toEqual(RED)++ editor.undo.undo()+ expect(readIcon(getNodeOrThrow(editor.graph, id))).toEqual({ 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' })+ })++ test('swap keeps the icon at its place among its siblings', async () => {+ const editor = setup()+ const id = await insert(editor, 'test:square')+ const after = editor.createShape('RECTANGLE', 0, 0, 10, 10)+ const pageId = editor.state.currentPageId++ await editor.swapIconGlyph(id, 'test:lines')+ editor.undo.undo()+ expect(getNodeOrThrow(editor.graph, pageId).childIds).toEqual([id, after])+ })++ test('color recolors the tinted paths in one undo step', async () => {+ const editor = setup()+ const id = await insert(editor, 'test:square')+ const pathId = editor.graph.getChildren(id)[0]?.id ?? ''++ editor.setIconColor(id, RED)+ expect(getNodeOrThrow(editor.graph, pathId).fills[0]?.color).toEqual(RED)++ editor.undo.undo()+ expect(getNodeOrThrow(editor.graph, pathId).fills[0]?.color).toMatchObject({ r: 0, g: 0, b: 0 })+ })+})++describe('icon commands across a document change', () => {+ test('an icon still loading when the document is replaced is not inserted into the new one', async () => {+ let release: (() => void) | undefined+ const loaded = new Promise<void>((resolve) => {+ release = resolve+ })+ const slow: IconProvider = {+ ...provider,+ async icons(names, size) {+ await loaded+ return provider.icons(names, size)+ }+ }+ const editor = createEditor({ getViewportSize: () => ({ width: 1000, height: 800 }), icons: slow })+ const inserting = editor.insertIcon('test:square')+ const replacement = new SceneGraph()+ editor.replaceGraph(replacement)+ release?.()++ expect(await inserting).toBeNull()+ expect([...replacement.getAllNodes()].some((node) => readIcon(node))).toBe(false)+ })+})diff --git a/packages/core/tests/icons/provider.test.ts b/packages/core/tests/icons/provider.test.tsnew file mode 100644index 000000000..5c3c617b0--- /dev/null+++ b/packages/core/tests/icons/provider.test.ts@@ -0,0 +1,139 @@+import { describe, expect, test } from 'bun:test'++import { createIconifyAPIClient } from '#core/icons/api'+import { createIconifyProvider } from '#core/icons/provider'++const SET = {+ prefix: 'test',+ width: 24,+ height: 24,+ icons: {+ square: { body: '<path fill="currentColor" d="M2 2h20v20H2z"/>' },+ wide: { body: '<path fill="currentColor" d="M0 0h32v16H0z"/>', width: 32, height: 16 }+ },+ aliases: { box: { parent: 'square' } }+}++const CATALOGUE = {+ test: { name: 'Test Icons', total: 3, category: 'General', license: { title: 'MIT' } },+ logos: { name: 'Logos', total: 9, palette: true },+ retired: { name: 'Retired', total: 1, hidden: true }+}++const LIST = {+ uncategorized: ['square'],+ categories: { Shapes: ['wide', 'square'], Boxes: ['box'] }+}++/**+ * A provider over a fake API that serves `SET`, `CATALOGUE`, and `LIST`, counting its requests.+ * `failing` lists paths that answer 500 until removed.+ */+function setup() {+ const requests: string[] = []+ const failing = new Set<string>()+ const fetcher = async (input: RequestInfo | URL) => {+ const url = new URL(input instanceof Request ? input.url : input)+ requests.push(url.pathname + url.search)+ if (failing.has(url.pathname)) return new Response('', { status: 500 })+ if (url.pathname === '/collections') return Response.json(CATALOGUE)+ if (url.pathname === '/collection') return Response.json(LIST)+ return Response.json(SET)+ }+ const provider = createIconifyProvider(+ createIconifyAPIClient(fetcher as typeof fetch, 'https://icons.test')+ )+ return { provider, requests, failing }+}++describe('Iconify provider', () => {+ test('previews draw each icon in its own box, with the color left to the page', async () => {+ const { provider } = setup()+ const previews = await provider.previews(['test:square', 'test:wide', 'test:box', 'test:gone'])++ expect([...previews.keys()]).toEqual(['test:square', 'test:wide', 'test:box'])+ expect(previews.get('test:wide')).toContain('viewBox="0 0 32 16"')+ expect(previews.get('test:square')).toContain('fill="currentColor"')+ expect(previews.get('test:box')).toBe(previews.get('test:square'))+ })++ test('previews and placed icons share one request per set', async () => {+ const { provider, requests } = setup()+ await provider.previews(['test:square', 'test:wide'])+ const icons = await provider.icons(['test:square', 'test:wide'], 48)++ expect(requests).toHaveLength(1)+ expect(icons.get('test:wide')).toMatchObject({ name: 'wide', width: 48 })+ })++ test('a long list of names is split over several requests', async () => {+ const { provider, requests } = setup()+ const names = Array.from({ length: 250 }, (_, index) => `test:icon-${index}`)+ await provider.previews(names)++ expect(requests).toHaveLength(3)+ })++ test('overlapping loads share requests, and a name the set lacks is not asked for again', async () => {+ const { provider, requests } = setup()+ await Promise.all([+ provider.previews(['test:square', 'test:gone']),+ provider.icons(['test:square'], 24)+ ])+ await provider.previews(['test:gone'])++ expect(requests).toHaveLength(1)+ })++ test('a failed load is asked for again', async () => {+ const { provider, requests, failing } = setup()+ failing.add('/test.json')+ await expect(provider.previews(['test:square'])).rejects.toThrow('500')++ failing.clear()+ expect((await provider.previews(['test:square'])).has('test:square')).toBe(true)+ expect(requests).toHaveLength(2)+ })++ test('a name without a set is refused', async () => {+ const { provider } = setup()+ await expect(provider.previews(['square'])).rejects.toThrow('prefix:name')+ })++ test('the set catalogue leaves out retired sets and is loaded once', async () => {+ const { provider, requests } = setup()+ const sets = await provider.collections()+ await provider.collections()++ expect(sets).toEqual([+ {+ prefix: 'test',+ name: 'Test Icons',+ total: 3,+ category: 'General',+ license: 'MIT',+ multicolor: false+ },+ { prefix: 'logos', name: 'Logos', total: 9, category: null, license: null, multicolor: true }+ ])+ expect(requests).toEqual(['/collections'])+ })++ test('browsing lists every icon in a set once, loose ones first', async () => {+ const { provider, requests } = setup()+ const names = await provider.browse('test')+ await provider.browse('test')++ expect(names).toEqual(['test:square', 'test:wide', 'test:box'])+ expect(requests).toEqual(['/collection?prefix=test'])+ })++ test('a failed catalogue is asked for again', async () => {+ const { provider, failing } = setup()+ failing.add('/collections')+ await expect(provider.collections()).rejects.toThrow('500')++ failing.clear()+ expect(await provider.collections()).toHaveLength(2)+ })+})diff --git a/packages/core/tests/icons/render.test.ts b/packages/core/tests/icons/render.test.tsindex f1c17b31d..d69b27e01 100644--- a/packages/core/tests/icons/render.test.ts+++ b/packages/core/tests/icons/render.test.ts@@ -9,10 +9,10 @@ import {parseFigFile,renderNodesToImage} from '@open-pencil/core/io'-import { SceneGraph } from '@open-pencil/scene-graph'+import { readIcon, readIconTint, SceneGraph } from '@open-pencil/scene-graph'import { parseColor } from '@open-pencil/scene-graph/color'-import { createIconFromPaths } from '#core/icons/render'+import { iconColor, placeIcon, recolorIcon, swapIcon } from '#core/icons/render'import { buildIconData } from '#core/icons/svg'const BLACK = parseColor('#000000')@@ -20,11 +20,11 @@ const BLACK = parseColor('#000000')function insertIcon(graph: SceneGraph, body: string, viewBox = 24, size = 24) {const icon = buildIconData({ body }, 'test', 'icon', viewBox, viewBox, size)const page = graph.getPages()[0]- const frame = createIconFromPaths(graph, icon, 'test:icon', size, BLACK, page.id)+ const frame = placeIcon(graph, page.id, icon, { size, color: BLACK })return { page, frame, vectors: graph.getChildren(frame.id) }}-describe('createIconFromPaths', () => {+describe('placeIcon', () => {test('keeps round stroke caps and joins after a .fig round trip', async () => {const graph = new SceneGraph()insertIcon(@@ -88,3 +88,54 @@ describe('createIconFromPaths', () => {}})})++describe('icon identity', () => {+ /** A two-path icon: one drawn in the icon's color, one in a fixed red. */+ const BODY =+ '<path fill="currentColor" d="M0 0h12v12H0z"/><path fill="#ff0000" d="M12 12h12v12H12z"/>'++ 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(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' })+ })++ test("recolors only the paths drawn in the icon's color", () => {+ const graph = new SceneGraph()+ const { frame } = insertIcon(graph, BODY)+ const blue = parseColor('#0000ff')+ recolorIcon(graph, frame.id, blue)+ const [tinted, fixed] = graph.getChildren(frame.id)+ expect(tinted?.fills[0]?.color).toEqual(blue)+ expect(fixed?.fills[0]?.color).toEqual(parseColor('#ff0000'))+ expect(iconColor(graph, frame)).toEqual(blue)+ })++ test('swaps the glyph, keeping the frame, its size, and its color', () => {+ const graph = new SceneGraph()+ const { frame } = insertIcon(graph, BODY, 24, 32)+ const green = parseColor('#00ff00')+ recolorIcon(graph, frame.id, green)+ const other = buildIconData({ body: '<path fill="currentColor" d="M0 0h24v24H0z"/>' }, 'test', 'square', 24, 24, 32)+ swapIcon(graph, frame.id, other)++ const swapped = expectDefined(graph.getNode(frame.id), 'swapped icon')+ expect(readIcon(swapped)).toEqual({ name: 'test:square' })+ expect([swapped.width, swapped.height]).toEqual([32, 32])+ const paths = graph.getChildren(frame.id)+ expect(paths).toHaveLength(1)+ expect(paths[0]?.fills[0]?.color).toEqual(green)+ })++ test('leaves artwork without a name in a set unnamed', () => {+ const graph = new SceneGraph()+ const icon = buildIconData({ body: BODY }, 'svg', 'custom', 24, 24, 24)+ const frame = placeIcon(graph, graph.getPages()[0].id, icon, { size: 24, color: BLACK, identity: false })+ expect(readIcon(frame)).toBeNull()+ })+})diff --git a/packages/core/tests/io/formats/html/vectors.test.ts b/packages/core/tests/io/formats/html/vectors.test.tsindex 5e9aa9d5b..24773123e 100644--- a/packages/core/tests/io/formats/html/vectors.test.ts+++ b/packages/core/tests/io/formats/html/vectors.test.ts@@ -1,7 +1,10 @@import { describe, expect, test } from 'bun:test'import { SceneGraph, type Fill } from '@open-pencil/scene-graph'+import { parseColor } from '@open-pencil/scene-graph/color'+import { placeIcon } from '#core/icons/render'+import { buildIconData } from '#core/icons/svg'import { renderNodesToHTML } from '#core/io/formats/html'const gradient: Fill = {@@ -63,3 +66,21 @@ describe('vector layers in HTML export', () => {expect(html).toMatch(/<svg width="120" height="1" viewBox="0 0 120 1"/)})})++describe('icons in HTML export', () => {+ test('draw as one SVG named by the icon, recolored through CSS color', async () => {+ const graph = new SceneGraph()+ const frame = graph.createNode('FRAME', graph.getPages()[0].id, { name: 'Card', width: 100, height: 100 })+ const body = '<path fill="currentColor" d="M0 0h12v12H0z"/><path fill="#ff0000" d="M12 12h12v12H12z"/>'+ const icon = buildIconData({ body }, 'test', 'icon', 24, 24, 24)+ placeIcon(graph, frame.id, icon, { size: 24, color: parseColor('#4f46e5') })++ const { html } = await renderNodesToHTML(graph, [frame.id])+ expect(html.match(/<svg/g)?.length).toBe(1)+ expect(html).toContain('data-icon="test:icon"')+ expect(html).toMatch(/<svg[^>]*style="[^"]*color: #4F46E5/)+ // The tinted path follows the color; the red one keeps its own.+ expect(html).toContain('fill="currentColor"')+ expect(html).toContain('fill="#FF0000"')+ })+})diff --git a/packages/design-jsx/src/export/icons.ts b/packages/design-jsx/src/export/icons.tsnew file mode 100644index 000000000..fccadb0d3--- /dev/null+++ b/packages/design-jsx/src/export/icons.ts@@ -0,0 +1,35 @@+import { 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)) {+ const tint = readIconTint(path)+ const paint = tint.includes('fill') ? path.fills[0] : undefined+ const stroke = tint.includes('stroke') ? path.strokes[0] : undefined+ const color = paint?.color ?? stroke?.color+ if (color) return colorToHex(color)+ }+ return 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.+ */+export function iconProps(node: SceneNode, graph: SceneGraph): JSXProp[] | null {+ const icon = readIcon(node)+ if (!icon) 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] : [])+ ]+}diff --git a/packages/design-jsx/src/export/index.ts b/packages/design-jsx/src/export/index.tsindex e385a4702..2ae56b0b7 100644--- a/packages/design-jsx/src/export/index.ts+++ b/packages/design-jsx/src/export/index.ts@@ -4,6 +4,7 @@ import { jsx, type SyntaxNode } from '@open-pencil/emit'import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'import { rekaExport, type RekaExport } from './behaviours'+import { iconProps } from './icons'import { collectProps, NODE_TYPE_TO_TAG, type JSXProp } from './props'import { valueSyntax } from './value'@@ -57,6 +58,12 @@ function nodeToJSX(.getChildren(node.id).flatMap((child) => nodeToJSX(child, graph, childDepth, layerIds, reka))if (reka.flatten.has(node.id)) return children(depth)+ // An icon is written by name; its paths are the icon set's to draw again.+ const icon = iconProps(node, graph)+ if (icon) {+ layerIds?.push(node.id)+ return [jsx.element('Icon', icon.map(propAttribute), [], depth)]+ }const tag = reka.tags.get(node.id) ?? NODE_TYPE_TO_TAG[node.type]if (!tag) return []layerIds?.push(node.id)diff --git a/packages/design-jsx/tests/export/icons.test.ts b/packages/design-jsx/tests/export/icons.test.tsnew file mode 100644index 000000000..edc1fcc87--- /dev/null+++ b/packages/design-jsx/tests/export/icons.test.ts@@ -0,0 +1,41 @@+import { describe, expect, test } from 'bun:test'++import { sceneNodeToJSX } from '#design-jsx/export/index'++import { 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',+ width: 20,+ height: 20+ })+ graph.updateNode(frame.id, { pluginData: withIcon(frame, { name: 'lucide:home' }) })+ const path = graph.createNode('VECTOR', frame.id, {+ name: 'path',+ width: 20,+ height: 20,+ fills: [{ type: 'SOLID', color, opacity: 1, visible: true }]+ })+ graph.updateNode(path.id, { pluginData: withIconTint(path, ['fill']) })+ return { graph, frame }+}++describe('icons in design JSX export', () => {+ test('write the icon by name, with its size and color, not its paths', () => {+ const { graph, frame } = iconFrame({ r: 79 / 255, g: 70 / 255, b: 229 / 255, a: 1 })+ expect(sceneNodeToJSX(frame.id, graph)).toBe(+ '<Icon name="lucide:home" size={20} color="#4F46E5" />'+ )+ })++ test('leave out black, the default color, and keep a layer name someone gave it', () => {+ const { graph, frame } = iconFrame({ r: 0, g: 0, b: 0, a: 1 }, 'Home')+ expect(sceneNodeToJSX(frame.id, graph)).toBe(+ '<Icon name="lucide:home" size={20} label="Home" />'+ )+ })+})diff --git a/packages/docs/.vitepress/labels.ts b/packages/docs/.vitepress/labels.tsindex a3cd12534..1aa81cfab 100644--- a/packages/docs/.vitepress/labels.ts+++ b/packages/docs/.vitepress/labels.ts@@ -9,6 +9,7 @@ export interface SidebarLabels {text: stringpen: stringvectorEditing: string+ icons: stringlayers: stringcontextMenu: stringexporting: string@@ -167,6 +168,7 @@ export const EN: SidebarLabels = {components: 'Components',variables: 'Variables',checkingDesigns: 'Checking Designs',+ icons: 'Icons',overview: 'Overview',gettingStarted: 'Getting Started',features: 'Features',@@ -193,6 +195,7 @@ export const DE: SidebarLabels = {components: 'Komponenten',variables: 'Variablen',checkingDesigns: 'Designs prüfen',+ icons: 'Symbole',overview: 'Überblick',gettingStarted: 'Erste Schritte',features: 'Funktionen',@@ -219,6 +222,7 @@ export const IT: SidebarLabels = {components: 'Componenti',variables: 'Variabili',checkingDesigns: 'Verificare i design',+ icons: 'Icone',overview: 'Panoramica',gettingStarted: 'Per iniziare',features: 'Funzionalità',@@ -245,6 +249,7 @@ export const FR: SidebarLabels = {components: 'Composants',variables: 'Variables',checkingDesigns: 'Vérifier les designs',+ icons: 'Icônes',overview: 'Vue d’ensemble',gettingStarted: 'Premiers pas',features: 'Fonctionnalités',@@ -271,6 +276,7 @@ export const ES: SidebarLabels = {components: 'Componentes',variables: 'Variables',checkingDesigns: 'Revisar diseños',+ icons: 'Iconos',overview: 'Resumen',gettingStarted: 'Primeros pasos',features: 'Características',@@ -297,6 +303,7 @@ export const PL: SidebarLabels = {components: 'Komponenty',variables: 'Zmienne',checkingDesigns: 'Sprawdzanie projektów',+ icons: 'Ikony',overview: 'Przegląd',gettingStarted: 'Rozpoczęcie pracy',features: 'Funkcje',@@ -323,6 +330,7 @@ export const RU: SidebarLabels = {components: 'Компоненты',variables: 'Переменные',checkingDesigns: 'Проверка дизайна',+ icons: 'Иконки',overview: 'Обзор',gettingStarted: 'Начало работы',features: 'Возможности',diff --git a/packages/docs/.vitepress/sidebars.ts b/packages/docs/.vitepress/sidebars.tsindex 70ce3e930..f9bd4ff10 100644--- a/packages/docs/.vitepress/sidebars.ts+++ b/packages/docs/.vitepress/sidebars.ts@@ -31,6 +31,8 @@ export const userGuideSidebar = ({ text: labels.text, link: `${prefix}/user-guide/text-editing` },{ text: labels.pen, link: `${prefix}/user-guide/pen-tool` },{ text: labels.vectorEditing, link: `${prefix}/user-guide/vector-edit` },+ // English only until translated; locales link to the canonical page.+ { text: labels.icons, link: '/user-guide/icons' },],},{diff --git a/packages/docs/programmable/sdk/getting-started.md b/packages/docs/programmable/sdk/getting-started.mdindex 7a1c107bf..b336a7107 100644--- a/packages/docs/programmable/sdk/getting-started.md+++ b/packages/docs/programmable/sdk/getting-started.md@@ -51,6 +51,8 @@ const editor = createEditor({Core state is framework-neutral; passing reactive state lets Vue controls observe editor changes. For a resizable editor, have `getViewportSize` return the current canvas container dimensions. `width` and `height` are not `EditorOptions` properties.+Icons come from Iconify by default. To serve them from elsewhere, such as a bundled or self-hosted set, pass an `IconProvider` from `@open-pencil/core/icons` as `icons`; the editor's commands, its icon picker, and its AI tools all use it.+### 2. Provide it to Vue```vuediff --git a/packages/docs/user-guide/icons.md b/packages/docs/user-guide/icons.mdnew file mode 100644index 000000000..9fc942e8e--- /dev/null+++ b/packages/docs/user-guide/icons.md@@ -0,0 +1,47 @@+---+title: Icons+description: Search open-source icon sets, insert icons, and swap or recolor them in OpenPencil.+---++# Icons++OpenPencil searches the open-source icon sets published through [Iconify](https://iconify.design), such as Lucide, Material Symbols, Tabler, and Phosphor. A placed icon remembers which icon it is, so you can swap it for another or change its color later, and exports write it as that icon.++Searching and placing icons needs a network connection to the Iconify API.++## Inserting an Icon++Open the icon picker in any of these ways:++- Click the **Insert icon** button at the end of the toolbar+- Choose **Object → Insert Icon…**+- Search for **Insert Icon** in the command palette (<kbd>⌘</kbd><kbd>K</kbd>)++Before you type, the picker shows the icons already placed in this file and the ones you picked lately. Type what you're looking for, such as `arrow` or `heart`, to search every set; each result shows a preview and the set it comes from.++Pick one to place it, 24 × 24, in the middle of the view, inside the frame you're editing if you've entered one. The new icon is selected, and <kbd>⌘</kbd><kbd>Z</kbd> removes it in one step.++## Choosing an Icon Set++The set button at the end of the search field (**All icon sets** at first) narrows the picker to one set. Sets are grouped by kind, such as Material or Logos; type to find one by name, such as `tabler`. Each set shows how many icons it has.++With a set chosen, the picker shows the whole set, loading more as you scroll, and a search looks only in that set. Hover over an icon, or move to it with the arrow keys, to see its name, set, and license below the grid. The picker remembers the set you chose last, and **Swap icon** opens on the set of the icon you're swapping.++## The Icon Section++Selecting a placed icon adds an **Icon** section to the Design panel.++- **Swap icon** opens the picker and draws the chosen icon in place of the current one. The icon keeps its size, position, and color.+- **Icon color** changes the color of the icon's own paths. Icons drawn in several fixed colors, such as brand logos, keep those colors and don't show this field.++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.++## Icons in Exports++- **Design JSX** writes a placed icon as `<Icon name="lucide:heart" size={24} color="#…" />`.+- **HTML** writes it as inline SVG marked with `data-icon`, with its paths painted in `currentColor` and the icon's color set on the `<svg>`, so changing that one `color` recolors it.+- **SVG and images** draw it like any other vector.++Icons placed by AI agents, MCP clients, and design JSX are icons in the same way, so the Icon section works on them too.diff --git a/packages/docs/user-guide/index.md b/packages/docs/user-guide/index.mdindex 5f49a8775..5cda1bde5 100644--- a/packages/docs/user-guide/index.md+++ b/packages/docs/user-guide/index.md@@ -22,6 +22,7 @@ Throughout this guide, keyboard shortcuts use Mac notation: <kbd>⌘</kbd> = <kb- [Drawing Shapes](./drawing-shapes) — rectangles, ellipses, lines, frames, sections, polygons, and stars- [Text Editing](./text-editing) — creating and editing text with rich formatting- [Pen Tool](./pen-tool) — drawing vector paths with bezier curves+- [Icons](./icons) — searching icon sets, inserting icons, and swapping or recoloring them## Organizing & Managingdiff --git a/packages/dom-css/src/export/projection.ts b/packages/dom-css/src/export/projection.tsindex 9dbfd2688..0e5b4dd85 100644--- a/packages/dom-css/src/export/projection.ts+++ b/packages/dom-css/src/export/projection.ts@@ -1,6 +1,11 @@import { fromUint8Array } from 'js-base64'-import { layoutSizingInParent, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'+import {+ layoutSizingInParent,+ readIcon,+ type SceneGraph,+ type SceneNode+} from '@open-pencil/scene-graph'import { BLACK } from '@open-pencil/scene-graph/constants'import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text-direction'@@ -23,7 +28,7 @@ export interface SceneGraphToDesignOptions {includeSourceIds?: boolean/** Write variable-bound values as `var(--name)` where CSS resolves them as drawn. Default true. */tokens?: boolean- /** Vector, boolean, star, and polygon layers as inline SVG; without it they project as boxes. */+ /** Vector, boolean, star, polygon, and icon layers as inline SVG; without it they project as boxes. */vectorElement?: VectorElementRenderer}@@ -414,7 +419,8 @@ function sceneNodeToDesignNode(}}- if (VECTOR_SHAPES.has(node.type)) {+ // An icon is one drawing, however many paths it has.+ if (VECTOR_SHAPES.has(node.type) || readIcon(node)) {const vector = vectorDesignNode(context, node, attrs, styleFromSceneNode(node, parent, css))if (vector) return vector}diff --git a/packages/scene-graph/src/icons/model.ts b/packages/scene-graph/src/icons/model.tsnew file mode 100644index 000000000..ebc015626--- /dev/null+++ b/packages/scene-graph/src/icons/model.ts@@ -0,0 +1,41 @@+import { readPluginData, withPluginData } from '../plugin-data/field'+import { OPEN_PENCIL_PLUGIN_DATA } from '../plugin-data/fields'+import type { SceneNode } from '../types'+import type { Icon, IconPaint } from './schema'++/** The icon a frame draws, or null when it is not an icon or its data is unreadable. */+export function readIcon(node: SceneNode): Icon | null {+ return readPluginData(node.pluginData, OPEN_PENCIL_PLUGIN_DATA.icon) ?? null+}++/** The node's plugin data with the icon set, or removed when null. */+export function withIcon(node: SceneNode, icon: Icon | null): SceneNode['pluginData'] {+ return withPluginData(node.pluginData, OPEN_PENCIL_PLUGIN_DATA.icon, icon ?? undefined)+}++/** 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>()+ for (const node of nodes) {+ const icon = readIcon(node)+ if (icon) names.add(icon.name)+ }+ return [...names]+}++/** The paints of an icon path that its icon's color sets; none when it keeps its own colors. */+export function readIconTint(node: SceneNode): readonly IconPaint[] {+ return readPluginData(node.pluginData, OPEN_PENCIL_PLUGIN_DATA.iconTint) ?? []+}++/** The path's plugin data with its tinted paints, or removed when there are none. */+export function withIconTint(+ node: SceneNode,+ paints: readonly IconPaint[]+): SceneNode['pluginData'] {+ return withPluginData(+ node.pluginData,+ OPEN_PENCIL_PLUGIN_DATA.iconTint,+ paints.length > 0 ? [...paints] : undefined+ )+}diff --git a/packages/scene-graph/src/icons/schema.ts b/packages/scene-graph/src/icons/schema.tsnew file mode 100644index 000000000..63c7670bd--- /dev/null+++ b/packages/scene-graph/src/icons/schema.ts@@ -0,0 +1,14 @@+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)) })++/** An icon a frame draws. */+export type Icon = v.InferOutput<typeof iconSchema>++export const ICON_PAINTS = ['fill', 'stroke'] as const+export type IconPaint = (typeof ICON_PAINTS)[number]++export const iconTintSchema = v.pipe(v.array(v.picklist(ICON_PAINTS)), v.minLength(1))diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.tsindex 60e8a476d..3b39085ca 100644--- a/packages/scene-graph/src/index.ts+++ b/packages/scene-graph/src/index.ts@@ -27,6 +27,8 @@ export * from './slots/content'export * from './slots/authoring'export * from './slots/limits'export * from './behaviours/kinds'+export * from './icons/schema'+export * from './icons/model'export * from './behaviours/layers'export * from './behaviours/model'export * from './behaviours/spec'diff --git a/packages/scene-graph/src/plugin-data/fields.ts b/packages/scene-graph/src/plugin-data/fields.tsindex 2448fff25..d78fcea9a 100644--- a/packages/scene-graph/src/plugin-data/fields.ts+++ b/packages/scene-graph/src/plugin-data/fields.ts@@ -4,6 +4,7 @@ import { behaviourSchema } from '../behaviours/schema'import type { OkHCLPayload } from '../color/okhcl'import { isExportFormatId, type ExportFormatId } from '../export-format'import { clampExportScale } from '../export-scale'+import { iconSchema, iconTintSchema } from '../icons/schema'import type { Rect } from '../primitives'import {MODE_ATTRIBUTE_PATTERN,@@ -169,7 +170,11 @@ export const OPEN_PENCIL_PLUGIN_DATA = {/** One entry per paint picked in OkHCL, so the picker reopens on the same coordinates. */okhcl: jsonPluginDataField('okhcl', 'content', okhcl),/** How a main component or component set behaves as a control in preview. */- behaviour: jsonPluginDataField('behaviour', 'content', behaviourSchema)+ behaviour: jsonPluginDataField('behaviour', 'content', behaviourSchema),+ /** The icon a frame draws, such as `lucide:home`, on the frame its paths are in. */+ icon: jsonPluginDataField('icon', 'content', iconSchema),+ /** Which of an icon path's paints its icon's color sets, on each path the source drew in it. */+ iconTint: jsonPluginDataField('iconTint', 'content', iconTintSchema)} satisfies Record<string, PluginDataKey>const NOT_CONTENT = Object.values(OPEN_PENCIL_PLUGIN_DATA).filter(diff --git a/packages/scene-graph/tests/icons/model.test.ts b/packages/scene-graph/tests/icons/model.test.tsnew file mode 100644index 000000000..00f074003--- /dev/null+++ b/packages/scene-graph/tests/icons/model.test.ts@@ -0,0 +1,23 @@+import { describe, expect, test } from 'bun:test'++import { iconNames, SceneGraph, withIcon } from '@open-pencil/scene-graph'++function icon(graph: SceneGraph, parentId: string, name: string) {+ const frame = graph.createNode('FRAME', parentId, { name: `Icon / ${name}` })+ graph.updateNode(frame.id, { pluginData: withIcon(frame, { name }) })+ return frame+}++describe('iconNames', () => {+ test('lists each placed icon once, in the order met, across frames', () => {+ const graph = new SceneGraph()+ const pageId = graph.getPages()[0].id+ const card = graph.createNode('FRAME', pageId, { name: 'Card' })+ icon(graph, pageId, 'lucide:heart')+ icon(graph, card.id, 'mdi:home')+ icon(graph, card.id, 'lucide:heart')+ graph.createNode('RECTANGLE', pageId, { name: 'Icon / lucide:star' })++ expect(iconNames(graph.getAllNodes())).toEqual(['lucide:heart', 'mdi:home'])+ })+})diff --git a/packages/vue/src/controls/icon/search.ts b/packages/vue/src/controls/icon/search.tsnew file mode 100644index 000000000..313f93af3--- /dev/null+++ b/packages/vue/src/controls/icon/search.ts@@ -0,0 +1,172 @@+import { tryOnScopeDispose, watchDebounced } from '@vueuse/core'+import { computed, ref, shallowRef, watch } from 'vue'++import type { IconCollection } from '@open-pencil/core/icons'++import { useEditor } from '#vue/editor/context'++const SEARCH_DEBOUNCE_MS = 250+/** Hits for a search over every set; the Iconify API returns no fewer than 32. */+const SEARCH_LIMIT = 64+/** Hits for a search within one set, which a grid can show many of; the API's most. */+const SET_SEARCH_LIMIT = 999+/** Icons shown at first and added each time the list nears its end. */+const PAGE_SIZE = 96++/**+ * Searches the editor's icon provider as `query` and `set` change, keeping only the latest+ * answer. With a set chosen and no query, it lists the whole set. Previews are drawn for what is+ * shown, a page at a time.+ */+export function useIconSearch() {+ const editor = useEditor()+ const provider = () => editor.iconProvider+ const query = ref('')+ /** The set to search or browse, by prefix; null searches every set. */+ const set = ref<string | null>(null)+ /** The icon names found, or null before anything is asked. */+ const results = shallowRef<string[] | null>(null)+ /**+ * The search filled its limit, so more icons match than were returned; Iconify reports only+ * how many it returned, not how many match.+ */+ const capped = ref(false)+ const loading = ref(false)+ const failed = ref(false)+ const shown = ref(PAGE_SIZE)+ let version = 0++ const sets = shallowRef<IconCollection[]>([])+ const setsLoading = ref(false)+ /** Set names by prefix, from the catalogue and from search answers. */+ const setNames = shallowRef<ReadonlyMap<string, string>>(new Map())++ async function loadSets() {+ if (sets.value.length > 0 || setsLoading.value) return+ setsLoading.value = true+ try {+ sets.value = await provider().collections()+ setNames.value = new Map([+ ...setNames.value,+ ...sets.value.map((info) => [info.prefix, info.name] as const)+ ])+ } catch (error) {+ // Searching every set still works without the catalogue.+ console.warn('Icon sets could not be loaded', error)+ } finally {+ setsLoading.value = false+ }+ }++ // A new query or set outdates the shown icons at once, before the answer arrives.+ function invalidate() {+ version+++ shown.value = PAGE_SIZE+ failed.value = false+ loading.value = query.value.trim() !== '' || set.value !== null+ if (!loading.value) results.value = null+ }++ async function run() {+ const term = query.value.trim()+ const prefix = set.value+ if (!term && !prefix) return+ const request = version+ try {+ let names: string[]+ if (term) {+ const limit = prefix ? SET_SEARCH_LIMIT : SEARCH_LIMIT+ const found = await provider().search(term, {+ limit,+ prefix: prefix ?? undefined+ })+ if (request === version)+ setNames.value = new Map([+ ...setNames.value,+ ...Object.entries(found.collections).map(([key, info]) => [key, info.name] as const)+ ])+ names = found.icons+ if (request === version) capped.value = names.length >= limit+ } else {+ names = prefix ? await provider().browse(prefix) : []+ if (request === version) capped.value = false+ }+ if (request === version) results.value = names+ } catch {+ if (request === version) failed.value = true+ } finally {+ if (request === version) loading.value = false+ }+ }++ watch(query, invalidate, { flush: 'sync' })+ watchDebounced(query, run, { debounce: SEARCH_DEBOUNCE_MS })+ watch(set, () => {+ invalidate()+ void run()+ })+ tryOnScopeDispose(() => version++)++ const visible = computed(() => results.value?.slice(0, shown.value) ?? [])+ const hasMore = computed(() => (results.value?.length ?? 0) > shown.value)+ function loadMore() {+ if (hasMore.value) shown.value += PAGE_SIZE+ }++ // Previews are asked for in one batch per tick, so a page of icons is one request per set.+ const previews = shallowRef<ReadonlyMap<string, string>>(new Map())+ const requested = new Set<string>()+ let pending: string[] = []+ function want(names: readonly string[]) {+ for (const name of names) {+ if (requested.has(name)) continue+ requested.add(name)+ pending.push(name)+ }+ if (pending.length === 0) return+ queueMicrotask(() => void drawPending())+ }+ async function drawPending() {+ const batch = pending+ pending = []+ if (batch.length === 0) return+ try {+ const drawn = await provider().previews(batch)+ previews.value = new Map([...previews.value, ...drawn])+ } catch (error) {+ // A failed batch may be asked for again by the next page or search.+ for (const name of batch) requested.delete(name)+ console.warn('Icon previews could not be loaded', error)+ }+ }+ watch(visible, want, { immediate: true })++ /** The name of the set an icon belongs to, such as Lucide, or its prefix while unknown. */+ function setName(name: string) {+ const prefix = name.slice(0, name.indexOf(':'))+ return setNames.value.get(prefix) ?? prefix+ }++ return {+ query,+ set,+ sets,+ /** The set catalogue is on its way. */+ setsLoading,+ loadSets,+ /** The icons to show now; more follow on `loadMore` while `hasMore`. */+ visible,+ /** How many icons were found. */+ found: computed(() => results.value?.length ?? 0),+ capped,+ hasMore,+ loadMore,+ loading,+ failed,+ /** Each icon's SVG markup, once drawn; icons show before their previews arrive. */+ previews,+ /** Asks for the previews of icons shown outside the results, such as recent ones. */+ want,+ setName+ }+}diff --git a/packages/vue/src/controls/icon/use.ts b/packages/vue/src/controls/icon/use.tsnew file mode 100644index 000000000..6d2eeca04--- /dev/null+++ b/packages/vue/src/controls/icon/use.ts@@ -0,0 +1,71 @@+import { watchImmediate } from '@vueuse/core'+import { ref } from 'vue'++import { iconColor } from '@open-pencil/core/icons'+import { readIcon } from '@open-pencil/scene-graph'+import type { Color } from '@open-pencil/scene-graph/primitives'++import { useUndoBatch } from '#vue/controls/undo-batch/use'+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 the selected icon: its name and its color. */+export function useIcon() {+ const editor = useEditor()+ const { selectedNode } = useSelectionState()+ const batch = useUndoBatch(editor.undo, editor.beginInteractiveEdit)++ const name = useSceneComputed(() => {+ const node = selectedNode.value+ return node ? (readIcon(node)?.name ?? null) : null+ })+ /** The color of the icon's tinted paths; null for an icon drawn only in its own colors. */+ const color = useSceneComputed(() => {+ const node = selectedNode.value+ return node && name.value ? iconColor(editor.graph, node) : null+ })++ /** The selected icon's SVG markup, for showing which icon it is. */+ const preview = ref<string | null>(null)+ /** The name of the set the icon comes from, such as Lucide, once the catalogue is in. */+ const setName = ref<string | null>(null)+ watchImmediate(name, async (current) => {+ // The last icon's preview never stands in for the next one while it loads.+ preview.value = null+ setName.value = null+ if (!current) return+ const prefix = current.slice(0, current.indexOf(':'))+ const [drawn, sets] = await Promise.all([+ editor.iconProvider.previews([current]).catch(() => null),+ editor.iconProvider.collections().catch(() => [])+ ])+ if (name.value !== current) return+ preview.value = drawn?.get(current) ?? null+ setName.value = sets.find((info) => info.prefix === prefix)?.name ?? null+ })++ async function swap(next: string) {+ const node = selectedNode.value+ if (!node || !name.value || name.value === next) return+ batch.flush()+ await editor.swapIconGlyph(node.id, next)+ }++ // A drag in the open color picker sends many colors; they undo as one step, committed when+ // the picker closes. A color typed in while it is closed is a step of its own.+ let picking = false+ function setColorPicking(open: boolean) {+ picking = open+ if (!open) batch.flush()+ }++ function setColor(next: Color) {+ const node = selectedNode.value+ if (!node || !name.value) return+ if (picking) batch.ensure(`icon-color:${node.id}`, 'Change icon color')+ editor.setIconColor(node.id, next)+ }++ return { name, color, preview, setName, swap, setColor, setColorPicking }+}diff --git a/packages/vue/src/i18n/locales/de/menu.json b/packages/vue/src/i18n/locales/de/menu.jsonindex 4012c4530..b6eea4dfd 100644--- a/packages/vue/src/i18n/locales/de/menu.json+++ b/packages/vue/src/i18n/locales/de/menu.json@@ -65,6 +65,7 @@"rulers": "Lineale","settings": "Einstellungen…","variables": "Variablen…",+ "insertIcon": "Symbol einfügen…","splitRight": "Nach rechts teilen","splitDown": "Nach unten teilen","closeView": "Ansicht schließen",diff --git a/packages/vue/src/i18n/locales/de/panels.json b/packages/vue/src/i18n/locales/de/panels.jsonindex a8575e53c..4ddbab11e 100644--- a/packages/vue/src/i18n/locales/de/panels.json+++ b/packages/vue/src/i18n/locales/de/panels.json@@ -388,6 +388,10 @@"searchFonts": "Schriftarten suchen...","blendMode": "Blendmodus","mask": "Maske",+ "icon": "Symbol",+ "iconColor": "Symbolfarbe",+ "swapIcon": "Symbol austauschen",+ "insertIcon": "Symbol einfügen","maskType": "Maskentyp","maskTypeAlpha": "Alpha","maskTypeVector": "Vektor",@@ -410,6 +414,26 @@"blendModeColor": "Farbe","blendModeLuminosity": "Luminanz","noFontsFound": "Keine Schriften gefunden",+ "searchIcons": "Symbole suchen...",+ "searchingIcons": "Suche…",+ "loadingIcons": "Symbole werden geladen…",+ "loadingIconSets": "Symbolsätze werden geladen…",+ "noIconsFound": "Keine Symbole gefunden",+ "iconSearchHint": "Tippen, um über 200.000 Open-Source-Symbole zu durchsuchen",+ "iconSearchFailed": "Symbole konnten nicht geladen werden. Prüfe deine Verbindung.",+ "insertIconFailed": "Das Symbol konnte nicht eingefügt werden.",+ "iconSet": "Symbolsatz",+ "allIconSets": "Alle Symbolsätze",+ "searchIconSets": "Symbolsätze suchen...",+ "noIconSetsFound": "Keine Symbolsätze gefunden",+ "recentIcons": "Zuletzt verwendet",+ "iconsInFile": "In dieser Datei",+ "otherIconSets": "Andere",+ "iconResultCount": {+ "one": "{count} Ergebnis",+ "many": "{count} Ergebnisse"+ },+ "iconResultCountCapped": "{count}+ Ergebnisse","noLocalFontsAvailable": "Keine lokalen Schriften verfügbar.","localFontsAccessHint": "Verwende die Desktop-App oder Chrome/Edge, um auf Systemschriften zuzugreifen.","editColor": "Farbe bearbeiten",diff --git a/packages/vue/src/i18n/locales/es/menu.json b/packages/vue/src/i18n/locales/es/menu.jsonindex dbe08d42b..0ed12e9ae 100644--- a/packages/vue/src/i18n/locales/es/menu.json+++ b/packages/vue/src/i18n/locales/es/menu.json@@ -65,6 +65,7 @@"rulers": "Reglas","settings": "Ajustes…","variables": "Variables…",+ "insertIcon": "Insertar icono…","splitRight": "Dividir a la derecha","splitDown": "Dividir hacia abajo","closeView": "Cerrar vista",diff --git a/packages/vue/src/i18n/locales/es/panels.json b/packages/vue/src/i18n/locales/es/panels.jsonindex 76439ba22..e0beee1a9 100644--- a/packages/vue/src/i18n/locales/es/panels.json+++ b/packages/vue/src/i18n/locales/es/panels.json@@ -388,6 +388,10 @@"searchFonts": "Buscar fuentes...","blendMode": "Modo de fusión","mask": "Máscara",+ "icon": "Icono",+ "iconColor": "Color del icono",+ "swapIcon": "Cambiar icono",+ "insertIcon": "Insertar icono","maskType": "Tipo de máscara","maskTypeAlpha": "Alfa","maskTypeVector": "Vectorial",@@ -410,6 +414,26 @@"blendModeColor": "Color","blendModeLuminosity": "Luminosidad","noFontsFound": "No se han encontrado fuentes",+ "searchIcons": "Buscar iconos...",+ "searchingIcons": "Buscando…",+ "loadingIcons": "Cargando iconos…",+ "loadingIconSets": "Cargando conjuntos de iconos…",+ "noIconsFound": "No se encontraron iconos",+ "iconSearchHint": "Escribe para buscar entre más de 200.000 iconos de código abierto",+ "iconSearchFailed": "No se pudieron cargar los iconos. Comprueba tu conexión.",+ "insertIconFailed": "No se pudo insertar el icono.",+ "iconSet": "Conjunto de iconos",+ "allIconSets": "Todos los conjuntos",+ "searchIconSets": "Buscar conjuntos de iconos...",+ "noIconSetsFound": "No se encontraron conjuntos",+ "recentIcons": "Recientes",+ "iconsInFile": "En este archivo",+ "otherIconSets": "Otros",+ "iconResultCount": {+ "one": "{count} resultado",+ "many": "{count} resultados"+ },+ "iconResultCountCapped": "{count}+ resultados","noLocalFontsAvailable": "No hay fuentes locales disponibles.","localFontsAccessHint": "Usa la aplicación de escritorio o Chrome/Edge para acceder a las fuentes del sistema.","editColor": "Editar color",diff --git a/packages/vue/src/i18n/locales/fr/menu.json b/packages/vue/src/i18n/locales/fr/menu.jsonindex 686a11d0d..e065870ba 100644--- a/packages/vue/src/i18n/locales/fr/menu.json+++ b/packages/vue/src/i18n/locales/fr/menu.json@@ -65,6 +65,7 @@"rulers": "Règles","settings": "Paramètres…","variables": "Variables…",+ "insertIcon": "Insérer une icône…","splitRight": "Diviser à droite","splitDown": "Diviser vers le bas","closeView": "Fermer la vue",diff --git a/packages/vue/src/i18n/locales/fr/panels.json b/packages/vue/src/i18n/locales/fr/panels.jsonindex b6133ee99..48134d2bc 100644--- a/packages/vue/src/i18n/locales/fr/panels.json+++ b/packages/vue/src/i18n/locales/fr/panels.json@@ -388,6 +388,10 @@"searchFonts": "Rechercher des polices...","blendMode": "Mode de fusion","mask": "Masque",+ "icon": "Icône",+ "iconColor": "Couleur de l'icône",+ "swapIcon": "Changer d'icône",+ "insertIcon": "Insérer une icône","maskType": "Type de masque","maskTypeAlpha": "Alpha","maskTypeVector": "Vectoriel",@@ -410,6 +414,26 @@"blendModeColor": "Couleur","blendModeLuminosity": "Luminosité","noFontsFound": "Aucune police trouvée",+ "searchIcons": "Rechercher des icônes...",+ "searchingIcons": "Recherche…",+ "loadingIcons": "Chargement des icônes…",+ "loadingIconSets": "Chargement des jeux d'icônes…",+ "noIconsFound": "Aucune icône trouvée",+ "iconSearchHint": "Tapez pour rechercher parmi plus de 200 000 icônes open source",+ "iconSearchFailed": "Impossible de charger les icônes. Vérifiez votre connexion.",+ "insertIconFailed": "Impossible d'insérer l'icône.",+ "iconSet": "Jeu d'icônes",+ "allIconSets": "Tous les jeux d'icônes",+ "searchIconSets": "Rechercher des jeux d'icônes...",+ "noIconSetsFound": "Aucun jeu d'icônes trouvé",+ "recentIcons": "Récentes",+ "iconsInFile": "Dans ce fichier",+ "otherIconSets": "Autres",+ "iconResultCount": {+ "one": "{count} résultat",+ "many": "{count} résultats"+ },+ "iconResultCountCapped": "{count}+ résultats","noLocalFontsAvailable": "Aucune police locale disponible.","localFontsAccessHint": "Utilisez l’application de bureau ou Chrome/Edge pour accéder aux polices système.","editColor": "Modifier la couleur",diff --git a/packages/vue/src/i18n/locales/it/menu.json b/packages/vue/src/i18n/locales/it/menu.jsonindex 588ed384c..dcdcd8c9c 100644--- a/packages/vue/src/i18n/locales/it/menu.json+++ b/packages/vue/src/i18n/locales/it/menu.json@@ -65,6 +65,7 @@"rulers": "Righelli","settings": "Impostazioni…","variables": "Variabili…",+ "insertIcon": "Inserisci icona…","splitRight": "Dividi a destra","splitDown": "Dividi in basso","closeView": "Chiudi vista",diff --git a/packages/vue/src/i18n/locales/it/panels.json b/packages/vue/src/i18n/locales/it/panels.jsonindex cd8d94d8a..cb2be2635 100644--- a/packages/vue/src/i18n/locales/it/panels.json+++ b/packages/vue/src/i18n/locales/it/panels.json@@ -388,6 +388,10 @@"searchFonts": "Cerca font...","blendMode": "Metodo di fusione","mask": "Maschera",+ "icon": "Icona",+ "iconColor": "Colore dell'icona",+ "swapIcon": "Sostituisci icona",+ "insertIcon": "Inserisci icona","maskType": "Tipo di maschera","maskTypeAlpha": "Alfa","maskTypeVector": "Vettore",@@ -410,6 +414,26 @@"blendModeColor": "Colore","blendModeLuminosity": "Luminosità","noFontsFound": "Nessun font trovato",+ "searchIcons": "Cerca icone...",+ "searchingIcons": "Ricerca…",+ "loadingIcons": "Caricamento icone…",+ "loadingIconSets": "Caricamento set di icone…",+ "noIconsFound": "Nessuna icona trovata",+ "iconSearchHint": "Digita per cercare tra oltre 200.000 icone open source",+ "iconSearchFailed": "Impossibile caricare le icone. Controlla la connessione.",+ "insertIconFailed": "Impossibile inserire l'icona.",+ "iconSet": "Set di icone",+ "allIconSets": "Tutti i set di icone",+ "searchIconSets": "Cerca set di icone...",+ "noIconSetsFound": "Nessun set di icone trovato",+ "recentIcons": "Recenti",+ "iconsInFile": "In questo file",+ "otherIconSets": "Altri",+ "iconResultCount": {+ "one": "{count} risultato",+ "many": "{count} risultati"+ },+ "iconResultCountCapped": "{count}+ risultati","noLocalFontsAvailable": "Nessun font locale disponibile.","localFontsAccessHint": "Usa l’app desktop o Chrome/Edge per accedere ai font di sistema.","editColor": "Modifica colore",diff --git a/packages/vue/src/i18n/locales/ja/menu.json b/packages/vue/src/i18n/locales/ja/menu.jsonindex 51473f2d5..7d1077670 100644--- a/packages/vue/src/i18n/locales/ja/menu.json+++ b/packages/vue/src/i18n/locales/ja/menu.json@@ -65,6 +65,7 @@"rulers": "ルーラー","settings": "設定…","variables": "変数…",+ "insertIcon": "アイコンを挿入…","splitRight": "右に分割","splitDown": "下に分割","closeView": "ビューを閉じる",diff --git a/packages/vue/src/i18n/locales/ja/panels.json b/packages/vue/src/i18n/locales/ja/panels.jsonindex 024ac9d7f..81bb30a45 100644--- a/packages/vue/src/i18n/locales/ja/panels.json+++ b/packages/vue/src/i18n/locales/ja/panels.json@@ -382,6 +382,10 @@"searchFonts": "フォントを検索...","blendMode": "ブレンドモード","mask": "マスク",+ "icon": "アイコン",+ "iconColor": "アイコンの色",+ "swapIcon": "アイコンを入れ替え",+ "insertIcon": "アイコンを挿入","maskType": "マスクの種類","maskTypeAlpha": "アルファ","maskTypeVector": "ベクター",@@ -404,6 +408,25 @@"blendModeColor": "カラー","blendModeLuminosity": "輝度","noFontsFound": "フォントが見つかりません",+ "searchIcons": "アイコンを検索...",+ "searchingIcons": "検索中…",+ "loadingIcons": "アイコンを読み込み中…",+ "loadingIconSets": "アイコンセットを読み込み中…",+ "noIconsFound": "アイコンが見つかりません",+ "iconSearchHint": "20万以上のオープンソースアイコンを検索できます",+ "iconSearchFailed": "アイコンを読み込めませんでした。接続を確認してください。",+ "insertIconFailed": "アイコンを挿入できませんでした。",+ "iconSet": "アイコンセット",+ "allIconSets": "すべてのアイコンセット",+ "searchIconSets": "アイコンセットを検索...",+ "noIconSetsFound": "アイコンセットが見つかりません",+ "recentIcons": "最近使用",+ "iconsInFile": "このファイル内",+ "otherIconSets": "その他",+ "iconResultCount": {+ "many": "{count} 件の結果"+ },+ "iconResultCountCapped": "{count} 件以上の結果","noLocalFontsAvailable": "利用できるローカルフォントがありません。","localFontsAccessHint": "システムフォントにアクセスするには、デスクトップアプリまたはChrome/Edgeを使用してください。","editColor": "色を編集",diff --git a/packages/vue/src/i18n/locales/pl/menu.json b/packages/vue/src/i18n/locales/pl/menu.jsonindex e24542235..6a82f5712 100644--- a/packages/vue/src/i18n/locales/pl/menu.json+++ b/packages/vue/src/i18n/locales/pl/menu.json@@ -65,6 +65,7 @@"rulers": "Linijki","settings": "Ustawienia…","variables": "Zmienne…",+ "insertIcon": "Wstaw ikonę…","splitRight": "Podziel w prawo","splitDown": "Podziel w dół","closeView": "Zamknij widok",diff --git a/packages/vue/src/i18n/locales/pl/panels.json b/packages/vue/src/i18n/locales/pl/panels.jsonindex 4073efd79..1da2d7d65 100644--- a/packages/vue/src/i18n/locales/pl/panels.json+++ b/packages/vue/src/i18n/locales/pl/panels.json@@ -394,6 +394,10 @@"searchFonts": "Szukaj fontów...","blendMode": "Tryb mieszania","mask": "Maska",+ "icon": "Ikona",+ "iconColor": "Kolor ikony",+ "swapIcon": "Zamień ikonę",+ "insertIcon": "Wstaw ikonę","maskType": "Typ maski","maskTypeAlpha": "Alfa","maskTypeVector": "Wektorowa",@@ -416,6 +420,27 @@"blendModeColor": "Kolor","blendModeLuminosity": "Jasność","noFontsFound": "Nie znaleziono czcionek",+ "searchIcons": "Szukaj ikon...",+ "searchingIcons": "Wyszukiwanie…",+ "loadingIcons": "Wczytywanie ikon…",+ "loadingIconSets": "Wczytywanie zestawów ikon…",+ "noIconsFound": "Nie znaleziono ikon",+ "iconSearchHint": "Wpisz, aby przeszukać ponad 200 000 ikon open source",+ "iconSearchFailed": "Nie udało się wczytać ikon. Sprawdź połączenie.",+ "insertIconFailed": "Nie udało się wstawić ikony.",+ "iconSet": "Zestaw ikon",+ "allIconSets": "Wszystkie zestawy ikon",+ "searchIconSets": "Szukaj zestawów ikon...",+ "noIconSetsFound": "Nie znaleziono zestawów ikon",+ "recentIcons": "Ostatnie",+ "iconsInFile": "W tym pliku",+ "otherIconSets": "Inne",+ "iconResultCount": {+ "one": "{count} wynik",+ "few": "{count} wyniki",+ "many": "{count} wyników"+ },+ "iconResultCountCapped": "{count}+ wyników","noLocalFontsAvailable": "Brak dostępnych czcionek lokalnych.","localFontsAccessHint": "Użyj aplikacji komputerowej lub Chrome/Edge, aby uzyskać dostęp do czcionek systemowych.","editColor": "Edytuj kolor",diff --git a/packages/vue/src/i18n/locales/ru/menu.json b/packages/vue/src/i18n/locales/ru/menu.jsonindex c87ec307a..8f2b340de 100644--- a/packages/vue/src/i18n/locales/ru/menu.json+++ b/packages/vue/src/i18n/locales/ru/menu.json@@ -65,6 +65,7 @@"rulers": "Линейки","settings": "Настройки…","variables": "Переменные…",+ "insertIcon": "Вставить иконку…","splitRight": "Разделить вправо","splitDown": "Разделить вниз","closeView": "Закрыть вид",diff --git a/packages/vue/src/i18n/locales/ru/panels.json b/packages/vue/src/i18n/locales/ru/panels.jsonindex c6c4ce792..550edd5bf 100644--- a/packages/vue/src/i18n/locales/ru/panels.json+++ b/packages/vue/src/i18n/locales/ru/panels.json@@ -394,6 +394,10 @@"searchFonts": "Поиск шрифтов...","blendMode": "Режим наложения","mask": "Маска",+ "icon": "Иконка",+ "iconColor": "Цвет иконки",+ "swapIcon": "Заменить иконку",+ "insertIcon": "Вставить иконку","maskType": "Тип маски","maskTypeAlpha": "Альфа-канал","maskTypeVector": "Вектор",@@ -416,6 +420,27 @@"blendModeColor": "Цвет","blendModeLuminosity": "Яркость","noFontsFound": "Шрифты не найдены",+ "searchIcons": "Искать иконки...",+ "searchingIcons": "Поиск…",+ "loadingIcons": "Загрузка иконок…",+ "loadingIconSets": "Загрузка наборов иконок…",+ "noIconsFound": "Иконки не найдены",+ "iconSearchHint": "Начните вводить, чтобы искать среди более чем 200 000 открытых иконок",+ "iconSearchFailed": "Не удалось загрузить иконки. Проверьте подключение.",+ "insertIconFailed": "Не удалось вставить иконку.",+ "iconSet": "Набор иконок",+ "allIconSets": "Все наборы иконок",+ "searchIconSets": "Искать наборы иконок...",+ "noIconSetsFound": "Наборы иконок не найдены",+ "recentIcons": "Недавние",+ "iconsInFile": "В этом файле",+ "otherIconSets": "Другие",+ "iconResultCount": {+ "one": "{count} результат",+ "few": "{count} результата",+ "many": "{count} результатов"+ },+ "iconResultCountCapped": "{count}+ результатов","noLocalFontsAvailable": "Локальные шрифты недоступны.","localFontsAccessHint": "Используйте настольное приложение или Chrome/Edge для доступа к системным шрифтам.","editColor": "Изменить цвет",diff --git a/packages/vue/src/i18n/locales/zh-cn/menu.json b/packages/vue/src/i18n/locales/zh-cn/menu.jsonindex fc4e773ca..8f23cc1eb 100644--- a/packages/vue/src/i18n/locales/zh-cn/menu.json+++ b/packages/vue/src/i18n/locales/zh-cn/menu.json@@ -65,6 +65,7 @@"rulers": "标尺","settings": "设置…","variables": "变量…",+ "insertIcon": "插入图标…","splitRight": "向右拆分","splitDown": "向下拆分","closeView": "关闭视图",diff --git a/packages/vue/src/i18n/locales/zh-cn/panels.json b/packages/vue/src/i18n/locales/zh-cn/panels.jsonindex 8108e90ce..8cadb92d0 100644--- a/packages/vue/src/i18n/locales/zh-cn/panels.json+++ b/packages/vue/src/i18n/locales/zh-cn/panels.json@@ -382,6 +382,10 @@"searchFonts": "搜索字体...","blendMode": "混合模式","mask": "蒙版",+ "icon": "图标",+ "iconColor": "图标颜色",+ "swapIcon": "替换图标",+ "insertIcon": "插入图标","maskType": "蒙版类型","maskTypeAlpha": "Alpha","maskTypeVector": "矢量",@@ -404,6 +408,25 @@"blendModeColor": "颜色","blendModeLuminosity": "明度","noFontsFound": "未找到字体",+ "searchIcons": "搜索图标...",+ "searchingIcons": "正在搜索…",+ "loadingIcons": "正在加载图标…",+ "loadingIconSets": "正在加载图标集…",+ "noIconsFound": "未找到图标",+ "iconSearchHint": "输入以搜索超过 20 万个开源图标",+ "iconSearchFailed": "无法加载图标,请检查网络连接。",+ "insertIconFailed": "无法插入图标。",+ "iconSet": "图标集",+ "allIconSets": "所有图标集",+ "searchIconSets": "搜索图标集...",+ "noIconSetsFound": "未找到图标集",+ "recentIcons": "最近使用",+ "iconsInFile": "此文件中",+ "otherIconSets": "其他",+ "iconResultCount": {+ "many": "{count} 个结果"+ },+ "iconResultCountCapped": "{count}+ 个结果","noLocalFontsAvailable": "没有可用的本地字体。","localFontsAccessHint": "请使用桌面应用或 Chrome/Edge 访问系统字体。","editColor": "编辑颜色",diff --git a/packages/vue/src/i18n/messages/menu.ts b/packages/vue/src/i18n/messages/menu.tsindex 6acc391b4..50db24fdd 100644--- a/packages/vue/src/i18n/messages/menu.ts+++ b/packages/vue/src/i18n/messages/menu.ts@@ -32,6 +32,7 @@ export const menuMessageDefaults = {language: 'Language',settings: 'Settings…',variables: 'Variables…',+ insertIcon: 'Insert Icon…',rulers: 'Rulers',multiplayerCursors: 'Multiplayer cursors',designIssues: 'Design issues',diff --git a/packages/vue/src/i18n/messages/panels.ts b/packages/vue/src/i18n/messages/panels.tsindex 55a4dcbfa..66749af48 100644--- a/packages/vue/src/i18n/messages/panels.ts+++ b/packages/vue/src/i18n/messages/panels.ts@@ -152,6 +152,10 @@ export const panelMessageDefaults = {stroke: 'Stroke',effects: 'Effects',mask: 'Mask',+ icon: 'Icon',+ iconColor: 'Icon color',+ swapIcon: 'Swap icon',+ insertIcon: 'Insert icon',export: 'Export',typography: 'Typography',fontFamily: 'Font family',@@ -497,6 +501,24 @@ export const panelMessageDefaults = {gridSectionSize: 'Section size',searchFonts: 'Search fonts...',noFontsFound: 'No fonts found',+ searchIcons: 'Search icons...',+ searchingIcons: 'Searching…',+ loadingIcons: 'Loading icons…',+ loadingIconSets: 'Loading icon sets…',+ noIconsFound: 'No icons found',+ iconSearchHint: 'Type to search over 200,000 open-source icons',+ iconSearchFailed: 'Icons could not be loaded. Check your connection.',+ insertIconFailed: 'The icon could not be inserted.',+ iconSet: 'Icon set',+ allIconSets: 'All icon sets',+ searchIconSets: 'Search icon sets...',+ noIconSetsFound: 'No icon sets found',+ recentIcons: 'Recent',+ iconsInFile: 'In this file',+ otherIconSets: 'Other',+ iconResultCount: count({ one: '{count} result', many: '{count} results' }),+ /** More icons match than a search returns. */+ iconResultCountCapped: params('{count}+ results'),noLocalFontsAvailable: 'No local fonts available.',localFontsAccessHint: 'Use the desktop app or Chrome/Edge to access system fonts.',editColor: 'Edit color',diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.tsindex 8fed65c3c..f44e95d0b 100644--- a/packages/vue/src/index.ts+++ b/packages/vue/src/index.ts@@ -105,6 +105,8 @@ export { useLayout } from '#vue/controls/layout/use'export type { LayoutAxis, SizeLimitProp } from '#vue/controls/layout/helpers'export { useAppearance } from '#vue/controls/appearance/use'export { useMask } from '#vue/controls/mask/use'+export { useIcon } from '#vue/controls/icon/use'+export { useIconSearch } from '#vue/controls/icon/search'export { useTypography } from '#vue/controls/typography/use'export type { UseTypographyOptions } from '#vue/controls/typography/use'export { useDocumentWorkspace } from '#vue/document/workspace/use'diff --git a/src/app/automation/bridge/figma-factory.ts b/src/app/automation/bridge/figma-factory.tsindex 1de6e7c1d..4f817b6aa 100644--- a/src/app/automation/bridge/figma-factory.ts+++ b/src/app/automation/bridge/figma-factory.ts@@ -10,6 +10,7 @@ export function makeFigmaFromStore(): FigmaAPI {const api = new FigmaAPI(store.graph)api.setRenderer(store.renderer ?? null)+ api.icons = store.iconProviderapi.theme = store.state.theme ?? 'light'api.currentPage = api.wrapNode(pageId)// The user's selection belongs to the page on screen.diff --git a/src/app/editor/design-check/format.ts b/src/app/editor/design-check/format.tsindex b15b44928..e2d1b4175 100644--- a/src/app/editor/design-check/format.ts+++ b/src/app/editor/design-check/format.ts@@ -1,5 +1,7 @@import type { LintFix, LintFixRequest } from '@open-pencil/core/lint'-import { locale, type useDesignCheckMessages } from '@open-pencil/vue'+import type { useDesignCheckMessages } from '@open-pencil/vue'++import { formatNumber } from '@/app/i18n/number'import type { DesignIssue } from './issues'@@ -52,19 +54,6 @@ const SPACING_DETAIL = {/** Figma's geometry field labels, which stay untranslated across its locales. */const GEOMETRY_LABELS: Record<string, string> = { x: 'X', y: 'Y', width: 'W', height: 'H' }-const numberFormats = new Map<string, Intl.NumberFormat>()--/** Numbers follow the app's language, not the browser's, like the rest of the panel. */-function formatNumber(value: number): string {- const language = locale.get()- let format = numberFormats.get(language)- if (!format) {- format = new Intl.NumberFormat(language, { maximumFractionDigits: 2 })- numberFormats.set(language, format)- }- return format.format(value)-}-function numberAt(issue: DesignIssue, key: string): number | undefined {const value = issue.data?.[key]return typeof value === 'number' ? value : undefineddiff --git a/src/app/editor/icon-picker/history.ts b/src/app/editor/icon-picker/history.tsnew file mode 100644index 000000000..334d4c83c--- /dev/null+++ b/src/app/editor/icon-picker/history.ts@@ -0,0 +1,35 @@+import { useLocalStorage } from '@vueuse/core'+import { uniq } from 'es-toolkit'+import * as v from 'valibot'++import { ICON_NAME } from '@open-pencil/scene-graph'++const MAX_RECENT_ICONS = 24+const RECENT_ICONS_STORAGE_KEY = 'open-pencil:recent-icons'+const ICON_SET_STORAGE_KEY = 'open-pencil:icon-set'++/** Stored icon names; anything unreadable reads as none rather than failing the picker. */+const RecentIconsJSON = v.pipe(+ v.string(),+ v.parseJson(),+ v.array(v.pipe(v.string(), v.regex(ICON_NAME)))+)++/** The icons this person picked last, newest first, across documents. */+export const recentIcons = useLocalStorage<string[]>(RECENT_ICONS_STORAGE_KEY, [], {+ serializer: {+ read: (raw) => {+ const parsed = v.safeParse(RecentIconsJSON, raw)+ return parsed.success ? parsed.output : []+ },+ write: (names) => JSON.stringify(names)+ }+})++/** The set the picker searched last, by prefix; empty for every set. */+export const lastIconSet = useLocalStorage<string>(ICON_SET_STORAGE_KEY, '')++/** Puts `name` first among the recent icons. */+export function rememberIcon(name: string): void {+ recentIcons.value = uniq([name, ...recentIcons.value]).slice(0, MAX_RECENT_ICONS)+}diff --git a/src/app/editor/session/types.ts b/src/app/editor/session/types.tsindex 2cd52e953..c2a736759 100644--- a/src/app/editor/session/types.ts+++ b/src/app/editor/session/types.ts@@ -26,6 +26,7 @@ export function createInitialAppEditorState(pageId: string): AppEditorState {nodeEditState: null,renameSelectionOpen: false,variablesOpen: false,+ iconPickerOpen: false,renameNodeId: null,numberFieldFocused: false,preparation: null,@@ -49,6 +50,8 @@ export type AppEditorState = EditorState & {renameSelectionOpen: boolean/** The variables dialog, opened from the Design panel, the View menu, or the palette. */variablesOpen: boolean+ /** The icon picker, opened from the toolbar, the Object menu, or the palette. */+ iconPickerOpen: booleanrenameNodeId: string | nullnumberFieldFocused: booleanpreparation: EditorPreparation | nulldiff --git a/src/app/i18n/number.ts b/src/app/i18n/number.tsnew file mode 100644index 000000000..5b068bd81--- /dev/null+++ b/src/app/i18n/number.ts@@ -0,0 +1,14 @@+import { locale } from '@open-pencil/vue'++const numberFormats = new Map<string, Intl.NumberFormat>()++/** Numbers follow the app's language, not the browser's, like the rest of the interface. */+export function formatNumber(value: number): string {+ const language = locale.get()+ let format = numberFormats.get(language)+ if (!format) {+ format = new Intl.NumberFormat(language, { maximumFractionDigits: 2 })+ numberFormats.set(language, format)+ }+ return format.format(value)+}diff --git a/src/app/shell/menu/app-menu.ts b/src/app/shell/menu/app-menu.tsindex 678edd2cd..8b7fd40b2 100644--- a/src/app/shell/menu/app-menu.ts+++ b/src/app/shell/menu/app-menu.ts@@ -113,6 +113,7 @@ export function useAppMenu() {preferences: 'preferences',settings: 'settings',variables: 'variables',+ 'insert-icon': 'insertIcon','view-rulers': 'rulers','view-multiplayer-cursors': 'multiplayerCursors','view-design-issues': 'designIssues',@@ -170,6 +171,9 @@ export function useAppMenu() {},settings: openSettingsDialog,variables: () => openVariablesDialog(store),+ 'insert-icon': () => {+ store.state.iconPickerOpen = true+ },'export-png': () => exportSelection('png'),'export-svg': () => exportSelection('svg'),'export-pptx': () => exportSelection('pptx'),diff --git a/src/app/shell/menu/schema.ts b/src/app/shell/menu/schema.tsindex cf55ae690..c3b80417e 100644--- a/src/app/shell/menu/schema.ts+++ b/src/app/shell/menu/schema.ts@@ -264,6 +264,12 @@ export const APP_MENU_SCHEMA = [command: 'selection.ungroup'},{ type: 'separator' },+ {+ id: 'insert-icon',+ label: 'Insert Icon…',+ palette: { keywords: ['iconify', 'symbol', 'glyph', 'lucide'] }+ },+ { type: 'separator' },{id: 'selection.toggleMask',label: 'Use as Mask',diff --git a/src/components/DesignPanel.vue b/src/components/DesignPanel.vueindex 7ca33e8a6..f5fde349e 100644--- a/src/components/DesignPanel.vue+++ b/src/components/DesignPanel.vue@@ -28,6 +28,7 @@ import ExportSection from './properties/ExportSection.vue'import FillSection from './properties/FillSection.vue'import FramePresetSelect from './properties/frame-presets/FramePresetSelect.vue'import FramePresetsSection from './properties/frame-presets/FramePresetsSection.vue'+import IconSection from './properties/IconSection.vue'import LayoutGridSection from './properties/layout/guides/LayoutGridSection.vue'import LayoutSection from './properties/layout/LayoutSection.vue'import MaskSection from './properties/MaskSection.vue'@@ -188,6 +189,7 @@ const { panels } = useI18n()<FramePresetSelect v-if="node.type === 'FRAME'" />+ <IconSection /><PositionSection /><ConstraintsSection /><LayoutSection />diff --git a/src/components/Toolbar/DesktopToolbar.vue b/src/components/Toolbar/DesktopToolbar.vueindex 93015f8ee..0dc133a65 100644--- a/src/components/Toolbar/DesktopToolbar.vue+++ b/src/components/Toolbar/DesktopToolbar.vue@@ -70,6 +70,8 @@ const emit = defineEmits<{</Tip></ToolbarItem></template>+ <!-- Inserting rather than drawing: commands such as placing an icon. -->+ <slot name="end" /></ToolbarRoot></div></template>diff --git a/src/components/Toolbar/MobileToolbar.vue b/src/components/Toolbar/MobileToolbar.vueindex 5e1da58d8..5eb2f0021 100644--- a/src/components/Toolbar/MobileToolbar.vue+++ b/src/components/Toolbar/MobileToolbar.vue@@ -185,6 +185,8 @@ function navigationClass(disabled: boolean) {/></motion.div></AnimatePresence>+ <!-- Inserting rather than drawing, in every category: commands such as placing an icon. -->+ <slot name="end" /></motion.div></ToolbarRoot>diff --git a/src/components/Toolbar/Toolbar.vue b/src/components/Toolbar/Toolbar.vueindex f528deceb..589803e6c 100644--- a/src/components/Toolbar/Toolbar.vue+++ b/src/components/Toolbar/Toolbar.vue@@ -13,6 +13,7 @@ import type { Tool } from '@open-pencil/vue'import { useEditorStore } from '@/app/editor/active-store'import { toolIcons } from '@/app/editor/icons'import { useActionToast } from '@/app/shell/toast/action'+import InsertIconButton from '@/components/icon-picker/InsertIconButton.vue'import { useToolbarActions } from '@/components/Toolbar/actions'import DesktopToolbar from '@/components/Toolbar/DesktopToolbar.vue'import MobileToolbar from '@/components/Toolbar/MobileToolbar.vue'@@ -77,7 +78,11 @@ function onActionTap(item: ToolbarActionItem) {:tool-shortcuts="toolShortcuts":ui="toolbarUI"@set-tool="actions.setTool"- />+ >+ <template #end>+ <InsertIconButton :ui="toolbarUI" />+ </template>+ </DesktopToolbar><MobileToolbarv-else@@ -98,6 +103,10 @@ function onActionTap(item: ToolbarActionItem) {@prev="goPrev"@next="goNext"@action="onActionTap"- />+ >+ <template #end>+ <InsertIconButton mobile :ui="toolbarUI" />+ </template>+ </MobileToolbar></ToolbarRoot></template>diff --git a/src/components/icon-picker/IconPicker.vue b/src/components/icon-picker/IconPicker.vuenew file mode 100644index 000000000..7a65bedb7--- /dev/null+++ b/src/components/icon-picker/IconPicker.vue@@ -0,0 +1,214 @@+<script setup lang="ts">+import { compact } from 'es-toolkit'+import { computed, ref, watch } from 'vue'++import { iconNames } from '@open-pencil/scene-graph'+import { useCommonMessages, useIconSearch, usePanelMessages } from '@open-pencil/vue'++import { useEditorStore } from '@/app/editor/active-store'+import { lastIconSet, recentIcons, rememberIcon } from '@/app/editor/icon-picker/history'+import { formatNumber } from '@/app/i18n/number'+import AppCombobox from '@/components/ui/select/AppCombobox.vue'+import type { AppComboboxOption } from '@/components/ui/select/AppCombobox.vue'+import AppPicker from '@/components/ui/select/AppPicker.vue'+import type { AppPickerItem } from '@/components/ui/select/AppPicker.vue'++import IconPreview from './IconPreview.vue'++const {+ heading,+ selected,+ set: initialSet,+ tooltip,+ side = 'left',+ align = 'start'+} = defineProps<{+ heading: string+ /** The icon shown now, marked in the grid. */+ selected?: string+ /** The set to open on, by prefix, such as the swapped icon's own; the last one chosen if unset. */+ set?: string+ tooltip?: string+ side?: 'left' | 'right' | 'top' | 'bottom'+ align?: 'start' | 'center' | 'end'+}>()+const emit = defineEmits<{ select: [name: string] }>()++/** The set selector's value for every set; Reka reserves the empty string, and no prefix has `*`. */+const ALL_SETS = '*'+const open = defineModel<boolean>('open', { default: false })++const store = useEditorStore()+const panels = usePanelMessages()+const common = useCommonMessages()+const search = useIconSearch()+const { query, visible, hasMore, loadMore, loading, failed, previews, setsLoading } = search++/** The set restored from the last visit, as opposed to one the caller asked for. */+let remembered: string | null = null+// A remembered set that no longer loads, such as one the source has since dropped, gives way+// to every set rather than leaving each later visit failed. A set the caller asked for stays.+watch(failed, (isFailed) => {+ if (!isFailed || !remembered || query.value.trim() || search.set.value !== remembered) return+ remembered = null+ lastIconSet.value = ''+ search.set.value = null+})++/** The icons placed in the document, read when the picker opens. */+const placed = ref<string[]>([])+watch(open, (isOpen) => {+ if (!isOpen) return+ void search.loadSets()+ remembered = initialSet ? null : lastIconSet.value || null+ search.set.value = initialSet ?? remembered+ placed.value = iconNames(store.graph.getAllNodes())+ search.want([...placed.value, ...recentIcons.value])+})++/** Sets by prefix, for their names and licenses in the footer. */+const setsByPrefix = computed(() => new Map(search.sets.value.map((info) => [info.prefix, info])))+const setOptions = computed<AppComboboxOption[]>(() => [+ { value: ALL_SETS, label: panels.value.allIconSets },+ ...search.sets.value.map((info) => ({+ value: info.prefix,+ label: info.name,+ meta: formatNumber(info.total),+ group: info.category ?? panels.value.otherIconSets+ }))+])+const chosenSet = computed({+ get: () => search.set.value ?? ALL_SETS,+ set: (value: string) => {+ const prefix = value === ALL_SETS ? null : value+ // A set chosen here is the person's choice, which a failed load does not undo.+ remembered = null+ search.set.value = prefix+ lastIconSet.value = prefix ?? ''+ }+})++function item(name: string, group?: string): AppPickerItem {+ return {+ value: name,+ label: name.slice(name.indexOf(':') + 1),+ description: search.setName(name),+ group+ }+}+/**+ * Before a query, the icons placed in the file and picked lately come first, from the chosen+ * set only, and then the rest of that set. A query shows only what it finds. Groups are named+ * only when there are several.+ */+const items = computed<AppPickerItem[]>(() => {+ if (query.value.trim()) return visible.value.map((name) => item(name))+ const prefix = search.set.value+ const inSet = (name: string) => !prefix || name.startsWith(`${prefix}:`)+ const inFile = placed.value.filter(inSet)+ const recent = recentIcons.value.filter((name) => inSet(name) && !inFile.includes(name))+ const shown = new Set([...inFile, ...recent])+ const rest = visible.value.filter((name) => !shown.has(name))+ const named = [inFile, recent, rest].filter((group) => group.length > 0).length > 1+ const setLabel = named && prefix ? search.setName(`${prefix}:`) : undefined+ return [+ ...inFile.map((name) => item(name, panels.value.iconsInFile)),+ ...recent.map((name) => item(name, panels.value.recentIcons)),+ ...rest.map((name) => item(name, setLabel))+ ]+})++/** What the footer says with nothing highlighted: the results, the set, or how to start. */+const summary = computed(() => {+ if (query.value.trim()) {+ if (loading.value) return ''+ const count = search.found.value+ return search.capped.value+ ? panels.value.iconResultCountCapped({ count })+ : panels.value.iconResultCount(count)+ }+ const info = search.set.value ? setsByPrefix.value.get(search.set.value) : undefined+ if (info) return compact([info.name, info.license, formatNumber(info.total)]).join(' · ')+ return panels.value.iconSearchHint+})+/** The set and license of a highlighted icon. */+function details(name: string) {+ const info = setsByPrefix.value.get(name.slice(0, name.indexOf(':')))+ return compact([search.setName(name), info?.license]).join(' · ')+}++const emptyLabel = computed(() => {+ if (failed.value) return panels.value.iconSearchFailed+ // Typing searches; choosing a set loads it.+ if (loading.value)+ return query.value.trim() ? panels.value.searchingIcons : panels.value.loadingIcons+ return query.value.trim() || search.set.value+ ? panels.value.noIconsFound+ : panels.value.iconSearchHint+})++function pick(name: string) {+ rememberIcon(name)+ emit('select', name)+}+</script>++<template>+ <AppPicker+ v-model:open="open"+ v-model:query="query"+ search="remote"+ layout="grid"+ :has-more="hasMore"+ :loading="loading"+ :heading="heading"+ :items="items"+ :selected="selected"+ :tooltip="tooltip"+ :side="side"+ :align="align"+ :search-placeholder="panels.searchIcons"+ :empty-label="emptyLabel"+ :close-label="common.close"+ @select="pick"+ @load-more="loadMore"+ >+ <template #trigger>+ <slot name="trigger" />+ </template>+ <template #search-trailing>+ <AppCombobox+ v-model="chosenSet"+ :options="setOptions"+ :label="panels.iconSet"+ :search-placeholder="panels.searchIconSets"+ :empty-label="setsLoading ? panels.loadingIconSets : panels.noIconSetsFound"+ :result-limit="setOptions.length"+ align="end"+ :ui="{+ trigger:+ 'mr-1 h-5 w-auto max-w-32 shrink-0 border-0 bg-transparent px-1.5 hover:bg-hover',+ value: 'text-muted',+ content: 'w-64'+ }"+ >+ <template #option="{ option }">+ <span class="min-w-0 flex-1 truncate">{{ option.label }}</span>+ <span class="shrink-0 text-muted tabular-nums">{{ option.meta }}</span>+ </template>+ </AppCombobox>+ </template>+ <template #leading="{ item: entry }">+ <IconPreview :svg="previews.get(entry.value)" class="size-5 text-surface" />+ </template>+ <template v-if="items.length > 0" #footer="{ highlighted }">+ <p class="flex h-5 items-center gap-1.5 truncate px-1 text-[11px] text-muted">+ <template v-if="highlighted">+ <span class="truncate text-surface">{{ highlighted.label }}</span>+ <span class="truncate">{{ details(highlighted.value) }}</span>+ </template>+ <span v-else class="truncate">{{ summary }}</span>+ </p>+ </template>+ </AppPicker>+</template>diff --git a/src/components/icon-picker/IconPreview.vue b/src/components/icon-picker/IconPreview.vuenew file mode 100644index 000000000..74d4cc348--- /dev/null+++ b/src/components/icon-picker/IconPreview.vue@@ -0,0 +1,21 @@+<script setup lang="ts">+import { computed } from 'vue'++/**+ * An icon drawn in the text color: its SVG markup serves as a mask, so it never runs as+ * markup in the page. Blank until the markup arrives, rather than a filled square.+ */+const { svg } = defineProps<{ svg?: string | null }>()+const style = computed(() =>+ svg ? { '--icon-preview': `url("data:image/svg+xml,${encodeURIComponent(svg)}")` } : undefined+)+</script>++<template>+ <span+ aria-hidden="true"+ class="inline-block size-4 shrink-0 mask-(--icon-preview) mask-contain mask-center mask-no-repeat data-[drawn]:bg-current"+ :data-drawn="svg ? '' : undefined"+ :style="style"+ />+</template>diff --git a/src/components/icon-picker/InsertIconButton.vue b/src/components/icon-picker/InsertIconButton.vuenew file mode 100644index 000000000..acf248f0b--- /dev/null+++ b/src/components/icon-picker/InsertIconButton.vue@@ -0,0 +1,42 @@+<script setup lang="ts">+import IconSmilePlus from '~icons/lucide/smile-plus'++import { usePanelMessages } from '@open-pencil/vue'++import { useEditorStore } from '@/app/editor/active-store'+import { toast } from '@/app/shell/ui'+import ToolButton from '@/components/Toolbar/ToolButton.vue'+import type { ToolbarUI } from '@/components/Toolbar/types'++import IconPicker from './IconPicker.vue'++/** The toolbar's icon picker, also opened by the Insert Icon command. */+const { ui, mobile = false } = defineProps<{ ui?: ToolbarUI; mobile?: boolean }>()+const store = useEditorStore()+const panels = usePanelMessages()++function insert(name: string) {+ store.insertIcon(name).catch(() => toast.error(panels.value.insertIconFailed))+}+</script>++<template>+ <IconPicker+ v-model:open="store.state.iconPickerOpen"+ :heading="panels.insertIcon"+ :tooltip="panels.insertIcon"+ side="top"+ align="center"+ @select="insert"+ >+ <template #trigger>+ <ToolButton+ :icon="IconSmilePlus"+ :label="panels.insertIcon"+ :active="store.state.iconPickerOpen"+ :mobile="mobile"+ :ui="ui"+ />+ </template>+ </IconPicker>+</template>diff --git a/src/components/properties/IconSection.vue b/src/components/properties/IconSection.vuenew file mode 100644index 000000000..d07e12aef--- /dev/null+++ b/src/components/properties/IconSection.vue@@ -0,0 +1,55 @@+<script setup lang="ts">+import { tv } from 'tailwind-variants'++import { 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 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 styles = tv(theme)()+</script>++<template>+ <PanelSection v-if="name" :label="panels.icon">+ <PanelFieldGroup :label="panels.swapIcon">+ <IconPicker+ :heading="panels.swapIcon"+ :selected="name"+ :set="name.slice(0, name.indexOf(':'))"+ @select="swap"+ >+ <template #trigger>+ <button+ type="button"+ aria-haspopup="listbox"+ data-property="icon-name"+ :aria-label="panels.swapIcon"+ :class="styles.trigger()"+ >+ <IconPreview :svg="preview" class="mr-1.5 size-3.5 text-surface" />+ <span :class="styles.value()">+ {{ name.slice(name.indexOf(':') + 1) }}+ <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" />+ </button>+ </template>+ </IconPicker>+ </PanelFieldGroup>+ <PanelFieldGroup v-if="color" :label="panels.iconColor" class="mt-1.5">+ <ColorInput+ :color="color"+ editable+ data-property="icon-color"+ @update="setColor"+ @open-change="setColorPicking"+ />+ </PanelFieldGroup>+ </PanelSection>+</template>diff --git a/src/components/ui/select/AppCombobox.vue b/src/components/ui/select/AppCombobox.vueindex 0758052ac..4da204ca0 100644--- a/src/components/ui/select/AppCombobox.vue+++ b/src/components/ui/select/AppCombobox.vue@@ -40,6 +40,8 @@ interface AppComboboxProps {emptyLabel?: stringdisabled?: booleanresultLimit?: number+ /** How the open list lines up with the trigger; `end` for a trigger at the end of a field. */+ align?: 'start' | 'center' | 'end'ui?: ComponentUI<AppComboboxTheme>}@@ -53,6 +55,7 @@ const {emptyLabel = 'No results',disabled = false,resultLimit = 100,+ align = 'start',ui} = defineProps<AppComboboxProps>()@@ -120,6 +123,7 @@ function updateOpen(value: boolean): void {<ComboboxPortal v-if="portalActive"><ComboboxContentposition="popper"+ :align="align":side-offset="2":class="styles.content({ class: ui?.content })">diff --git a/src/components/ui/select/AppPicker.stories.ts b/src/components/ui/select/AppPicker.stories.tsindex d3875bea3..0abbd9c98 100644--- a/src/components/ui/select/AppPicker.stories.ts+++ b/src/components/ui/select/AppPicker.stories.ts@@ -11,7 +11,7 @@ const meta = {docs: {description: {component:- 'A searchable, grouped list that opens beside the properties panel. Comfortable rows carry a thumbnail and a description; compact rows suit plain names such as variables.'+ 'A searchable, grouped list that opens beside the properties panel. Comfortable rows carry a thumbnail and a description; compact rows suit plain names such as variables; the grid shows thumbnails alone, naming the highlighted one in the footer.'}}}@@ -59,3 +59,16 @@ export const CompactWithFooter: Story = {)}}++export const Grid: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ const page = within(canvasElement.ownerDocument.body)+ await userEvent.click(canvas.getByRole('button', { name: 'Insert shape' }))+ const search = await page.findByPlaceholderText('Search shapes')+ await waitFor(() => expect(search).toHaveFocus())+ // The first shape is highlighted on opening; down moves a row of eight, to the ninth.+ await userEvent.keyboard('{ArrowDown}{Enter}')+ await waitFor(() => expect(canvas.getByText(/^Chosen:/)).toHaveTextContent('Chosen: star'))+ }+}diff --git a/src/components/ui/select/AppPicker.vue b/src/components/ui/select/AppPicker.vueindex 8710abef2..b44a426b4 100644--- a/src/components/ui/select/AppPicker.vue+++ b/src/components/ui/select/AppPicker.vue@@ -25,6 +25,20 @@ export interface AppPickerProps {/** Tooltip on the trigger; wraps the popover trigger so both reach the same element. */tooltip?: stringdensity?: 'compact' | 'comfortable'+ /**+ * `grid` shows each item's thumbnail alone, eight to a row, with the highlighted item's label+ * passed to the footer; for browsing many items by sight, such as icons.+ */+ layout?: 'list' | 'grid'+ /** More items follow the shown ones; scrolling near the end emits `loadMore`. */+ hasMore?: boolean+ /** The items are on their way: placeholders stand in for them, and `emptyLabel` is announced. */+ loading?: boolean+ /**+ * `local` filters `items` by the query; `remote` shows them as given, for a list the owner+ * searches itself through `v-model:query`.+ */+ search?: 'local' | 'remote'side?: 'left' | 'right' | 'top' | 'bottom'align?: 'start' | 'center' | 'end'ui?: ComponentUI<AppPickerTheme>@@ -35,12 +49,15 @@ export interface AppPickerSlots {trigger(): VNode[]/** Thumbnail or icon before an item's label. */leading?(props: { item: AppPickerItem }): VNode[]- /** Actions below the list, such as creating a new choice. */- footer?(props: { close: () => void }): VNode[]+ /** A control at the end of the search field that narrows the list, such as a category. */+ 'search-trailing'?(): VNode[]+ /** Actions or details below the list; `highlighted` is the item under the pointer or keys. */+ footer?(props: { close: () => void; highlighted: AppPickerItem | null }): VNode[]}</script><script setup lang="ts">+import { useInfiniteScroll, unrefElement } from '@vueuse/core'import {ListboxContent,ListboxFilter,@@ -56,13 +73,13 @@ import {type AcceptableValue} from 'reka-ui'import { tv } from 'tailwind-variants'-import { computed, ref, watch } from 'vue'+import { computed, shallowRef, useTemplateRef, watch, type ComponentPublicInstance } from 'vue'import { fuzzySearch, useRetainedPopup } from '@open-pencil/vue'import AppButton from '@/components/ui/button/AppButton.vue'import Tip from '@/components/ui/overlay/Tip.vue'-import theme from '@/theme/select/picker'+import theme, { APP_PICKER_GRID_COLUMNS } from '@/theme/select/picker'const {heading,@@ -73,24 +90,30 @@ const {selected,tooltip,density = 'comfortable',+ layout = 'list',+ hasMore = false,+ loading = false,+ search = 'local',side = 'left',align = 'start',ui} = defineProps<AppPickerProps>()-const emit = defineEmits<{ select: [value: string] }>()+const emit = defineEmits<{ select: [value: string]; loadMore: [] }>()const slots = defineSlots<AppPickerSlots>()const open = defineModel<boolean>('open', { default: false })const { portalActive } = useRetainedPopup(open, () => close())-const query = ref('')+const query = defineModel<string>('query', { default: '' })// However the list closes, by the user or from outside through v-model, it reopens unfiltered.watch(open, (isOpen) => {if (!isOpen) query.value = ''})-const styles = computed(() => tv(theme)({ density }))+const styles = computed(() => tv(theme)({ density, layout }))const matches = computed(() => {const term = query.value.trim()- return term ? fuzzySearch(items, ['label', 'description', 'group'], term) : items+ return term && search === 'local'+ ? fuzzySearch(items, ['label', 'description', 'group'], term)+ : items})const groups = computed(() => {const byGroup = new Map<string, AppPickerItem[]>()@@ -101,6 +124,47 @@ const groups = computed(() => {return [...byGroup.entries()]})+const highlighted = shallowRef<AppPickerItem | null>(null)+watch(matches, () => {+ highlighted.value = null+})+function highlight(payload: { value: AcceptableValue } | undefined) {+ highlighted.value = matches.value.find((item) => item.value === payload?.value) ?? null+}++/** Placeholders shown while loading: the grid's visible rows, or a few list rows. */+const LOADING_PLACEHOLDERS = computed(() => (layout === 'grid' ? APP_PICKER_GRID_COLUMNS * 7 : 3))++const ROW_KEYS = new Map([+ ['ArrowDown', 1],+ ['ArrowUp', -1]+])+// ListboxRoot is generic, so its instance type is spelled as the part used here.+const listbox = useTemplateRef<{ highlightItem: (value: AcceptableValue) => void }>('listboxRoot')+// Reka moves through a listbox one item at a time. The grid lays it out horizontally, so+// left and right move an item, and up and down move a row here; with nothing highlighted, they+// start at the first item.+function moveRow(event: KeyboardEvent) {+ const rows = ROW_KEYS.get(event.key)+ if (layout !== 'grid' || !rows) return+ event.preventDefault()+ const current = highlighted.value?.value+ const index = matches.value.findIndex((item) => item.value === current)+ const target = index === -1 ? 0 : index + rows * APP_PICKER_GRID_COLUMNS+ const next = matches.value[Math.min(Math.max(target, 0), matches.value.length - 1)]+ if (next) listbox.value?.highlightItem(next.value)+}++const list = useTemplateRef<ComponentPublicInstance>('listContent')+useInfiniteScroll(+ () => unrefElement(list),+ () => emit('loadMore'),+ {+ distance: 120,+ canLoadMore: () => open.value && hasMore+ }+)+function close() {open.value = false}@@ -124,6 +188,7 @@ function select(value: AcceptableValue) {:side="side":align="align":side-offset="8"+ :collision-padding="8":aria-label="heading":class="styles.content({ class: ui?.content })"@open-auto-focus.prevent@@ -136,7 +201,15 @@ function select(value: AcceptableValue) {</AppButton></PopoverClose></div>- <ListboxRoot class="flex min-h-0 flex-col" highlight-on-hover @update:model-value="select">+ <ListboxRoot+ ref="listboxRoot"+ class="flex min-h-0 flex-1 flex-col"+ highlight-on-hover+ :orientation="layout === 'grid' ? 'horizontal' : 'vertical'"+ @update:model-value="select"+ @highlight="highlight"+ @keydown="moveRow"+ ><div :class="styles.search({ class: ui?.search })"><icon-lucide-search :class="styles.searchIcon({ class: ui?.searchIcon })" /><ListboxFilter@@ -146,12 +219,30 @@ function select(value: AcceptableValue) {:aria-label="searchPlaceholder":class="styles.input({ class: ui?.input })"/>+ <slot name="search-trailing" /></div>- <ListboxContent :class="styles.list({ class: ui?.list })" :aria-label="heading">- <p v-if="groups.length === 0" :class="styles.empty({ class: ui?.empty })">+ <ListboxContent+ ref="listContent"+ :class="styles.list({ class: ui?.list })"+ :aria-label="heading"+ >+ <div v-if="groups.length === 0 && loading" :class="styles.group({ class: ui?.group })">+ <span class="sr-only" role="status">{{ emptyLabel }}</span>+ <span+ v-for="index in LOADING_PLACEHOLDERS"+ :key="index"+ aria-hidden="true"+ :class="styles.placeholder({ class: ui?.placeholder })"+ />+ </div>+ <p v-else-if="groups.length === 0" :class="styles.empty({ class: ui?.empty })">{{ emptyLabel }}</p>- <ListboxGroup v-for="[group, entries] in groups" :key="group">+ <ListboxGroup+ v-for="[group, entries] in groups"+ :key="group"+ :class="styles.group({ class: ui?.group })"+ ><ListboxGroupLabel v-if="group" :class="styles.groupLabel({ class: ui?.groupLabel })">{{ group }}</ListboxGroupLabel>@@ -162,6 +253,8 @@ function select(value: AcceptableValue) {:value="item.value":disabled="item.disabled":aria-disabled="item.disabled || undefined"+ :aria-label="layout === 'grid' ? item.label : undefined"+ :data-selected="item.value === selected || undefined":class="styles.item({ class: ui?.item })"><span v-if="slots.leading" :class="styles.leading({ class: ui?.leading })">@@ -185,7 +278,7 @@ function select(value: AcceptableValue) {</ListboxContent></ListboxRoot><div v-if="slots.footer" :class="styles.footer({ class: ui?.footer })">- <slot name="footer" :close="close" />+ <slot name="footer" :close="close" :highlighted="highlighted" /></div></PopoverContent></PopoverPortal>diff --git a/src/components/ui/select/examples/Picker.vue b/src/components/ui/select/examples/Picker.vueindex efd557d5b..bb981ec16 100644--- a/src/components/ui/select/examples/Picker.vue+++ b/src/components/ui/select/examples/Picker.vue@@ -1,8 +1,15 @@<script setup lang="ts">import { ref } from 'vue'+import IconCircle from '~icons/lucide/circle'import IconComponent from '~icons/lucide/component'import IconDiamond from '~icons/lucide/diamond'+import IconHeart from '~icons/lucide/heart'+import IconHexagon from '~icons/lucide/hexagon'import IconPlus from '~icons/lucide/plus'+import IconShapes from '~icons/lucide/shapes'+import IconSquare from '~icons/lucide/square'+import IconStar from '~icons/lucide/star'+import IconTriangle from '~icons/lucide/triangle'import AppButton from '@/components/ui/button/AppButton.vue'import IconButton from '@/components/ui/button/IconButton.vue'@@ -26,6 +33,14 @@ const variables: AppPickerItem[] = [{ value: 'space/lg', label: 'Space/lg', group: 'Spacing' },{ value: 'radius/md', label: 'Radius/md', group: 'Radius', disabled: true }]+// More than a row of the grid, so moving a row by keyboard lands on a known shape.+const SHAPE_ICONS = [IconCircle, IconSquare, IconTriangle, IconHexagon, IconStar, IconHeart]+const shapes: AppPickerItem[] = ['Circle', 'Square', 'Triangle', 'Hexagon', 'Star', 'Heart']+ .flatMap((name) => [name, `${name} outline`])+ .map((label) => ({ value: label.toLowerCase().replace(' ', '-'), label, description: 'Shapes' }))+function shapeIcon(value: string) {+ return SHAPE_ICONS[Math.floor(shapes.findIndex((shape) => shape.value === value) / 2)]+}const chosen = ref('')</script>@@ -69,6 +84,28 @@ const chosen = ref('')</template></AppPicker></div>+ <div class="flex items-center justify-between text-xs text-surface">+ Shapes+ <AppPicker+ heading="Insert shape"+ :items="shapes"+ layout="grid"+ search-placeholder="Search shapes"+ empty-label="No shapes found"+ close-label="Close"+ @select="chosen = $event"+ >+ <template #trigger>+ <IconButton label="Insert shape"><IconShapes class="size-3.5" /></IconButton>+ </template>+ <template #leading="{ item }"+ ><component :is="shapeIcon(item.value)" class="size-4"+ /></template>+ <template #footer="{ highlighted }">+ <p class="h-5 truncate px-1 text-[11px] text-surface">{{ highlighted?.label }}</p>+ </template>+ </AppPicker>+ </div><p class="text-[11px] text-muted">Chosen: {{ chosen || '—' }}</p></div></template>diff --git a/src/theme/select/picker.ts b/src/theme/select/picker.tsindex 2e861a2a7..0ad5afd86 100644--- a/src/theme/select/picker.ts+++ b/src/theme/select/picker.ts@@ -2,6 +2,9 @@ import { motionStyles } from '../motion/styles'import { floatingSurface } from '../overlay'import { panelFieldBase } from '../panel/field'+/** Choices per row in the grid layout; keyboard navigation moves this many for a row. */+export const APP_PICKER_GRID_COLUMNS = 8+/** A searchable list of choices that opens beside the properties panel, as Figma's pickers do. */const appPickerTheme = {slots: {@@ -17,6 +20,7 @@ const appPickerTheme = {input:'h-full min-w-0 flex-1 bg-transparent pr-2 pl-7 text-xs text-surface outline-none placeholder:text-muted',list: 'flex min-h-0 flex-col gap-2 overflow-y-auto px-2 pb-2',+ group: '',groupLabel: 'px-1 pb-1 text-[10px] font-medium tracking-wide text-muted uppercase',item: 'flex w-full cursor-pointer items-center gap-2 rounded px-1 py-1 text-left outline-none select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[highlighted]:bg-hover',leading:@@ -26,6 +30,7 @@ const appPickerTheme = {description: 'block truncate text-[10px] text-muted',check: 'size-3 shrink-0 text-primary',empty: 'px-1 py-2 text-[11px] text-muted',+ placeholder: 'block h-10 rounded bg-hover motion-safe:animate-pulse',footer: 'border-t border-border p-1'},variants: {@@ -34,9 +39,27 @@ const appPickerTheme = {compact: { leading: 'size-5 border-0 bg-transparent', item: 'min-h-7' },/** A thumbnail and a description line, for components and assets. */comfortable: {}+ },+ layout: {+ list: {},+ /** Thumbnails alone, named in the footer as they are highlighted, for browsing many. */+ grid: {+ // A fixed height keeps the picker still while results arrive and leaves room below its+ // search for menus such as a category list.+ content: 'h-96 w-72',+ list: 'flex-1',+ empty: 'm-auto max-w-60 text-center',+ group: 'grid grid-cols-8 gap-0.5',+ groupLabel: 'col-span-full pt-1',+ item: 'aspect-square justify-center p-0 data-[selected]:ring-1 data-[selected]:ring-primary',+ placeholder: 'aspect-square h-auto',+ leading: 'size-full border-0 bg-transparent text-surface',+ text: 'sr-only',+ check: 'hidden'+ }}},- defaultVariants: { density: 'comfortable' as const }+ defaultVariants: { density: 'comfortable' as const, layout: 'list' as const }}export type AppPickerTheme = typeof appPickerThemediff --git a/tests/e2e/design/icons.spec.ts b/tests/e2e/design/icons.spec.tsnew file mode 100644index 000000000..3a2dee2fc--- /dev/null+++ b/tests/e2e/design/icons.spec.ts@@ -0,0 +1,173 @@+import type { Page } from '@playwright/test'++import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'+import { openAppMenu } from '#tests/helpers/menu'+import { propertyField, propertySection } from '#tests/helpers/properties'+import { getNodeById, getPageChildren, getSelectedNode } from '#tests/helpers/store'++/** A small icon set served in place of the Iconify API, so the workflow needs no network. */+const SET = {+ prefix: 'test',+ width: 24,+ height: 24,+ icons: {+ square: { body: '<path fill="currentColor" d="M2 2h20v20H2z"/>' },+ ring: { body: '<circle cx="12" cy="12" r="9" fill="none" stroke="currentColor"/>' }+ }+}++const ctx = useEditorSetupWithClear()+/** Requests per endpoint, and the set each search was limited to. */+const requests = { search: 0, sets: 0, searchPrefixes: [] as (string | null)[] }++test.beforeAll(async () => {+ await ctx.page.route('https://api.iconify.design/**', async (route) => {+ const url = new URL(route.request().url())+ if (url.pathname === '/search') {+ requests.search+++ requests.searchPrefixes.push(url.searchParams.get('prefix'))+ await route.fulfill({+ json: {+ icons: ['test:square', 'test:ring'],+ total: 2,+ collections: { test: { name: 'Test Icons', total: 2 } }+ }+ })+ } else if (url.pathname === '/collections') {+ await route.fulfill({+ json: { test: { name: 'Test Icons', total: 2, license: { title: 'MIT' } } }+ })+ } else if (url.pathname === '/collection') {+ await route.fulfill({ json: { uncategorized: ['square', 'ring'] } })+ } else {+ requests.sets+++ await route.fulfill({ json: SET })+ }+ })+})++test.beforeEach(() => {+ requests.search = 0+ requests.sets = 0+ requests.searchPrefixes = []+})++async function pick(page: Page, picker: string, query: string, icon: string) {+ const dialog = page.getByRole('dialog', { name: picker })+ await expect(dialog).toBeVisible()+ await dialog.getByRole('textbox').fill(query)+ await dialog.getByRole('option', { name: icon }).click()+ await expect(dialog).toBeHidden()+}++async function insertSquare(page: Page) {+ await page.getByRole('button', { name: 'Insert icon' }).click()+ await pick(page, 'Insert icon', 'shape', 'square')+ await expect(propertyField(page, 'icon-name')).toContainText('square')+}++test('the toolbar inserts a picked icon, selected, as one undo step', async () => {+ const { page, canvas } = ctx+ await insertSquare(page)++ const icon = await getSelectedNode(page)+ expect(icon).toMatchObject({ type: 'FRAME', name: 'Icon / test: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 })++ await canvas.undo()+ expect(await getPageChildren(page)).toEqual([])+})++test('the Object menu opens the same picker', async () => {+ const { page } = ctx+ const menu = await openAppMenu(page, 'Object')+ await menu.getByRole('menuitem', { name: 'Insert Icon…' }).click()+ await pick(page, 'Insert icon', 'shape', 'ring')++ expect(await getSelectedNode(page)).toMatchObject({ name: 'Icon / test:ring' })+})++test('the Icon section swaps the glyph in place, undoably', async () => {+ const { page, canvas } = ctx+ await insertSquare(page)+ const before = await getSelectedNode(page)++ await propertySection(page, 'Icon').getByRole('button', { name: 'Swap icon' }).click()+ await pick(page, 'Swap icon', 'shape', 'ring')++ await expect(propertyField(page, 'icon-name')).toContainText('ring')+ expect(await getSelectedNode(page)).toMatchObject({+ id: before?.id,+ x: before?.x,+ y: before?.y,+ name: 'Icon / test:ring'+ })++ await canvas.undo()+ await expect(propertyField(page, 'icon-name')).toContainText('square')+})++test('the Icon section recolors the icon', async () => {+ const { page, canvas } = ctx+ await insertSquare(page)+ const pathId = (await getSelectedNode(page))?.childIds[0] ?? ''++ const hex = propertyField(page, 'icon-color').getByTestId('color-hex-input')+ await hex.fill('FF0000')+ await hex.press('Enter')+ // Undo in a focused field undoes its text; the document's undo needs focus elsewhere.+ await hex.blur()++ await expect+ .poll(async () => (await getNodeById(page, pathId))?.fills[0]?.color)+ .toMatchObject({ r: 1, g: 0, b: 0 })++ await canvas.undo()+ await expect+ .poll(async () => (await getNodeById(page, pathId))?.fills[0]?.color)+ .toMatchObject({ r: 0, g: 0, b: 0 })+})++test('a chosen set is browsed without a query, and a query searches only it', async () => {+ const { page } = ctx+ await page.getByRole('button', { name: 'Insert icon' }).click()+ const dialog = page.getByRole('dialog', { name: 'Insert icon' })+ await dialog.getByRole('button', { name: 'Icon set' }).click()+ await page.getByRole('option', { name: /Test Icons/ }).click()++ // Each icon of the set shows once, under the set or ahead of it as recent.+ await expect(dialog.getByRole('option')).toHaveCount(2)+ expect(requests.search).toBe(0)++ await dialog.getByRole('textbox').fill('shape')+ await expect.poll(() => requests.searchPrefixes).toEqual(['test'])+ await expect(dialog.getByRole('option')).toHaveCount(2)++ await page.keyboard.press('Escape')+ await expect(dialog).toBeHidden()+})++test('icons in the file and picked lately come first', async () => {+ const { page, canvas } = ctx+ await insertSquare(page)+ await page.getByRole('button', { name: 'Insert icon' }).click()+ const dialog = page.getByRole('dialog', { name: 'Insert icon' })+ await expect(+ dialog.getByRole('group', { name: 'In this file' }).getByRole('option', { name: 'square' })+ ).toBeVisible()+ // Canvas shortcuts wait for the picker to finish closing.+ await page.keyboard.press('Escape')+ await expect(dialog).toBeHidden()++ // With the icon gone from the file, it is still among the recent ones.+ await canvas.clearCanvas()+ expect(await getPageChildren(page)).toEqual([])+ await page.getByRole('button', { name: 'Insert icon' }).click()+ await expect(+ dialog.getByRole('group', { name: 'Recent' }).getByRole('option', { name: 'square' })+ ).toBeVisible()+ await page.keyboard.press('Escape')+ await expect(dialog).toBeHidden()+})diff --git a/tests/engine/icons/iconify.test.ts b/tests/engine/icons/iconify.test.tsindex 6ad1df12d..854d54152 100644--- a/tests/engine/icons/iconify.test.ts+++ b/tests/engine/icons/iconify.test.ts@@ -1,8 +1,18 @@import { describe, expect, test, beforeAll } from 'bun:test'-import { fetchIcon, fetchIcons, searchIcons, searchIconsBatch } from '@open-pencil/core'+import { createIconifyProvider } from '@open-pencil/core'-import { expectDefined } from '#tests/helpers/assert'+const provider = createIconifyProvider()+const fetchIcons = (names: string[], size = 24) => provider.icons(names, size)+const searchIcons = (query: string, options?: { limit?: number; prefix?: string }) =>+ provider.search(query, options)++/** One icon, failing like a caller that needs it. */+async function fetchIcon(name: string, size = 24) {+ const icon = (await fetchIcons([name], size)).get(name)+ if (!icon) throw new Error(`Icon "${name}" not found`)+ return icon+}let hasNetwork = truebeforeAll(async () => {@@ -126,12 +136,3 @@ describe('searchIcons', () => {}})})--describe('searchIconsBatch', () => {- networkTest('searches multiple queries in parallel', async () => {- const results = await searchIconsBatch(['heart', 'arrow'], { limit: 5 })- expect(results.size).toBe(2)- expect(expectDefined(results.get('heart'), 'heart results').icons.length).toBeGreaterThan(0)- expect(expectDefined(results.get('arrow'), 'arrow results').icons.length).toBeGreaterThan(0)- })-})diff --git a/tests/engine/text/edit-undo.test.ts b/tests/engine/text/edit-undo.test.tsindex 3635b66e2..45677411b 100644--- a/tests/engine/text/edit-undo.test.ts+++ b/tests/engine/text/edit-undo.test.ts@@ -6,6 +6,7 @@ import { SceneGraph, TextEditor, UndoManager } from '@open-pencil/core'import type { StyleRun } from '@open-pencil/core'import { createTextActions } from '@open-pencil/core/editor'import type { EditorContext, EditorState } from '@open-pencil/core/editor'+import { iconify } from '@open-pencil/core/icons'import { getInstanceOverride } from '@open-pencil/scene-graph'import type { DerivedTextGlyph } from '@open-pencil/scene-graph'@@ -49,6 +50,7 @@ function setup() {getCk: () => null,loadFont: async () => null,getViewportSize: () => ({ width: 800, height: 600 }),+ icons: iconify,subscribeToGraph: () => undefined,resolveFigmaClipboardImages: null,beginInteractiveEdit: () => () => undefined,