AI-native design editor. Open-source Figma alternative.
feat: copy node ID / XPath from context menu, CLI selection command
Danila Poyarkov714390b54b0b
diff --git a/packages/cli/src/commands/selection.ts b/packages/cli/src/commands/selection.tsnew file mode 100644index 000000000..a80d88d69--- /dev/null+++ b/packages/cli/src/commands/selection.ts@@ -0,0 +1,54 @@+import { defineCommand } from 'citty'++import { rpc } from '../app-client'+import { bold, entity, fmtList, formatType, printError } from '../format'++interface SelectionNode {+ id: string+ name: string+ type: string+ width: number+ height: number+ xpath: string | null+}++export default defineCommand({+ meta: { description: 'Get current selection from the running app' },+ args: {+ json: { type: 'boolean', description: 'Output as JSON' }+ },+ async run({ args }) {+ try {+ const nodes = await rpc<SelectionNode[]>('selection')++ if (args.json) {+ console.log(JSON.stringify(nodes, null, 2))+ return+ }++ if (nodes.length === 0) {+ console.log('\n No nodes selected.\n')+ return+ }++ console.log('')+ console.log(bold(` ${nodes.length} selected node${nodes.length !== 1 ? 's' : ''}`))+ console.log('')+ console.log(+ fmtList(+ nodes.map((n) => ({+ header: entity(formatType(n.type), n.name, n.id),+ details: {+ size: `${n.width}×${n.height}`,+ ...(n.xpath ? { xpath: n.xpath } : {})+ }+ }))+ )+ )+ console.log('')+ } catch (error) {+ printError(error)+ process.exit(1)+ }+ }+})diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.tsindex 58ab40bbe..22d5e69eb 100755--- a/packages/cli/src/index.ts+++ b/packages/cli/src/index.ts@@ -12,6 +12,7 @@ import lint from './commands/lint'import node from './commands/node'import pages from './commands/pages'import query from './commands/query'+import selection from './commands/selection'import tree from './commands/tree'import variables from './commands/variables'@@ -35,6 +36,7 @@ const main = defineCommand({query,node,pages,+ selection,tree,variables}diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex a8baf9502..0279efed9 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -96,7 +96,7 @@ export type {StepBudget} from './tools'export { executeRpcCommand, ALL_RPC_COMMANDS } from './rpc'-export { queryByXPath, matchByXPath } from './xpath'+export { queryByXPath, matchByXPath, nodeToXPath } from './xpath'export type { XPathQueryOptions } from './xpath'export {okhclToRGBA,diff --git a/packages/core/src/xpath.ts b/packages/core/src/xpath.tsindex 2cd13f141..7939f76c3 100644--- a/packages/core/src/xpath.ts+++ b/packages/core/src/xpath.ts@@ -247,6 +247,58 @@ export async function queryByXPath(return results}+/**+ * Build an XPath selector that uniquely identifies a node in its page.+ *+ * Strategy: walk from the node up to the page root, building path segments.+ * Each segment uses the node type as the element name. If the name is+ * unique among siblings of the same type, use `[@name='...']`.+ * Otherwise fall back to a positional predicate `[n]`.+ */+export function nodeToXPath(graph: SceneGraph, nodeId: string): string | null {+ const node = graph.getNode(nodeId)+ if (!node) return null++ const segments: string[] = []+ let current = node++ for (;;) {+ if (current.type === 'CANVAS') break+ const parentId: string | null = current.parentId+ const parent: SceneNode | undefined = parentId ? graph.getNode(parentId) : undefined++ segments.unshift(buildSegment(graph, current, parent))+ if (!parent || parent.type === 'CANVAS') break+ current = parent+ }++ return segments.length > 0 ? '//' + segments.join('/') : null+}++function buildSegment(graph: SceneGraph, node: SceneNode, parent: SceneNode | undefined): string {+ const tag = node.type+ const escaped = escapeXPathName(node.name)++ if (!parent) return `${tag}[@name=${escaped}]`++ const siblings = parent.childIds+ .map((id) => graph.getNode(id))+ .filter((n): n is SceneNode => n !== undefined && n.type === tag)++ const sameNameCount = siblings.filter((s) => s.name === node.name).length+ if (sameNameCount <= 1) return `${tag}[@name=${escaped}]`++ const index = siblings.findIndex((s) => s.id === node.id) + 1+ return `${tag}[${index}]`+}++function escapeXPathName(s: string): string {+ if (!s.includes("'")) return `'${s}'`+ if (!s.includes('"')) return `"${s}"`+ const parts = s.split("'").map((p) => `'${p}'`)+ return `concat(${parts.join(', "\'", ')})`+}+export async function matchByXPath(graph: SceneGraph,selector: string,diff --git a/packages/vue/src/i18n/messages.ts b/packages/vue/src/i18n/messages.tsindex c1a27671a..d988fc840 100644--- a/packages/vue/src/i18n/messages.ts+++ b/packages/vue/src/i18n/messages.ts@@ -38,7 +38,16 @@ export const menuMessages = i18n('menu', {bold: 'Bold',italic: 'Italic',- underline: 'Underline'+ underline: 'Underline',++ pasteHere: 'Paste here',+ copyPasteAs: 'Copy/Paste as',+ copyAsText: 'Copy as text',+ copyAsSVG: 'Copy as SVG',+ copyAsPNG: 'Copy as PNG',+ copyAsJSX: 'Copy as JSX',+ copyNodeId: 'Copy node ID',+ copyXPath: 'Copy XPath'})export const commandMessages = i18n('commands', {diff --git a/packages/vue/src/locales/de.json b/packages/vue/src/locales/de.jsonindex 25137c3f2..98ed324ed 100644--- a/packages/vue/src/locales/de.json+++ b/packages/vue/src/locales/de.json@@ -30,7 +30,15 @@"toggleUI": "UI umschalten","bold": "Fett","italic": "Kursiv",- "underline": "Unterstrichen"+ "underline": "Unterstrichen",+ "pasteHere": "Hier einfügen",+ "copyPasteAs": "Kopieren/Einfügen als",+ "copyAsText": "Als Text kopieren",+ "copyAsSVG": "Als SVG kopieren",+ "copyAsPNG": "Als PNG kopieren",+ "copyAsJSX": "Als JSX kopieren",+ "copyNodeId": "Knoten-ID kopieren",+ "copyXPath": "XPath kopieren"},"commands": {"undo": "Rückgängig",diff --git a/packages/vue/src/locales/es.json b/packages/vue/src/locales/es.jsonindex 0d142353d..123125631 100644--- a/packages/vue/src/locales/es.json+++ b/packages/vue/src/locales/es.json@@ -30,7 +30,15 @@"toggleUI": "Alternar interfaz","bold": "Negrita","italic": "Cursiva",- "underline": "Subrayado"+ "underline": "Subrayado",+ "pasteHere": "Pegar aquí",+ "copyPasteAs": "Copiar/Pegar como",+ "copyAsText": "Copiar como texto",+ "copyAsSVG": "Copiar como SVG",+ "copyAsPNG": "Copiar como PNG",+ "copyAsJSX": "Copiar como JSX",+ "copyNodeId": "Copiar ID del nodo",+ "copyXPath": "Copiar XPath"},"commands": {"undo": "Deshacer",diff --git a/packages/vue/src/locales/fr.json b/packages/vue/src/locales/fr.jsonindex 06a418d93..b2d076c91 100644--- a/packages/vue/src/locales/fr.json+++ b/packages/vue/src/locales/fr.json@@ -30,7 +30,15 @@"toggleUI": "Basculer l’interface","bold": "Gras","italic": "Italique",- "underline": "Souligné"+ "underline": "Souligné",+ "pasteHere": "Coller ici",+ "copyPasteAs": "Copier/Coller en tant que",+ "copyAsText": "Copier en texte",+ "copyAsSVG": "Copier en SVG",+ "copyAsPNG": "Copier en PNG",+ "copyAsJSX": "Copier en JSX",+ "copyNodeId": "Copier l'ID du nœud",+ "copyXPath": "Copier le XPath"},"commands": {"undo": "Annuler",diff --git a/packages/vue/src/locales/it.json b/packages/vue/src/locales/it.jsonindex 402abc36a..a0a023633 100644--- a/packages/vue/src/locales/it.json+++ b/packages/vue/src/locales/it.json@@ -30,7 +30,15 @@"toggleUI": "Mostra/nascondi interfaccia","bold": "Grassetto","italic": "Corsivo",- "underline": "Sottolineato"+ "underline": "Sottolineato",+ "pasteHere": "Incolla qui",+ "copyPasteAs": "Copia/Incolla come",+ "copyAsText": "Copia come testo",+ "copyAsSVG": "Copia come SVG",+ "copyAsPNG": "Copia come PNG",+ "copyAsJSX": "Copia come JSX",+ "copyNodeId": "Copia ID nodo",+ "copyXPath": "Copia XPath"},"commands": {"undo": "Annulla",diff --git a/packages/vue/src/locales/pl.json b/packages/vue/src/locales/pl.jsonindex 7c604c9bc..eaf8fc417 100644--- a/packages/vue/src/locales/pl.json+++ b/packages/vue/src/locales/pl.json@@ -30,7 +30,15 @@"toggleUI": "Przełącz interfejs","bold": "Pogrubienie","italic": "Kursywa",- "underline": "Podkreślenie"+ "underline": "Podkreślenie",+ "pasteHere": "Wklej tutaj",+ "copyPasteAs": "Kopiuj/Wklej jako",+ "copyAsText": "Kopiuj jako tekst",+ "copyAsSVG": "Kopiuj jako SVG",+ "copyAsPNG": "Kopiuj jako PNG",+ "copyAsJSX": "Kopiuj jako JSX",+ "copyNodeId": "Kopiuj ID węzła",+ "copyXPath": "Kopiuj XPath"},"commands": {"undo": "Cofnij",diff --git a/packages/vue/src/locales/ru.json b/packages/vue/src/locales/ru.jsonindex 19727f334..fd9ebb9a3 100644--- a/packages/vue/src/locales/ru.json+++ b/packages/vue/src/locales/ru.json@@ -30,7 +30,15 @@"toggleUI": "Переключить интерфейс","bold": "Жирный","italic": "Курсив",- "underline": "Подчёркнутый"+ "underline": "Подчёркнутый",+ "pasteHere": "Вставить сюда",+ "copyPasteAs": "Копировать/Вставить как",+ "copyAsText": "Копировать как текст",+ "copyAsSVG": "Копировать как SVG",+ "copyAsPNG": "Копировать как PNG",+ "copyAsJSX": "Копировать как JSX",+ "copyNodeId": "Копировать ID узла",+ "copyXPath": "Копировать XPath"},"commands": {"undo": "Отменить",diff --git a/packages/vue/src/locales/zh-CN.json b/packages/vue/src/locales/zh-CN.jsonindex 5c526a74b..b65b56a20 100644--- a/packages/vue/src/locales/zh-CN.json+++ b/packages/vue/src/locales/zh-CN.json@@ -30,7 +30,15 @@"toggleUI": "切换界面","bold": "加粗","italic": "斜体",- "underline": "下划线"+ "underline": "下划线",+ "pasteHere": "粘贴到此处",+ "copyPasteAs": "复制/粘贴为",+ "copyAsText": "复制为文本",+ "copyAsSVG": "复制为 SVG",+ "copyAsPNG": "复制为 PNG",+ "copyAsJSX": "复制为 JSX",+ "copyNodeId": "复制节点 ID",+ "copyXPath": "复制 XPath"},"commands": {"undo": "撤销",diff --git a/src/automation/server.ts b/src/automation/server.tsindex b47dc14a8..5d806495e 100644--- a/src/automation/server.ts+++ b/src/automation/server.ts@@ -13,6 +13,7 @@ import {computeAllLayouts,selectionToJSX,sceneNodeToJSX,+ nodeToXPath,randomHex} from '@open-pencil/core'@@ -125,6 +126,22 @@ export function connectAutomation(getStore: () => EditorStore, authToken: stringreturn { ok: true }}+ async function handleSelection(store: EditorStore): Promise<unknown> {+ const ids = [...store.state.selectedIds]+ const nodes = ids+ .map((id) => store.graph.getNode(id))+ .filter((n): n is NonNullable<typeof n> => n !== undefined)+ .map((n) => ({+ id: n.id,+ name: n.name,+ type: n.type,+ width: Math.round(n.width),+ height: Math.round(n.height),+ xpath: nodeToXPath(store.graph, n.id)+ }))+ return { ok: true, result: nodes }+ }+const commandHandlers: Partial<Record<string, (store: EditorStore, args: unknown) => Promise<unknown>>> = {@@ -132,6 +149,7 @@ export function connectAutomation(getStore: () => EditorStore, authToken: stringtool: handleTool,export: handleExport,export_jsx: handleExportJsx,+ selection: handleSelection,save_file: handleSaveFile}diff --git a/src/components/CanvasMenu.vue b/src/components/CanvasMenu.vueindex 2ec62fe6d..f8a3e4e43 100644--- a/src/components/CanvasMenu.vue+++ b/src/components/CanvasMenu.vue@@ -9,7 +9,8 @@ import {ContextMenuPortal} from 'reka-ui'import { useClipboard } from '@vueuse/core'-import { useEditorCommands, useMenuModel, useSelectionState } from '@open-pencil/vue'+import { nodeToXPath } from '@open-pencil/core'+import { useEditorCommands, useI18n, useMenuModel, useSelectionState } from '@open-pencil/vue'import { toast } from '@/utils/toast'import { useEditorStore } from '@/stores/editor'@@ -21,6 +22,7 @@ const { copy } = useClipboard()const { editor, selectedIds, hasSelection } = useSelectionState()const { getCommand } = useEditorCommands()const { canvasMenu } = useMenuModel()+const { menu: t } = useI18n()function ids() {return [...selectedIds.value]@@ -42,6 +44,24 @@ async function clipboardWrite(text: string | null, label: string) {toast.info(`Copied as ${label}`)}+function copyNodeId() {+ const nodeIds = ids()+ if (nodeIds.length === 0) return+ copy(nodeIds.join(', '))+ toast.info(`Copied node ID${nodeIds.length > 1 ? 's' : ''}`)+}++function copyXPath() {+ const nodeIds = ids()+ if (nodeIds.length === 0) return+ const xpaths = nodeIds+ .map((id) => nodeToXPath(store.graph, id))+ .filter((x): x is string => x !== null)+ if (xpaths.length === 0) return+ copy(xpaths.join('\n'))+ toast.info(`Copied XPath${xpaths.length > 1 ? 's' : ''}`)+}+async function copyAsPNG() {if (!navigator.clipboard?.write || typeof ClipboardItem === 'undefined') {toast.error('PNG clipboard export is not available in this browser')@@ -71,13 +91,16 @@ const cls = {<template><ContextMenuContent :class="cls.menu" :side-offset="2" align="start"><ContextMenuItem :class="cls.item" :disabled="!hasSelection" @select="execCommand('copy')">- <span>Copy</span><span class="text-[11px] text-muted">⌘C</span>+ <span>{{ t.copy }}</span+ ><span class="text-[11px] text-muted">⌘C</span></ContextMenuItem><ContextMenuItem :class="cls.item" :disabled="!hasSelection" @select="execCommand('cut')">- <span>Cut</span><span class="text-[11px] text-muted">⌘X</span>+ <span>{{ t.cut }}</span+ ><span class="text-[11px] text-muted">⌘X</span></ContextMenuItem><ContextMenuItem :class="cls.item" @select="execCommand('paste')">- <span>Paste here</span><span class="text-[11px] text-muted">⌘V</span>+ <span>{{ t.pasteHere }}</span+ ><span class="text-[11px] text-muted">⌘V</span></ContextMenuItem><ContextMenuItem:class="cls.item"@@ -147,28 +170,36 @@ const cls = {<ContextMenuSub><ContextMenuSubTrigger :class="cls.item">- <span>Copy/Paste as</span><span class="text-sm text-muted">›</span>+ <span>{{ t.copyPasteAs }}</span+ ><span class="text-sm text-muted">›</span></ContextMenuSubTrigger><ContextMenuPortal><ContextMenuSubContent :class="cls.menu"><ContextMenuItem:class="cls.item"@select="clipboardWrite(editor.copySelectionAsText(ids()), 'text')"- >Copy as text</ContextMenuItem+ >{{ t.copyAsText }}</ContextMenuItem><ContextMenuItem:class="cls.item"@select="clipboardWrite(editor.copySelectionAsSVG(ids()), 'SVG')"- >Copy as SVG</ContextMenuItem+ >{{ t.copyAsSVG }}</ContextMenuItem><ContextMenuItem :class="cls.item" @select="copyAsPNG">- <span>Copy as PNG</span><span class="text-[11px] text-muted">⇧⌘C</span>+ <span>{{ t.copyAsPNG }}</span+ ><span class="text-[11px] text-muted">⇧⌘C</span></ContextMenuItem><ContextMenuItem:class="cls.item"@select="clipboardWrite(editor.copySelectionAsJSX(ids()), 'JSX')"- >Copy as JSX</ContextMenuItem+ >{{ t.copyAsJSX }}</ContextMenuItem>+ <ContextMenuItem :class="cls.item" @select="copyNodeId">{{+ t.copyNodeId+ }}</ContextMenuItem>+ <ContextMenuItem :class="cls.item" @select="copyXPath">{{+ t.copyXPath+ }}</ContextMenuItem></ContextMenuSubContent></ContextMenuPortal></ContextMenuSub>diff --git a/tests/engine/xpath.test.ts b/tests/engine/xpath.test.tsindex 839c62a79..663a2ef52 100644--- a/tests/engine/xpath.test.ts+++ b/tests/engine/xpath.test.ts@@ -1,6 +1,6 @@import { describe, expect, test } from 'bun:test'-import { FigmaAPI, SceneGraph, matchByXPath, queryByXPath } from '@open-pencil/core'+import { FigmaAPI, SceneGraph, matchByXPath, nodeToXPath, queryByXPath } from '@open-pencil/core'function setup() {const graph = new SceneGraph()@@ -99,6 +99,87 @@ describe('queryByXPath', () => {})})+describe('nodeToXPath', () => {+ test('returns null for missing node', () => {+ const { graph } = setup()+ expect(nodeToXPath(graph, 'nonexistent')).toBeNull()+ })++ test('uses name predicate for unique name among siblings', () => {+ const { graph, figma } = setup()+ const rect = figma.createRectangle()+ rect.name = 'Header'+ const text = figma.createText()+ text.name = 'Title'++ const xpath = nodeToXPath(graph, rect.id)+ expect(xpath).toBe("//RECTANGLE[@name='Header']")+ })++ test('includes name even when sole child of that type', () => {+ const { graph, figma } = setup()+ const frame = figma.createFrame()+ frame.name = 'Card'+ const text = figma.createText()+ text.name = 'Label'+ frame.appendChild(text)++ const xpath = nodeToXPath(graph, text.id)+ expect(xpath).toBe("//FRAME[@name='Card']/TEXT[@name='Label']")+ })++ test('uses positional predicate for duplicate names', () => {+ const { graph, figma } = setup()+ const r1 = figma.createRectangle()+ r1.name = 'Item'+ const r2 = figma.createRectangle()+ r2.name = 'Item'++ const xpath1 = nodeToXPath(graph, r1.id)+ const xpath2 = nodeToXPath(graph, r2.id)+ expect(xpath1).toBe('//RECTANGLE[1]')+ expect(xpath2).toBe('//RECTANGLE[2]')+ })++ test('builds multi-level path', () => {+ const { graph, figma } = setup()+ const frame = figma.createFrame()+ frame.name = 'Container'+ const inner = figma.createFrame()+ inner.name = 'Row'+ frame.appendChild(inner)+ const text = figma.createText()+ text.name = 'Label'+ inner.appendChild(text)++ const xpath = nodeToXPath(graph, text.id)+ expect(xpath).toBe("//FRAME[@name='Container']/FRAME[@name='Row']/TEXT[@name='Label']")+ })++ test('round-trips with queryByXPath', async () => {+ const { graph, figma } = setup()+ const frame = figma.createFrame()+ frame.name = 'Sidebar'+ const btn = figma.createRectangle()+ btn.name = 'Button'+ frame.appendChild(btn)++ const xpath = nodeToXPath(graph, btn.id)!+ const results = await queryByXPath(graph, xpath)+ expect(results.length).toBe(1)+ expect(results[0].id).toBe(btn.id)+ })++ test('handles names with single quotes', () => {+ const { graph, figma } = setup()+ const rect = figma.createRectangle()+ rect.name = "it's a test"++ const xpath = nodeToXPath(graph, rect.id)+ expect(xpath).toBe('//RECTANGLE[@name="it\'s a test"]')+ })+})+describe('matchByXPath', () => {test('returns true for matching node', async () => {const { graph, figma } = setup()