Skip to content

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

feat(editor): copy and paste layer properties (Alt+Cmd+C, Alt+Cmd+V) (#1213)

LarryBambellecd5d8a54c8c5
diff --git a/changes/1213/added.md b/changes/1213/added.md
new file mode 100644
index 000000000..f2ff4c4c9
--- /dev/null
+++ b/changes/1213/added.md
@@ -0,0 +1 @@
+- Copy properties and Paste properties (Alt+Cmd+C, Alt+Cmd+V, also under Copy/Paste as in the canvas menu) carry the look of one layer to others through the system clipboard, to and from Figma.
diff --git a/packages/core/src/clipboard.ts b/packages/core/src/clipboard.ts
index 1ef592f5a..5a7389c4d 100644
--- a/packages/core/src/clipboard.ts
+++ b/packages/core/src/clipboard.ts
@@ -1,6 +1,14 @@
-import { embedClipboardImages, encodeFigmaClipboard } from '@open-pencil/fig/clipboard'
+import {
+ embedClipboardImages,
+ encodeFigmaClipboard,
+ type FigmaClipboardAssetType
+} from '@open-pencil/fig/clipboard'
import { randomInt } from '@open-pencil/scene-graph/random'
-export { parseFigmaClipboard, figmaNodesBounds } from '@open-pencil/fig/clipboard'
+export {
+ parseFigmaClipboard,
+ figmaNodesBounds,
+ type FigmaClipboardAssetType
+} from '@open-pencil/fig/clipboard'
import { placeSlotContent, type FigNodeChangeExportRuntime } from '@open-pencil/fig/node-change'
import { initCodec } from '@open-pencil/kiwi/fig/codec'
import type { GUID, NodeChange as KiwiNodeChange } from '@open-pencil/kiwi/fig/codec'
@@ -100,18 +108,20 @@ function clipboardGraph(graph: SceneGraph): SceneGraph {
export function buildFigmaClipboardHTML(
nodes: SceneNode[],
- graph: SceneGraph
+ graph: SceneGraph,
+ assetType: FigmaClipboardAssetType = 'UNKNOWN'
): Promise<string | null> {
const written = clipboardGraph(graph)
return withFigExportRuntime(written, undefined, (runtime) =>
- writeFigmaClipboardHTML(nodes, written, runtime)
+ writeFigmaClipboardHTML(nodes, written, runtime, assetType)
)
}
async function writeFigmaClipboardHTML(
nodes: SceneNode[],
graph: SceneGraph,
- runtime: FigNodeChangeExportRuntime
+ runtime: FigNodeChangeExportRuntime,
+ assetType: FigmaClipboardAssetType
): Promise<string | null> {
const fontDigestMap = await buildFontDigestMap(graph)
@@ -246,7 +256,7 @@ async function writeFigmaClipboardHTML(
}
}
embedClipboardImages(nodeChanges, blobs, graph.images)
- return encodeFigmaClipboard(nodeChanges, blobs, randomInt())
+ return encodeFigmaClipboard(nodeChanges, blobs, randomInt(), assetType)
}
export {
diff --git a/packages/core/src/editor/bridges/clipboard.ts b/packages/core/src/editor/bridges/clipboard.ts
index 7272af1ad..743051b7b 100644
--- a/packages/core/src/editor/bridges/clipboard.ts
+++ b/packages/core/src/editor/bridges/clipboard.ts
@@ -1,4 +1,5 @@
import type { createClipboardActions } from '#core/editor/clipboard'
+import type { CopyOptions } from '#core/editor/clipboard/copy'
import type { createSelectionActions } from '#core/editor/selection'
type ClipboardActions = ReturnType<typeof createClipboardActions>
@@ -8,7 +9,8 @@ export function createClipboardBridge(clipboard: ClipboardActions, selection: Se
return {
duplicateSelected: () => clipboard.duplicateSelected(selection.getSelectedNodes()),
duplicateNode: clipboard.duplicateNode,
- prepareCopy: () => clipboard.prepareCopy(selection.getSelectedNodes()),
+ prepareCopy: (options?: CopyOptions) =>
+ clipboard.prepareCopy(selection.getSelectedNodes(), options),
pasteSnapshot: clipboard.pasteSnapshot,
pasteFromHTML: clipboard.pasteFromHTML,
deleteSelected: clipboard.deleteSelected,
diff --git a/packages/core/src/editor/clipboard.ts b/packages/core/src/editor/clipboard.ts
index 9e4b5f2d5..0835182e0 100644
--- a/packages/core/src/editor/clipboard.ts
+++ b/packages/core/src/editor/clipboard.ts
@@ -10,7 +10,7 @@ import { computeAllLayouts } from '#core/layout'
import { createClipboardAssetActions } from './clipboard/assets'
import type { ClipboardSnapshot } from './clipboard/copy'
import { createClipboardCopyActions } from './clipboard/copy'
-import { importClipboardDependencies } from './clipboard/dependencies'
+import { importClipboardDependenciesWithUndo } from './clipboard/dependencies'
import { createClipboardExportActions } from './clipboard/export'
import { createClipboardFontActions } from './clipboard/fonts'
import { deleteIds, recreateSnapshots, restoreDeletedEntries } from './clipboard/history'
@@ -155,31 +155,11 @@ export function createClipboardActions(ctx: EditorContext) {
cursorPos?: Vector,
options: PasteOptions = {}
) {
+ // Copy properties writes layers for Paste properties only, as in Figma.
+ if (snapshot.properties) return
let created: string[] = []
ctx.undo.runBatch('Paste', () => {
- const dependencies = importClipboardDependencies(ctx, snapshot)
- if (dependencies.styleSnapshots.length > 0) {
- ctx.undo.push({
- label: 'Import clipboard styles',
- forward: () => {
- for (const style of dependencies.styleSnapshots) {
- ctx.graph.preserveSourceMetadataDuring(() =>
- ctx.graph.createNode(style.type, ctx.state.currentPageId, style)
- )
- }
- },
- inverse: () => {
- for (const style of dependencies.styleSnapshots) ctx.graph.deleteNode(style.id)
- }
- })
- }
- if (dependencies.applyVariables && dependencies.revertVariables) {
- ctx.undo.push({
- label: 'Import clipboard variables',
- forward: dependencies.applyVariables,
- inverse: dependencies.revertVariables
- })
- }
+ const dependencies = importClipboardDependenciesWithUndo(ctx, snapshot)
created = pasteOpenPencilNodes(
dependencies.nodes,
snapshot.placement,
@@ -211,6 +191,7 @@ export function createClipboardActions(ctx: EditorContext) {
}
const figma = await parseFigmaClipboard(html)
+ if (figma?.assetType === 'STYLE_PROPERTIES') return
if (figma) {
// One undo step for the paste and any slot it claims.
const pasted = ctx.undo.runBatch('Paste', () => {
diff --git a/packages/core/src/editor/clipboard/copy.ts b/packages/core/src/editor/clipboard/copy.ts
index bb48b0adb..07b74e5be 100644
--- a/packages/core/src/editor/clipboard/copy.ts
+++ b/packages/core/src/editor/clipboard/copy.ts
@@ -7,6 +7,11 @@ import { captureClipboardSnapshot, type ClipboardSnapshot } from './snapshot'
export type { ClipboardSnapshot } from './snapshot'
+export interface CopyOptions {
+ /** Copy properties: the same layers, marked so Paste skips them and Paste properties reads them. */
+ properties?: boolean
+}
+
export interface ClipboardPayload {
snapshot?: ClipboardSnapshot
html: string
@@ -36,11 +41,19 @@ function graphForSnapshot(ctx: EditorContext, snapshot: ClipboardSnapshot): Scen
}
export function createClipboardCopyActions(ctx: EditorContext) {
- async function prepareCopy(selectedNodes: SceneNode[]): Promise<ClipboardPayload> {
+ async function prepareCopy(
+ selectedNodes: SceneNode[],
+ options: CopyOptions = {}
+ ): Promise<ClipboardPayload> {
if (selectedNodes.length === 0) return { html: '', plainText: '' }
const snapshot = captureClipboardSnapshot(ctx.graph, selectedNodes)
+ if (options.properties) snapshot.properties = true
const plainText = snapshot.nodes.map((node) => node.name).join('\n')
- const html = await buildFigmaClipboardHTML(snapshot.nodes, graphForSnapshot(ctx, snapshot))
+ const html = await buildFigmaClipboardHTML(
+ snapshot.nodes,
+ graphForSnapshot(ctx, snapshot),
+ options.properties ? 'STYLE_PROPERTIES' : 'UNKNOWN'
+ )
if (!html) throw new Error('Could not encode selection for the clipboard')
return { html, plainText, snapshot }
}
diff --git a/packages/core/src/editor/clipboard/dependencies.ts b/packages/core/src/editor/clipboard/dependencies.ts
index 464dd16fe..9e05b7453 100644
--- a/packages/core/src/editor/clipboard/dependencies.ts
+++ b/packages/core/src/editor/clipboard/dependencies.ts
@@ -13,6 +13,37 @@ export interface ClipboardDependencyImport {
revertVariables?: () => void
}
+/** Imports a snapshot's styles and variables as undo steps of the running batch. */
+export function importClipboardDependenciesWithUndo(
+ ctx: EditorContext,
+ snapshot: ClipboardSnapshot
+): ClipboardDependencyImport {
+ const dependencies = importClipboardDependencies(ctx, snapshot)
+ if (dependencies.styleSnapshots.length > 0) {
+ ctx.undo.push({
+ label: 'Import clipboard styles',
+ forward: () => {
+ for (const style of dependencies.styleSnapshots) {
+ ctx.graph.preserveSourceMetadataDuring(() =>
+ ctx.graph.createNode(style.type, ctx.state.currentPageId, style)
+ )
+ }
+ },
+ inverse: () => {
+ for (const style of dependencies.styleSnapshots) ctx.graph.deleteNode(style.id)
+ }
+ })
+ }
+ if (dependencies.applyVariables && dependencies.revertVariables) {
+ ctx.undo.push({
+ label: 'Import clipboard variables',
+ forward: dependencies.applyVariables,
+ inverse: dependencies.revertVariables
+ })
+ }
+ return dependencies
+}
+
export function importClipboardDependencies(
ctx: EditorContext,
snapshot: ClipboardSnapshot
diff --git a/packages/core/src/editor/clipboard/paste/properties.ts b/packages/core/src/editor/clipboard/paste/properties.ts
new file mode 100644
index 000000000..d24b55b86
--- /dev/null
+++ b/packages/core/src/editor/clipboard/paste/properties.ts
@@ -0,0 +1,235 @@
+import { omitBy, pick } from 'es-toolkit/object'
+
+import { materializeFigFragment } from '@open-pencil/fig'
+import {
+ AUTO_LAYOUT_FIELDS,
+ CORNER_FIELDS,
+ PAINT_FIELDS,
+ STROKE_FIELDS,
+ STYLE_LINK_FIELDS,
+ TEXT_STYLE_FIELDS,
+ sharedStyleRefKey,
+ type SceneGraph,
+ type SceneNode,
+ type StyleRun
+} from '@open-pencil/scene-graph'
+
+import { parseFigmaClipboard, parseOpenPencilClipboard } from '#core/clipboard'
+import { importClipboardDependenciesWithUndo } from '#core/editor/clipboard/dependencies'
+import type { ClipboardSnapshot } from '#core/editor/clipboard/snapshot'
+import type { EditorContext } from '#core/editor/types'
+
+/**
+ * Figma's Paste properties: the look of the one copied layer, applied to others. Position, size,
+ * rotation, name, constraints, export settings, content, and structure never move.
+ */
+
+const APPEARANCE_FIELDS = [
+ ...PAINT_FIELDS,
+ ...STROKE_FIELDS,
+ sharedStyleRefKey('fill'),
+ sharedStyleRefKey('stroke'),
+ sharedStyleRefKey('effect')
+] as const
+
+/** Auto layout and layout grids, which move only from one frame to another. */
+const FRAME_FIELDS = [
+ ...AUTO_LAYOUT_FIELDS,
+ 'itemReverseZIndex',
+ 'layoutGrids',
+ sharedStyleRefKey('grid')
+] as const satisfies ReadonlyArray<keyof SceneNode>
+
+/** Text style fields, which move only from one text layer to another. */
+const TEXT_FIELDS = [...TEXT_STYLE_FIELDS, sharedStyleRefKey('text')] as const
+
+const NO_APPEARANCE: ReadonlySet<SceneNode['type']> = new Set(['CANVAS', 'SECTION', 'CONNECTOR'])
+const FRAME_TYPES: ReadonlySet<SceneNode['type']> = new Set(['FRAME', 'COMPONENT', 'INSTANCE'])
+
+type PastedField =
+ | (typeof APPEARANCE_FIELDS)[number]
+ | (typeof CORNER_FIELDS)[number]
+ | (typeof FRAME_FIELDS)[number]
+ | (typeof TEXT_FIELDS)[number]
+
+/** The run overrides that replace a text layer's own value of each pasted field. */
+const RUN_OVERRIDES: Readonly<Record<string, readonly string[]>> = {
+ fills: ['fills', 'fillStyleId'],
+ fillStyleId: ['fills', 'fillStyleId'],
+ textStyleId: ['textStyleId']
+}
+
+function fieldOf(key: string): string {
+ return key.split('/')[0] ?? key
+}
+
+/** Fields a text layer's character runs override, which Figma treats as mixed and leaves alone. */
+function mixedFields(source: SceneNode): Set<string> {
+ const mixed = new Set<string>()
+ for (const run of source.styleRuns) {
+ for (const key of Object.keys(run.style)) mixed.add(key)
+ for (const key of Object.keys(run.style.boundVariables ?? {})) mixed.add(key)
+ }
+ if (mixed.has('fills') || mixed.has('fillStyleId')) mixed.add('fills').add('fillStyleId')
+ return mixed
+}
+
+function pastedFields(source: SceneNode, target: SceneNode): PastedField[] {
+ const fields: PastedField[] = [...APPEARANCE_FIELDS]
+ // A text layer has no corners in Figma.
+ if (source.type !== 'TEXT' && target.type !== 'TEXT') fields.push(...CORNER_FIELDS)
+ if (FRAME_TYPES.has(source.type) && FRAME_TYPES.has(target.type)) fields.push(...FRAME_FIELDS)
+ if (source.type === 'TEXT' && target.type === 'TEXT') fields.push(...TEXT_FIELDS)
+ const mixed = source.type === 'TEXT' ? mixedFields(source) : new Set<string>()
+ return fields.filter((field) => !mixed.has(field))
+}
+
+/** The target's runs without the overrides the pasted fields replace, so they cover all of it. */
+function runsWithout(runs: StyleRun[], fields: ReadonlySet<string>): StyleRun[] {
+ const overrides = new Set([...fields].flatMap((field) => RUN_OVERRIDES[field] ?? [field]))
+ return runs.flatMap((run) => {
+ const style = omitBy(run.style, (_, key) => overrides.has(key))
+ if (style.boundVariables) {
+ const bound = omitBy(style.boundVariables, (_, key) => fields.has(key))
+ if (Object.keys(bound).length > 0) style.boundVariables = bound
+ else delete style.boundVariables
+ }
+ return Object.keys(style).length > 0 ? [{ ...run, style }] : []
+ })
+}
+
+/** Whether `source` is a layer whose look can be pasted. */
+export function hasPastableProperties(source: SceneNode): boolean {
+ return !NO_APPEARANCE.has(source.type)
+}
+
+/**
+ * What pasting the look of `source` onto `target` changes, or null when the target takes none (a
+ * page, a section, a connector). Locked layers take it, as in Figma.
+ */
+export function pastedPropertyChanges(
+ source: SceneNode,
+ target: SceneNode
+): Partial<SceneNode> | null {
+ if (!hasPastableProperties(source) || NO_APPEARANCE.has(target.type)) return null
+ const fields = pastedFields(source, target)
+ const changes: Partial<SceneNode> = structuredClone(pick(source, fields))
+ const replaced = new Set<string>(fields)
+ if (target.type === 'TEXT' && target.styleRuns.length > 0)
+ changes.styleRuns = runsWithout(target.styleRuns, replaced)
+ // Bindings of the fields being replaced go; the copied ones come in.
+ const kept = Object.entries(target.boundVariables).filter(([key]) => !replaced.has(fieldOf(key)))
+ const brought = Object.entries(source.boundVariables).filter(([key]) =>
+ replaced.has(fieldOf(key))
+ )
+ changes.boundVariables = Object.fromEntries([...kept, ...brought])
+ return changes
+}
+
+/**
+ * A copied layer from another document, keeping only the style and variable links `graph` can
+ * resolve; the copied values stay either way.
+ */
+export function withResolvableLinks(source: SceneNode, graph: SceneGraph): SceneNode {
+ const resolved = structuredClone(source)
+ for (const field of STYLE_LINK_FIELDS) {
+ const id = resolved[field]
+ if (id && !graph.getNode(id)) resolved[field] = null
+ }
+ resolved.boundVariables = Object.fromEntries(
+ Object.entries(resolved.boundVariables).filter(([, id]) => graph.variables.has(id))
+ )
+ return resolved
+}
+
+interface PastedSource {
+ node: SceneNode
+ images: ReadonlyMap<string, Uint8Array>
+}
+
+/** The one layer a clipboard payload from another app or tab holds, or null. */
+async function sourceFromHTML(html: string): Promise<PastedSource | null> {
+ const openPencil = parseOpenPencilClipboard(html)
+ if (openPencil) {
+ const { nodes, images } = openPencil
+ return nodes.length === 1 ? { node: nodes[0], images } : null
+ }
+ const figma = await parseFigmaClipboard(html)
+ if (!figma) return null
+ const fragment = materializeFigFragment(figma.nodes, figma.blobs, {
+ missingComponent: 'detach-empty'
+ })
+ const { rootIds } = fragment
+ const node = rootIds.length === 1 ? fragment.graph.getNode(rootIds[0]) : undefined
+ return node ? { node, images: fragment.graph.images } : null
+}
+
+export function createClipboardPropertiesActions(
+ ctx: EditorContext,
+ updateNodeWithUndo: (id: string, changes: Partial<SceneNode>, label?: string) => void,
+ loadFontsForNodes: (nodeIds: string[]) => Promise<unknown>
+) {
+ const LABEL = 'Paste properties'
+
+ function targets(): SceneNode[] {
+ return [...ctx.state.selectedIds].flatMap((id) => {
+ const node = ctx.graph.getNode(id)
+ return node && !NO_APPEARANCE.has(node.type) ? [node] : []
+ })
+ }
+
+ /** Applies the look of `source` to `targets` in the running batch; returns the changed ids. */
+ function apply(
+ source: SceneNode,
+ images: ReadonlyMap<string, Uint8Array>,
+ nodes: SceneNode[]
+ ): string[] {
+ for (const paint of [...source.fills, ...source.strokes]) {
+ const bytes = paint.imageHash ? images.get(paint.imageHash) : undefined
+ if (paint.imageHash && bytes && !ctx.graph.images.has(paint.imageHash))
+ ctx.graph.images.set(paint.imageHash, bytes)
+ }
+ return nodes.flatMap((target) => {
+ const changes = pastedPropertyChanges(source, target)
+ if (!changes) return []
+ updateNodeWithUndo(target.id, changes, LABEL)
+ return [target.id]
+ })
+ }
+
+ async function finish(changed: string[]): Promise<number> {
+ if (changed.length > 0) {
+ await loadFontsForNodes(changed)
+ ctx.requestRender()
+ }
+ return changed.length
+ }
+
+ /**
+ * Paste properties from a copy made in this app: the look of its one layer, with the styles and
+ * variables it uses, onto every selected layer in one undo step. Returns how many changed.
+ */
+ async function pastePropertiesFromSnapshot(snapshot: ClipboardSnapshot): Promise<number> {
+ const nodes = targets()
+ if (snapshot.nodes.length !== 1 || !hasPastableProperties(snapshot.nodes[0])) return 0
+ if (nodes.length === 0) return 0
+ const changed = ctx.undo.runBatch(LABEL, () => {
+ const [source] = importClipboardDependenciesWithUndo(ctx, snapshot).nodes
+ return apply(source, snapshot.images, nodes)
+ })
+ return finish(changed)
+ }
+
+ /** Paste properties from clipboard HTML, such as a Figma copy; links it cannot resolve drop. */
+ async function pastePropertiesFromHTML(html: string): Promise<number> {
+ const nodes = targets()
+ if (nodes.length === 0) return 0
+ const source = await sourceFromHTML(html)
+ if (!source || !hasPastableProperties(source.node)) return 0
+ const resolved = withResolvableLinks(source.node, ctx.graph)
+ const changed = ctx.undo.runBatch(LABEL, () => apply(resolved, source.images, nodes))
+ return finish(changed)
+ }
+
+ return { pastePropertiesFromSnapshot, pastePropertiesFromHTML }
+}
diff --git a/packages/core/src/editor/clipboard/snapshot.ts b/packages/core/src/editor/clipboard/snapshot.ts
index 68a8414e6..80e872f64 100644
--- a/packages/core/src/editor/clipboard/snapshot.ts
+++ b/packages/core/src/editor/clipboard/snapshot.ts
@@ -14,6 +14,8 @@ export interface ClipboardSnapshot {
/** Where the copied layers sat on the canvas when they were copied. */
placement: ClipboardPlacement
images: Map<string, Uint8Array>
+ /** Written by Copy properties: Paste skips it and Paste properties reads it, as in Figma. */
+ properties?: boolean
}
function referencedStyleIds(nodes: SceneNode[]): Set<string> {
diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.ts
index dd378d02d..b520fd78c 100644
--- a/packages/core/src/editor/create.ts
+++ b/packages/core/src/editor/create.ts
@@ -31,6 +31,7 @@ import { createLintFixBridge } from './bridges/lint'
import { createStructureBridge } from './bridges/structure'
import { createUndoBridge } from './bridges/undo'
import { createClipboardActions } from './clipboard'
+import { createClipboardPropertiesActions } from './clipboard/paste/properties'
import { createColorSpaceActions } from './color-space'
import { createComponentSyncScheduler } from './component-sync'
import { createComponentActions } from './components'
@@ -278,6 +279,11 @@ export function createEditor(options?: EditorOptions) {
const undoActions = createUndoActions(ctx)
const text = createTextActions(ctx)
const nodes = createNodeActions(ctx)
+ const clipboardProperties = createClipboardPropertiesActions(
+ ctx,
+ nodes.updateNodeWithUndo,
+ clipboard.loadFontsForNodes
+ )
const variables = createVariableActions(ctx)
const designTokens = createDesignTokenActions(ctx, variables, nodes)
const vectorize = createVectorizeActions(ctx)
@@ -479,6 +485,9 @@ export function createEditor(options?: EditorOptions) {
// Clipboard — bridge functions that need selectedNodes
...clipboardBridge,
+ // Paste properties: the look of a copied layer, onto the selection
+ ...clipboardProperties,
+
// Components — bridge functions
...componentBridge,
diff --git a/packages/core/src/editor/index.ts b/packages/core/src/editor/index.ts
index b1d53485a..462f10b27 100644
--- a/packages/core/src/editor/index.ts
+++ b/packages/core/src/editor/index.ts
@@ -26,7 +26,8 @@ export { executeAtomicTool } from './history/atomic-tool'
export { isEmptyDocumentChange, type DocumentChange } from './history/document-change'
export type { PageSnapshot } from './history/snapshot/page'
export { graphFromDocumentChange, graphFromPageSnapshot } from './history/snapshot/graph'
-export type { ClipboardPayload, ClipboardSnapshot } from './clipboard/copy'
+export type { ClipboardPayload, ClipboardSnapshot, CopyOptions } from './clipboard/copy'
+export { pastedPropertyChanges } from './clipboard/paste/properties'
export { resolvePasteTarget } from './clipboard/paste/target'
export { playIslandRoots } from './play/islands'
export { resolvePlayState, type InstanceState } from './play/states'
diff --git a/packages/core/tests/editor/clipboard/paste/properties.test.ts b/packages/core/tests/editor/clipboard/paste/properties.test.ts
new file mode 100644
index 000000000..fe486bd66
--- /dev/null
+++ b/packages/core/tests/editor/clipboard/paste/properties.test.ts
@@ -0,0 +1,239 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createEditor, type Editor } from '@open-pencil/core/editor'
+import { colorToFill } from '@open-pencil/scene-graph/color'
+
+import { withResolvableLinks } from '#core/editor/clipboard/paste/properties'
+import { getNodeOrThrow } from '#core-tests/helpers/assert'
+
+const LINK = { type: 'URL', value: 'https://example.com/' } as const
+const RED = colorToFill('#ff0000')
+const GREEN = colorToFill('#00ff00')
+
+function setup() {
+ const editor = createEditor()
+ const pageId = editor.graph.getPages()[0].id
+ const source = editor.graph.createNode('RECTANGLE', pageId, {
+ name: 'Source',
+ width: 100,
+ height: 40,
+ rotation: 15,
+ fills: [RED],
+ strokes: [{ ...colorToFill('#0000ff'), weight: 3, align: 'INSIDE' }],
+ borderTopWeight: 5,
+ independentStrokeWeights: true,
+ cornerRadius: 8,
+ opacity: 0.5
+ })
+ const target = editor.graph.createNode('RECTANGLE', pageId, {
+ name: 'Target',
+ x: 200,
+ width: 60,
+ height: 60,
+ fills: [GREEN]
+ })
+ return { editor, pageId, source, target }
+}
+
+async function copyProperties(editor: Editor, ids: string[]) {
+ editor.select(ids)
+ const payload = await editor.prepareCopy({ properties: true })
+ if (!payload.snapshot) throw new Error('Copy properties wrote no snapshot')
+ return { html: payload.html, snapshot: payload.snapshot }
+}
+
+const fillOf = (editor: Editor, id: string) => getNodeOrThrow(editor.graph, id).fills[0]?.color
+
+describe('paste properties', () => {
+ test('moves the look of the copied layer without its geometry, rotation, or name', async () => {
+ const { editor, source, target } = setup()
+ const { snapshot } = await copyProperties(editor, [source.id])
+ editor.select([target.id])
+ expect(await editor.pastePropertiesFromSnapshot(snapshot)).toBe(1)
+
+ const pasted = getNodeOrThrow(editor.graph, target.id)
+ expect(pasted.fills[0]?.color).toEqual(RED.color)
+ expect(pasted.strokes).toHaveLength(1)
+ expect([pasted.borderTopWeight, pasted.independentStrokeWeights]).toEqual([5, true])
+ expect([pasted.cornerRadius, pasted.opacity]).toEqual([8, 0.5])
+ expect([pasted.name, pasted.width, pasted.height, pasted.x, pasted.rotation]).toEqual([
+ 'Target',
+ 60,
+ 60,
+ 200,
+ 0
+ ])
+ })
+
+ test('reads a copy of the layers from the Figma clipboard format too', async () => {
+ const { editor, source, target } = setup()
+ const { html } = await copyProperties(editor, [source.id])
+ editor.select([target.id])
+ expect(await editor.pastePropertiesFromHTML(html)).toBe(1)
+ expect(fillOf(editor, target.id)).toEqual(RED.color)
+ })
+
+ test('Paste skips a Copy properties payload, as Figma does', async () => {
+ const { editor, pageId, source } = setup()
+ const { html, snapshot } = await copyProperties(editor, [source.id])
+ const count = () => editor.graph.getChildren(pageId).length
+ const before = count()
+ await editor.pasteSnapshot(snapshot)
+ await editor.pasteFromHTML(html)
+ expect(count()).toBe(before)
+ })
+
+ test('pastes onto every selected layer, locked ones too, in one undo step', async () => {
+ const { editor, pageId, source, target } = setup()
+ const locked = editor.graph.createNode('ELLIPSE', pageId, { fills: [GREEN], locked: true })
+ const { snapshot } = await copyProperties(editor, [source.id])
+ editor.select([target.id, locked.id])
+ expect(await editor.pastePropertiesFromSnapshot(snapshot)).toBe(2)
+ expect(fillOf(editor, locked.id)).toEqual(RED.color)
+
+ editor.undoAction()
+ expect([fillOf(editor, target.id), fillOf(editor, locked.id)]).toEqual([
+ GREEN.color,
+ GREEN.color
+ ])
+ editor.redoAction()
+ expect(fillOf(editor, locked.id)).toEqual(RED.color)
+ })
+
+ test('a copy of several layers pastes nothing and leaves no undo step', async () => {
+ const { editor, pageId, source, target } = setup()
+ const other = editor.graph.createNode('ELLIPSE', pageId, { fills: [RED] })
+ const { snapshot } = await copyProperties(editor, [source.id, other.id])
+ editor.select([target.id])
+ expect(await editor.pastePropertiesFromSnapshot(snapshot)).toBe(0)
+ expect(fillOf(editor, target.id)).toEqual(GREEN.color)
+ expect(editor.undo.canUndo).toBe(false)
+ })
+
+ test('auto layout and layout grids move only from one frame to another', async () => {
+ const { editor, pageId, target } = setup()
+ const frame = editor.graph.createNode('FRAME', pageId, {
+ layoutMode: 'HORIZONTAL',
+ itemSpacing: 14,
+ paddingLeft: 9,
+ fills: [RED]
+ })
+ const other = editor.graph.createNode('FRAME', pageId, { width: 120, height: 90 })
+ const { snapshot } = await copyProperties(editor, [frame.id])
+ editor.select([other.id, target.id])
+ await editor.pastePropertiesFromSnapshot(snapshot)
+ const pastedFrame = getNodeOrThrow(editor.graph, other.id)
+ expect([pastedFrame.layoutMode, pastedFrame.itemSpacing, pastedFrame.paddingLeft]).toEqual([
+ 'HORIZONTAL',
+ 14,
+ 9
+ ])
+ expect(getNodeOrThrow(editor.graph, target.id).layoutMode).toBe('NONE')
+ expect(fillOf(editor, target.id)).toEqual(RED.color)
+ })
+
+ test('variable bindings of the pasted fields replace the target’s and keep the rest', async () => {
+ const { editor, source, target } = setup()
+ const tokens = editor.graph.createCollection('Tokens')
+ const color = (name: string, hex: string) =>
+ editor.graph.createVariable(name, 'COLOR', tokens.id, colorToFill(hex).color).id
+ const size = (name: string) => editor.graph.createVariable(name, 'FLOAT', tokens.id, 40).id
+ const [brand, old, width, height] = [
+ color('Brand', '#ff0000'),
+ color('Old', '#00ff00'),
+ size('Width'),
+ size('Height')
+ ]
+ editor.graph.updateNode(source.id, { boundVariables: { 'fills/0/color': brand, width } })
+ editor.graph.updateNode(target.id, { boundVariables: { 'fills/0/color': old, height } })
+ const { snapshot } = await copyProperties(editor, [source.id])
+ editor.select([target.id])
+ await editor.pastePropertiesFromSnapshot(snapshot)
+ expect(getNodeOrThrow(editor.graph, target.id).boundVariables).toEqual({
+ 'fills/0/color': brand,
+ height
+ })
+ })
+
+ test('a layer from another document keeps its values but drops links it cannot resolve', () => {
+ const { editor, source } = setup()
+ const foreign = {
+ ...getNodeOrThrow(editor.graph, source.id),
+ fillStyleId: 'missing-style',
+ boundVariables: { opacity: 'missing-variable' }
+ }
+ const resolved = withResolvableLinks(foreign, editor.graph)
+ expect([resolved.fillStyleId, resolved.boundVariables]).toEqual([null, {}])
+ expect(resolved.fills[0]?.color).toEqual(RED.color)
+ })
+})
+
+describe('paste properties on text', () => {
+ function textSetup() {
+ const editor = createEditor()
+ const pageId = editor.graph.getPages()[0].id
+ const styled = editor.graph.createNode('TEXT', pageId, {
+ text: 'Styled',
+ fontFamily: 'Inter',
+ fontSize: 32,
+ fontWeight: 700,
+ paragraphSpacing: 10,
+ fills: [RED]
+ })
+ const plain = editor.graph.createNode('TEXT', pageId, {
+ text: 'Plain text',
+ fontSize: 12,
+ styleRuns: [
+ { start: 0, length: 5, style: { fontSize: 40, hyperlink: LINK } },
+ { start: 5, length: 5, style: { fills: [GREEN], fillStyleId: 'style-a' } }
+ ]
+ })
+ const shape = editor.graph.createNode('RECTANGLE', pageId, { cornerRadius: 4 })
+ return { editor, pageId, styled, plain, shape }
+ }
+
+ test('a text style covers every character run and keeps their links', async () => {
+ const { editor, styled, plain } = textSetup()
+ const { snapshot } = await copyProperties(editor, [styled.id])
+ editor.select([plain.id])
+ await editor.pastePropertiesFromSnapshot(snapshot)
+
+ const pasted = getNodeOrThrow(editor.graph, plain.id)
+ expect([pasted.fontSize, pasted.fontWeight, pasted.paragraphSpacing]).toEqual([32, 700, 10])
+ expect(pasted.fills[0]?.color).toEqual(RED.color)
+ expect(pasted.styleRuns).toEqual([{ start: 0, length: 5, style: { hyperlink: LINK } }])
+ })
+
+ test('mixed character styles of the copied text are not pasted', async () => {
+ const { editor, pageId, plain } = textSetup()
+ const target = editor.graph.createNode('TEXT', pageId, {
+ text: 'Target',
+ fontSize: 14,
+ fills: [colorToFill('#0000ff')]
+ })
+ const { snapshot } = await copyProperties(editor, [plain.id])
+ editor.select([target.id])
+ await editor.pastePropertiesFromSnapshot(snapshot)
+ const pasted = getNodeOrThrow(editor.graph, target.id)
+ expect(pasted.fontSize).toBe(14)
+ expect(pasted.fills[0]?.color).toEqual(colorToFill('#0000ff').color)
+ })
+
+ test('a shape gives text its paints but no corner radius, and text keeps a shape’s radius', async () => {
+ const { editor, styled, plain, shape } = textSetup()
+ editor.graph.updateNode(shape.id, { fills: [colorToFill('#0000ff')] })
+ const fromShape = await copyProperties(editor, [shape.id])
+ editor.select([plain.id])
+ await editor.pastePropertiesFromSnapshot(fromShape.snapshot)
+ const text = getNodeOrThrow(editor.graph, plain.id)
+ expect(text.fills[0]?.color).toEqual(colorToFill('#0000ff').color)
+ expect([text.fontSize, text.cornerRadius]).toEqual([12, 0])
+
+ const fromText = await copyProperties(editor, [styled.id])
+ editor.select([shape.id])
+ await editor.pastePropertiesFromSnapshot(fromText.snapshot)
+ const pastedShape = getNodeOrThrow(editor.graph, shape.id)
+ expect(pastedShape.fills[0]?.color).toEqual(RED.color)
+ expect([pastedShape.cornerRadius, pastedShape.fontSize]).toEqual([4, shape.fontSize])
+ })
+})
diff --git a/packages/docs/reference/figma-compatibility.md b/packages/docs/reference/figma-compatibility.md
index 80ada88cf..4bfa4bc12 100644
--- a/packages/docs/reference/figma-compatibility.md
+++ b/packages/docs/reference/figma-compatibility.md
@@ -57,7 +57,7 @@ Feature-by-feature comparison of Figma Design capabilities with Open Pencil's cu
| Measure distances between layers | 🔲 | Alt-hover to show distances |
| Edit objects in bulk | ✅ | Multi-selection properties panel: edit position, size, appearance, fill, stroke, effects across multiple nodes; shared values display normally, differing values show "Mixed" |
| Identify matching objects | 🔲 | Find similar layers |
-| Copy/paste properties | 🔲 | Copy fill/stroke/effects between layers |
+| Copy/paste properties | ✅ | <kbd>⌥</kbd><kbd>⌘</kbd><kbd>C</kbd> / <kbd>⌥</kbd><kbd>⌘</kbd><kbd>V</kbd> through the system clipboard, to and from Figma: fills, strokes, effects, corners, styles, variables, auto layout between frames, text style between text layers |
| Parent-child relationships | ✅ | Full hierarchy with parentIndex, reparenting via drag |
## Vector Tools
diff --git a/packages/docs/reference/keyboard-shortcuts.md b/packages/docs/reference/keyboard-shortcuts.md
index 2cd83aceb..d53546241 100644
--- a/packages/docs/reference/keyboard-shortcuts.md
+++ b/packages/docs/reference/keyboard-shortcuts.md
@@ -60,8 +60,8 @@ Full Figma-compatible shortcut map. ✅ = implemented.
| <kbd>⌘</kbd><kbd>A</kbd> | Select All | ✅ |
| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>A</kbd> | Select Inverse | ✅ |
| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>C</kbd> | Copy as PNG | ✅ |
-| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>C</kbd> | Copy Properties | 🔲 |
-| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>V</kbd> | Paste Properties | 🔲 |
+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>C</kbd> | Copy Properties | ✅ |
+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>V</kbd> | Paste Properties | ✅ |
## View
diff --git a/packages/docs/user-guide/context-menu.md b/packages/docs/user-guide/context-menu.md
index c7db0efe1..b7c77b40a 100644
--- a/packages/docs/user-guide/context-menu.md
+++ b/packages/docs/user-guide/context-menu.md
@@ -34,6 +34,19 @@ The **Copy/Paste as** submenu offers additional clipboard formats for the select
Clipboard actions are disabled when nothing is selected (except Paste, which is available when the clipboard has content).
+## Copy and Paste Properties
+
+| Action | Shortcut (Mac) | Shortcut (Win/Linux) |
+|--------|----------------|----------------------|
+| Copy properties | <kbd>⌥</kbd><kbd>⌘</kbd><kbd>C</kbd> | <kbd>Alt</kbd> + <kbd>Ctrl</kbd> + <kbd>C</kbd> |
+| Paste properties | <kbd>⌥</kbd><kbd>⌘</kbd><kbd>V</kbd> | <kbd>Alt</kbd> + <kbd>Ctrl</kbd> + <kbd>V</kbd> |
+
+Both are in the **Copy/Paste as** submenu.
+
+- **Copy properties** puts the selected layer on the system clipboard the way Figma does, marked so a plain Paste ignores it.
+- **Paste properties** applies the look of the one layer on the clipboard to every selected layer, locked ones included, in one undo step. It reads a copy made with Copy properties or ordinary Copy, here or in Figma.
+- The look is fills, strokes, effects, opacity, blend mode, corner radius, and linked styles and variables. Between frames it includes auto layout and layout grids, and between text layers the text style. Position, size, rotation, name, and content never change, and properties a text layer mixes across its characters are left alone.
+
## Z-Order
| Action | Shortcut |
diff --git a/packages/fig/src/clipboard/encode.ts b/packages/fig/src/clipboard/encode.ts
index a53c6a6e0..8e0950199 100644
--- a/packages/fig/src/clipboard/encode.ts
+++ b/packages/fig/src/clipboard/encode.ts
@@ -6,11 +6,15 @@ import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import { buildFigKiwi } from '../node-change'
+/** What a clipboard payload is for: layers to paste, or Copy properties' look for Paste properties. */
+export type FigmaClipboardAssetType = 'UNKNOWN' | 'STYLE_PROPERTIES'
+
/** Encode prepared node changes; runtime shaping and font loading belong to the caller. */
export function encodeFigmaClipboard(
nodeChanges: NodeChange[],
blobs: Uint8Array[],
- pasteID: number
+ pasteID: number,
+ assetType: FigmaClipboardAssetType = 'UNKNOWN'
): string {
const message = {
type: 'NODE_CHANGES',
@@ -18,6 +22,7 @@ export function encodeFigmaClipboard(
ackID: 0,
pasteID,
pasteFileKey: 'openpencil',
+ pasteAssetType: assetType,
nodeChanges,
blobs: blobs.map((bytes) => ({ bytes }))
}
diff --git a/packages/fig/src/clipboard/import.ts b/packages/fig/src/clipboard/import.ts
index 4c45918e5..90ca71c22 100644
--- a/packages/fig/src/clipboard/import.ts
+++ b/packages/fig/src/clipboard/import.ts
@@ -16,9 +16,15 @@ const FigmaClipboardMetaJSON = v.pipe(
type FigmaClipboardMeta = v.InferOutput<typeof FigmaClipboardMetaJSON>
-export async function parseFigmaClipboard(
- html: string
-): Promise<{ nodes: KiwiNodeChange[]; meta: FigmaClipboardMeta; blobs: Uint8Array[] } | null> {
+export interface ParsedFigmaClipboard {
+ nodes: KiwiNodeChange[]
+ meta: FigmaClipboardMeta
+ blobs: Uint8Array[]
+ /** `STYLE_PROPERTIES` for Copy properties, which Paste skips and Paste properties reads. */
+ assetType: string
+}
+
+export async function parseFigmaClipboard(html: string): Promise<ParsedFigmaClipboard | null> {
const metaMatch = html.match(/\(figmeta\)(.*?)\(\/figmeta\)/)
const bufMatch = html.match(/\(figma\)(.*?)\(\/figma\)/s)
if (!metaMatch || !bufMatch) return null
@@ -42,13 +48,14 @@ export async function parseFigmaClipboard(
const msg = compiled.decodeMessage(dataRaw) as {
nodeChanges?: KiwiNodeChange[]
blobs?: Array<{ bytes: Uint8Array | Record<string, number> }>
+ pasteAssetType?: string
}
const blobs: Uint8Array[] = (msg.blobs ?? []).map((b) =>
b.bytes instanceof Uint8Array ? b.bytes : new Uint8Array(Object.values(b.bytes))
)
- return { nodes: msg.nodeChanges ?? [], meta, blobs }
+ return { nodes: msg.nodeChanges ?? [], meta, blobs, assetType: msg.pasteAssetType ?? 'UNKNOWN' }
} catch {
return null
}
diff --git a/packages/fig/src/clipboard/index.ts b/packages/fig/src/clipboard/index.ts
index 90d145a33..ed7cfee93 100644
--- a/packages/fig/src/clipboard/index.ts
+++ b/packages/fig/src/clipboard/index.ts
@@ -1,3 +1,3 @@
-export { parseFigmaClipboard, figmaNodesBounds } from './import'
-export { encodeFigmaClipboard } from './encode'
+export { parseFigmaClipboard, figmaNodesBounds, type ParsedFigmaClipboard } from './import'
+export { encodeFigmaClipboard, type FigmaClipboardAssetType } from './encode'
export { embedClipboardImages } from './images'
diff --git a/packages/kiwi/src/fig/schema/fig.kiwi b/packages/kiwi/src/fig/schema/fig.kiwi
index dab55c8bc..356742aa0 100644
--- a/packages/kiwi/src/fig/schema/fig.kiwi
+++ b/packages/kiwi/src/fig/schema/fig.kiwi
@@ -4259,6 +4259,10 @@ message ClientBroadcast {
enum PasteAssetType {
UNKNOWN = 0;
VARIABLE = 1;
+ STYLE_PROPERTIES = 2;
+ STYLE_PROPERTIES_FILL = 3;
+ STYLE_PROPERTIES_STROKE = 4;
+ STYLE_PROPERTIES_EFFECT = 5;
}
message Message {
diff --git a/packages/scene-graph/AGENTS.md b/packages/scene-graph/AGENTS.md
index a45f07a09..7683730a7 100644
--- a/packages/scene-graph/AGENTS.md
+++ b/packages/scene-graph/AGENTS.md
@@ -18,6 +18,7 @@ Framework-neutral document model. Owns node types, primitives, geometry, matrice
- A node's per-axis sizing (Figma's `layoutSizingHorizontal`/`Vertical`) is read and written through `packages/scene-graph/src/layout/sizing.ts`. Fill is stored on the child as Figma stores it, `layoutGrow` along the parent's primary axis (a grid's is horizontal) and `layoutAlignSelf: 'STRETCH'` across it; `primaryAxisSizing`/`counterAxisSizing` only fix or hug. Layout, the Figma API, the properties panel, and exporters call it instead of mapping axes themselves (`tests/engine/figma/api/layout/sizing.test.ts`).
- Formats read auto layout keywords (stack direction, `justify-content`, `align-items`, `align-self`, padding shorthand) through `packages/scene-graph/src/layout/keywords.ts`, and an importer builds fill and hug for a node not yet in the graph with `fillSizingFields` and `autoLayoutSizingFields`. Design JSX and `.pen` pass their own spellings straight to it, and DOM/CSS parses CSS values first with `parseCSSJustifyContent` and its siblings in `@open-pencil/scene-graph/css` (`packages/scene-graph/tests/layout/keywords.test.ts`, `packages/scene-graph/tests/css/layout.test.ts`).
- CSS values that become scene-graph types, such as grid track lists, are parsed in `@open-pencil/scene-graph/css` on `postcss-value-parser`; design-jsx and dom-css call it instead of splitting or matching CSS by hand (`packages/scene-graph/tests/css`).
+- Groups of `SceneNode` fields (transform, size, size limits, paints, strokes, corners, auto layout, text style) are named once in `packages/scene-graph/src/fields/`, and style links come from `STYLE_LINK_FIELDS`. Build a field list, such as instance sync, layout invalidation or Paste properties, from those groups instead of spelling the fields again (`packages/scene-graph/src/instances/fields.ts`).
- Every plugin-data key OpenPencil writes is a field of `OPEN_PENCIL_PLUGIN_DATA` in `packages/scene-graph/src/plugin-data/fields.ts`, with the Valibot schema that reads it and its role: `content` travels with library assets and counts towards their hash (`contentPluginData`), `format` repeats a node field for files, `bookkeeping` stays behind. Read and replace entries with `readPluginData` and `withPluginData` instead of matching `pluginId` and `key` by hand. The fields test checks that keys stay unique.
- A layer's `status` stays stored wherever the layer moves, as Figma keeps it; whether it shows, and whether one may be set, come from `effectiveStatus` and `statusPlacement` in `packages/scene-graph/src/statuses/node.ts`, which the Figma API, `.fig` and the UI share. Copies start without one (`packages/core/tests/figma-api/dev-status.test.ts`).
- Vector network types live here; `vectorNetworkBlob` codecs live in `packages/core/src/vector/`.
diff --git a/packages/scene-graph/src/fields/appearance.ts b/packages/scene-graph/src/fields/appearance.ts
new file mode 100644
index 000000000..fcb68dfa7
--- /dev/null
+++ b/packages/scene-graph/src/fields/appearance.ts
@@ -0,0 +1,35 @@
+import type { SceneNode } from '../types'
+
+/** What a layer is painted with, and how it blends. */
+export const PAINT_FIELDS = [
+ 'fills',
+ 'strokes',
+ 'effects',
+ 'opacity',
+ 'blendMode'
+] as const satisfies readonly (keyof SceneNode)[]
+
+/** How strokes are drawn, beside their paints. */
+export const STROKE_FIELDS = [
+ 'strokeWeight',
+ 'strokeAlign',
+ 'strokeCap',
+ 'strokeJoin',
+ 'strokeMiterLimit',
+ 'dashPattern',
+ 'independentStrokeWeights',
+ 'borderTopWeight',
+ 'borderRightWeight',
+ 'borderBottomWeight',
+ 'borderLeftWeight'
+] as const satisfies readonly (keyof SceneNode)[]
+
+export const CORNER_FIELDS = [
+ 'cornerRadius',
+ 'topLeftRadius',
+ 'topRightRadius',
+ 'bottomRightRadius',
+ 'bottomLeftRadius',
+ 'independentCorners',
+ 'cornerSmoothing'
+] as const satisfies readonly (keyof SceneNode)[]
diff --git a/packages/scene-graph/src/fields/layout.ts b/packages/scene-graph/src/fields/layout.ts
new file mode 100644
index 000000000..ef85cea80
--- /dev/null
+++ b/packages/scene-graph/src/fields/layout.ts
@@ -0,0 +1,33 @@
+import type { SceneNode } from '../types'
+
+/** How a frame lays out its children: auto layout and its grid tracks. */
+export const AUTO_LAYOUT_FIELDS = [
+ 'layoutMode',
+ 'layoutDirection',
+ 'layoutWrap',
+ 'primaryAxisAlign',
+ 'counterAxisAlign',
+ 'counterAxisAlignContent',
+ 'primaryAxisSizing',
+ 'counterAxisSizing',
+ 'itemSpacing',
+ 'counterAxisSpacing',
+ 'paddingTop',
+ 'paddingRight',
+ 'paddingBottom',
+ 'paddingLeft',
+ 'strokesIncludedInLayout',
+ 'gridTemplateColumns',
+ 'gridTemplateRows',
+ 'gridColumnGap',
+ 'gridRowGap'
+] as const satisfies readonly (keyof SceneNode)[]
+
+/** Size limits a layer keeps however it is resized. */
+export const SIZE_CONSTRAINT_FIELDS = [
+ 'minWidth',
+ 'maxWidth',
+ 'minHeight',
+ 'maxHeight',
+ 'targetAspectRatio'
+] as const satisfies readonly (keyof SceneNode)[]
diff --git a/packages/scene-graph/src/fields/text.ts b/packages/scene-graph/src/fields/text.ts
index 85250050c..a2d7b6868 100644
--- a/packages/scene-graph/src/fields/text.ts
+++ b/packages/scene-graph/src/fields/text.ts
@@ -33,3 +33,30 @@ export const TEXT_LAYOUT_FIELDS = [
'textAutoResize',
'maxLines'
] as const satisfies readonly (keyof SceneNode)[]
+
+export const TEXT_DECORATION_FIELDS = [
+ 'textDecoration',
+ 'textDecorationStyle',
+ 'textDecorationThickness',
+ 'textUnderlineOffset',
+ 'textDecorationFills',
+ 'textDecorationSkipInk'
+] as const satisfies readonly (keyof SceneNode)[]
+
+/** How text is styled, apart from its content and how its box sizes. */
+export const TEXT_STYLE_FIELDS = [
+ 'fontFamily',
+ 'fontSize',
+ 'fontWeight',
+ 'italic',
+ 'lineHeight',
+ 'letterSpacing',
+ 'paragraphSpacing',
+ 'paragraphIndent',
+ 'textAlignHorizontal',
+ 'textAlignVertical',
+ 'textCase',
+ ...TEXT_DECORATION_FIELDS,
+ 'fontFeatures',
+ 'fontVariations'
+] as const satisfies readonly (keyof SceneNode)[]
diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.ts
index fa9b9a60a..b3c358d23 100644
--- a/packages/scene-graph/src/index.ts
+++ b/packages/scene-graph/src/index.ts
@@ -9,7 +9,16 @@ export * from './plugin-data/fields'
export { rescaleNodeTree, scaleNodeChanges } from './scaling'
import { TRANSFORM_FIELDS, SIZE_FIELDS } from './fields/geometry'
export { TRANSFORM_FIELDS, SIZE_FIELDS } from './fields/geometry'
-export { TEXT_METRIC_FIELDS, TEXT_SHAPING_FIELDS, TEXT_LAYOUT_FIELDS } from './fields/text'
+import { AUTO_LAYOUT_FIELDS, SIZE_CONSTRAINT_FIELDS } from './fields/layout'
+export { AUTO_LAYOUT_FIELDS, SIZE_CONSTRAINT_FIELDS } from './fields/layout'
+export { CORNER_FIELDS, PAINT_FIELDS, STROKE_FIELDS } from './fields/appearance'
+export {
+ TEXT_METRIC_FIELDS,
+ TEXT_SHAPING_FIELDS,
+ TEXT_LAYOUT_FIELDS,
+ TEXT_DECORATION_FIELDS,
+ TEXT_STYLE_FIELDS
+} from './fields/text'
export * from './transfer'
export * from './instance-overrides'
export * from './asset-keys'
@@ -561,36 +570,14 @@ export class SceneGraph {
static LAYOUT_AFFECTING_KEYS: ReadonlySet<string> = new Set([
...TRANSFORM_FIELDS,
...SIZE_FIELDS,
- 'layoutMode',
- 'layoutDirection',
- 'itemSpacing',
- 'counterAxisSpacing',
- 'paddingLeft',
- 'paddingRight',
- 'paddingTop',
- 'paddingBottom',
- 'primaryAxisAlign',
- 'counterAxisAlign',
- 'counterAxisAlignContent',
- 'layoutWrap',
- 'primaryAxisSizing',
- 'counterAxisSizing',
+ ...AUTO_LAYOUT_FIELDS,
'layoutPositioning',
'layoutGrow',
'layoutAlignSelf',
- 'strokesIncludedInLayout',
'horizontalConstraint',
'verticalConstraint',
- 'gridTemplateColumns',
- 'gridTemplateRows',
- 'gridColumnGap',
- 'gridRowGap',
'gridPosition',
- 'minWidth',
- 'maxWidth',
- 'minHeight',
- 'maxHeight',
- 'targetAspectRatio'
+ ...SIZE_CONSTRAINT_FIELDS
])
runPreviewUpdates(fn: () => void, beforeUpdate?: NodePreviewObserver): void {
diff --git a/packages/scene-graph/src/instances/fields.ts b/packages/scene-graph/src/instances/fields.ts
index 484947188..4f99d678a 100644
--- a/packages/scene-graph/src/instances/fields.ts
+++ b/packages/scene-graph/src/instances/fields.ts
@@ -1,34 +1,23 @@
+import { difference } from 'es-toolkit/array'
+
import type { SceneNode } from '../'
+import { CORNER_FIELDS, PAINT_FIELDS, STROKE_FIELDS } from '../fields/appearance'
+import { SIZE_FIELDS, TRANSFORM_FIELDS } from '../fields/geometry'
+import { AUTO_LAYOUT_FIELDS, SIZE_CONSTRAINT_FIELDS } from '../fields/layout'
+import { TEXT_STYLE_FIELDS } from '../fields/text'
+import { STYLE_LINK_FIELDS } from '../shared-styles'
export const INSTANCE_SYNC_TEXT_PROPS = [
'name',
'text',
- 'fontSize',
- 'fontWeight',
- 'fontFamily',
- 'italic',
+ ...TEXT_STYLE_FIELDS,
'textDirection',
- 'letterSpacing',
- 'lineHeight',
- 'textCase',
- 'textDecoration',
- 'textDecorationStyle',
- 'textDecorationThickness',
- 'textUnderlineOffset',
- 'textDecorationFills',
- 'textDecorationSkipInk',
- 'textAlignHorizontal',
- 'textAlignVertical',
'textAutoResize',
'textTruncation',
'maxLines',
'leadingTrim',
- 'paragraphSpacing',
- 'paragraphIndent',
'listSpacing',
'hangingList',
- 'fontVariations',
- 'fontFeatures',
// Styled ranges belong to the characters: an instance that overrides its text keeps them.
'styleRuns',
'textParagraphs'
@@ -40,83 +29,13 @@ export const INSTANCE_SYNC_FIELD_OWNERS: Readonly<Partial<Record<string, string>
textParagraphs: 'text'
}
-export const INSTANCE_SYNC_PROPS: (keyof SceneNode)[] = [
- 'width',
- 'height',
- 'minWidth',
- 'maxWidth',
- 'minHeight',
- 'maxHeight',
- 'targetAspectRatio',
- 'fills',
- 'strokes',
- 'effects',
- 'opacity',
- 'cornerRadius',
- 'topLeftRadius',
- 'topRightRadius',
- 'bottomRightRadius',
- 'bottomLeftRadius',
- 'independentCorners',
- 'layoutMode',
- 'layoutDirection',
- 'layoutWrap',
- 'primaryAxisAlign',
- 'counterAxisAlign',
- 'primaryAxisSizing',
- 'counterAxisSizing',
- 'itemSpacing',
- 'counterAxisSpacing',
- 'paddingTop',
- 'paddingRight',
- 'paddingBottom',
- 'paddingLeft',
- 'gridTemplateColumns',
- 'gridTemplateRows',
- 'gridColumnGap',
- 'gridRowGap',
- 'gridPosition',
- 'clipsContent',
- 'itemReverseZIndex',
- 'strokesIncludedInLayout',
- 'layoutGrids',
- 'blendMode',
- 'cornerSmoothing',
- 'strokeWeight',
- 'strokeAlign',
- 'strokeCap',
- 'strokeJoin',
- 'strokeMiterLimit',
- 'dashPattern',
- 'independentStrokeWeights',
- 'borderTopWeight',
- 'borderRightWeight',
- 'borderBottomWeight',
- 'borderLeftWeight',
- 'boundVariables',
- 'variableModes',
- // Applied shared styles follow the component unless an instance overrides them.
- 'fillStyleId',
- 'strokeStyleId',
- 'textStyleId',
- 'effectStyleId',
- 'gridStyleId'
-]
-
-/** How a layer inside an instance sits in its parent and whether it is locked, which its overrides may change. */
-export const INSTANCE_SYNC_CHILD_PROPS = ['layoutGrow', 'layoutAlignSelf', 'locked'] as const
-
/**
* Where a component's layer sits and how it is shaped, which Figma refuses to override in an
* instance ("This property cannot be overridden in an instance"), so its copies always follow.
* A layer in an auto layout flow takes its position from the layout instead.
*/
export const INSTANCE_FOLLOWED_FIELDS = [
- 'x',
- 'y',
- 'rotation',
- 'flipX',
- 'flipY',
+ ...TRANSFORM_FIELDS,
'horizontalConstraint',
'verticalConstraint',
'layoutPositioning',
@@ -128,6 +47,30 @@ export const INSTANCE_FOLLOWED_FIELDS = [
'starInnerRadius'
] as const
+/** Fields a component's layer gives its copies unless an instance overrides them. */
+export const INSTANCE_SYNC_PROPS: (keyof SceneNode)[] = difference(
+ [
+ ...SIZE_FIELDS,
+ ...SIZE_CONSTRAINT_FIELDS,
+ ...PAINT_FIELDS,
+ ...STROKE_FIELDS,
+ ...CORNER_FIELDS,
+ ...AUTO_LAYOUT_FIELDS,
+ 'itemReverseZIndex',
+ 'gridPosition',
+ 'clipsContent',
+ 'layoutGrids',
+ 'boundVariables',
+ 'variableModes',
+ // Applied shared styles follow the component unless an instance overrides them.
+ ...STYLE_LINK_FIELDS
+ ],
+ INSTANCE_FOLLOWED_FIELDS
+)
+
+/** How a layer inside an instance sits in its parent and whether it is locked, which its overrides may change. */
+export const INSTANCE_SYNC_CHILD_PROPS = ['layoutGrow', 'layoutAlignSelf', 'locked'] as const
+
/** Fields an edit to a layer inside an instance records as that instance's override. */
export const INSTANCE_OVERRIDE_FIELDS = [
...INSTANCE_SYNC_PROPS,
diff --git a/packages/scene-graph/src/shared-styles.ts b/packages/scene-graph/src/shared-styles.ts
index 5a98e87f9..a9197318f 100644
--- a/packages/scene-graph/src/shared-styles.ts
+++ b/packages/scene-graph/src/shared-styles.ts
@@ -8,6 +8,9 @@ const STYLE_REF_KEYS = {
grid: 'gridStyleId'
} as const satisfies Record<SharedStyleKind, keyof SceneNode>
+/** The fields that link a layer to its shared styles. */
+export const STYLE_LINK_FIELDS = Object.values(STYLE_REF_KEYS)
+
const STYLE_TYPES = {
fill: 'FILL',
stroke: 'FILL',
diff --git a/packages/vue/src/i18n/locales/de/menu.json b/packages/vue/src/i18n/locales/de/menu.json
index 6c4eb1281..79cb1cdf2 100644
--- a/packages/vue/src/i18n/locales/de/menu.json
+++ b/packages/vue/src/i18n/locales/de/menu.json
@@ -37,6 +37,8 @@
"underline": "Unterstrichen",
"pasteHere": "Hier einfügen",
"pasteToReplace": "Zum Ersetzen einfügen",
+ "copyProperties": "Eigenschaften kopieren",
+ "pasteProperties": "Eigenschaften einfügen",
"copyPasteAs": "Kopieren/Einfügen als",
"copyAsText": "Als Text kopieren",
"copyAsSVG": "Als SVG kopieren",
diff --git a/packages/vue/src/i18n/locales/es/menu.json b/packages/vue/src/i18n/locales/es/menu.json
index 05703ad8f..a9e610833 100644
--- a/packages/vue/src/i18n/locales/es/menu.json
+++ b/packages/vue/src/i18n/locales/es/menu.json
@@ -36,6 +36,8 @@
"strikethrough": "Tachado",
"pasteHere": "Pegar aquí",
"pasteToReplace": "Pegar y reemplazar",
+ "copyProperties": "Copiar propiedades",
+ "pasteProperties": "Pegar propiedades",
"copyPasteAs": "Copiar/Pegar como",
"copyAsText": "Copiar como texto",
"copyAsSVG": "Copiar como SVG",
diff --git a/packages/vue/src/i18n/locales/fr/menu.json b/packages/vue/src/i18n/locales/fr/menu.json
index d3c59f761..e38138351 100644
--- a/packages/vue/src/i18n/locales/fr/menu.json
+++ b/packages/vue/src/i18n/locales/fr/menu.json
@@ -37,6 +37,8 @@
"underline": "Souligné",
"pasteHere": "Coller ici",
"pasteToReplace": "Coller pour remplacer",
+ "copyProperties": "Copier les propriétés",
+ "pasteProperties": "Coller les propriétés",
"copyPasteAs": "Copier/Coller en tant que",
"copyAsText": "Copier en texte",
"copyAsSVG": "Copier en SVG",
diff --git a/packages/vue/src/i18n/locales/it/menu.json b/packages/vue/src/i18n/locales/it/menu.json
index 71f0c6733..a48d8d538 100644
--- a/packages/vue/src/i18n/locales/it/menu.json
+++ b/packages/vue/src/i18n/locales/it/menu.json
@@ -37,6 +37,8 @@
"underline": "Sottolineato",
"pasteHere": "Incolla qui",
"pasteToReplace": "Incolla per sostituire",
+ "copyProperties": "Copia proprietà",
+ "pasteProperties": "Incolla proprietà",
"copyPasteAs": "Copia/Incolla come",
"copyAsText": "Copia come testo",
"copyAsSVG": "Copia come SVG",
diff --git a/packages/vue/src/i18n/locales/ja/menu.json b/packages/vue/src/i18n/locales/ja/menu.json
index 315784623..47bf8171c 100644
--- a/packages/vue/src/i18n/locales/ja/menu.json
+++ b/packages/vue/src/i18n/locales/ja/menu.json
@@ -36,6 +36,8 @@
"strikethrough": "打ち消し線",
"pasteHere": "ここに貼り付け",
"pasteToReplace": "貼り付けて置換",
+ "copyProperties": "プロパティをコピー",
+ "pasteProperties": "プロパティを貼り付け",
"copyPasteAs": "形式を選択してコピー/貼り付け",
"copyAsText": "テキストとしてコピー",
"copyAsSVG": "SVGとしてコピー",
diff --git a/packages/vue/src/i18n/locales/pl/menu.json b/packages/vue/src/i18n/locales/pl/menu.json
index a519fab2e..236484ed6 100644
--- a/packages/vue/src/i18n/locales/pl/menu.json
+++ b/packages/vue/src/i18n/locales/pl/menu.json
@@ -37,6 +37,8 @@
"underline": "Podkreślenie",
"pasteHere": "Wklej tutaj",
"pasteToReplace": "Wklej, aby zastąpić",
+ "copyProperties": "Kopiuj właściwości",
+ "pasteProperties": "Wklej właściwości",
"copyPasteAs": "Kopiuj/Wklej jako",
"copyAsText": "Kopiuj jako tekst",
"copyAsSVG": "Kopiuj jako SVG",
diff --git a/packages/vue/src/i18n/locales/ru/menu.json b/packages/vue/src/i18n/locales/ru/menu.json
index 51b9bc9a9..ccc6e765c 100644
--- a/packages/vue/src/i18n/locales/ru/menu.json
+++ b/packages/vue/src/i18n/locales/ru/menu.json
@@ -37,6 +37,8 @@
"underline": "Подчёркнутый",
"pasteHere": "Вставить сюда",
"pasteToReplace": "Вставить для замены",
+ "copyProperties": "Копировать свойства",
+ "pasteProperties": "Вставить свойства",
"copyPasteAs": "Копировать/Вставить как",
"copyAsText": "Копировать как текст",
"copyAsSVG": "Копировать как SVG",
diff --git a/packages/vue/src/i18n/locales/zh-cn/menu.json b/packages/vue/src/i18n/locales/zh-cn/menu.json
index 6d08ec7fe..6bf77b130 100644
--- a/packages/vue/src/i18n/locales/zh-cn/menu.json
+++ b/packages/vue/src/i18n/locales/zh-cn/menu.json
@@ -37,6 +37,8 @@
"underline": "下划线",
"pasteHere": "粘贴到这里",
"pasteToReplace": "粘贴并替换",
+ "copyProperties": "复制属性",
+ "pasteProperties": "粘贴属性",
"copyPasteAs": "复制/粘贴为",
"copyAsText": "复制为文本",
"copyAsSVG": "复制为 SVG",
diff --git a/packages/vue/src/i18n/messages/menu.ts b/packages/vue/src/i18n/messages/menu.ts
index b8ddd18f2..c268ea1e6 100644
--- a/packages/vue/src/i18n/messages/menu.ts
+++ b/packages/vue/src/i18n/messages/menu.ts
@@ -65,6 +65,8 @@ export const menuMessageDefaults = {
pasteHere: 'Paste here',
pasteToReplace: 'Paste to replace',
+ copyProperties: 'Copy properties',
+ pasteProperties: 'Paste properties',
renameSelection: 'Rename selection…',
copyPasteAs: 'Copy/Paste as',
copyAsText: 'Copy as text',
diff --git a/src/app/editor/canvas/menu/actions.ts b/src/app/editor/canvas/menu/actions.ts
index 3bbbb8766..499348227 100644
--- a/src/app/editor/canvas/menu/actions.ts
+++ b/src/app/editor/canvas/menu/actions.ts
@@ -4,6 +4,10 @@ import { nodeToXPath } from '@open-pencil/core/xpath'
import type { EditorStore } from '@/app/editor/active-store'
import { pasteClipboardToReplace } from '@/app/editor/clipboard/paste/replace'
+import {
+ copySelectionProperties,
+ pasteClipboardProperties
+} from '@/app/editor/clipboard/properties'
import { executeClipboardCommand } from '@/app/editor/clipboard/system'
import { createTextClipboard } from '@/app/editor/clipboard/text'
import { canVectorizeImageNode, vectorizeImageNode } from '@/app/editor/vectorize'
@@ -73,6 +77,8 @@ export function createCanvasMenuActions(store: EditorStore, selectedIds: Ref<Set
ids,
execCommand,
pasteToReplace: () => pasteClipboardToReplace(store),
+ copyProperties: () => copySelectionProperties(store),
+ pasteProperties: () => pasteClipboardProperties(store),
clipboardWrite,
copyNodeId,
copyXPath,
diff --git a/src/app/editor/canvas/menu/context.ts b/src/app/editor/canvas/menu/context.ts
index 7f465b5e3..98f7fb5c0 100644
--- a/src/app/editor/canvas/menu/context.ts
+++ b/src/app/editor/canvas/menu/context.ts
@@ -6,8 +6,10 @@ import type { createCanvasMenuActions } from '@/app/editor/canvas/menu/actions'
import {
CANVAS_COPY_AS_ACTIONS,
CANVAS_COPY_AS_GROUP_TEST_ID,
+ CANVAS_PROPERTIES_ACTIONS,
CANVAS_VECTORIZE_TEST_ID,
- type CanvasContextActionId
+ type CanvasContextActionId,
+ type CanvasContextActionMeta
} from '@/app/editor/canvas/menu/registry'
const STATIC_SELECTION_COMMAND_IDS = new Set(['selection.duplicate', 'selection.delete'])
@@ -22,6 +24,8 @@ type CanvasCopyLabels = {
copyAsJSX: string
copyNodeId: string
copyXPath: string
+ copyProperties: string
+ pasteProperties: string
convertToVector: string
}
@@ -58,6 +62,10 @@ function copyAction(
return runAsync(actions.copyNodeId)
case 'copy-xpath':
return runAsync(actions.copyXPath)
+ case 'copy-properties':
+ return runAsync(actions.copyProperties)
+ case 'paste-properties':
+ return runAsync(actions.pasteProperties)
default: {
const exhaustive: never = id
return exhaustive
@@ -70,15 +78,20 @@ function copyPasteAsEntry(
actions: CanvasMenuActions,
labels: CanvasCopyLabels
): MenuEntry {
+ const item = (meta: CanvasContextActionMeta): MenuEntry => ({
+ label: labels[meta.labelKey],
+ testId: meta.testId,
+ shortcut: formatShortcut(meta.shortcut),
+ action: copyAction(meta.id, editor, actions)
+ })
return {
label: labels.copyPasteAs,
testId: CANVAS_COPY_AS_GROUP_TEST_ID,
- sub: CANVAS_COPY_AS_ACTIONS.map((meta) => ({
- label: labels[meta.labelKey],
- testId: meta.testId,
- shortcut: formatShortcut(meta.shortcut),
- action: copyAction(meta.id, editor, actions)
- }))
+ sub: [
+ ...CANVAS_COPY_AS_ACTIONS.map(item),
+ { separator: true },
+ ...CANVAS_PROPERTIES_ACTIONS.map(item)
+ ]
}
}
diff --git a/src/app/editor/canvas/menu/registry.ts b/src/app/editor/canvas/menu/registry.ts
index d4c9fe7b0..3f9eef1f2 100644
--- a/src/app/editor/canvas/menu/registry.ts
+++ b/src/app/editor/canvas/menu/registry.ts
@@ -7,6 +7,8 @@ export type CanvasContextActionId =
| 'copy-as-jsx'
| 'copy-node-id'
| 'copy-xpath'
+ | 'copy-properties'
+ | 'paste-properties'
export type CanvasContextLabelKey =
| 'copyAsText'
@@ -15,6 +17,8 @@ export type CanvasContextLabelKey =
| 'copyAsJSX'
| 'copyNodeId'
| 'copyXPath'
+ | 'copyProperties'
+ | 'pasteProperties'
export type CanvasContextActionMeta = {
id: CanvasContextActionId
@@ -35,3 +39,19 @@ export const CANVAS_COPY_AS_ACTIONS = [
{ id: 'copy-node-id', labelKey: 'copyNodeId' },
{ id: 'copy-xpath', labelKey: 'copyXPath' }
] satisfies CanvasContextActionMeta[]
+
+/** Figma lists these under Copy/Paste as, after the copy formats. */
+export const CANVAS_PROPERTIES_ACTIONS = [
+ {
+ id: 'copy-properties',
+ labelKey: 'copyProperties',
+ shortcut: 'MOD+ALT+C',
+ testId: 'context-copy-properties'
+ },
+ {
+ id: 'paste-properties',
+ labelKey: 'pasteProperties',
+ shortcut: 'MOD+ALT+V',
+ testId: 'context-paste-properties'
+ }
+] satisfies CanvasContextActionMeta[]
diff --git a/src/app/editor/clipboard/paste/replace.ts b/src/app/editor/clipboard/paste/replace.ts
index a8dc0f48a..8ee477787 100644
--- a/src/app/editor/clipboard/paste/replace.ts
+++ b/src/app/editor/clipboard/paste/replace.ts
@@ -1,45 +1,8 @@
import type { EditorStore } from '@/app/editor/active-store'
-import { isDesignClipboardHTML } from '@/app/editor/clipboard/html'
-import { getInMemoryClipboardHTML } from '@/app/editor/clipboard/memory'
import { pasteClipboardHTML } from '@/app/editor/clipboard/paste/content'
+import { readClipboardHTML } from '@/app/editor/clipboard/read'
import { notificationMessages } from '@/app/i18n/notifications'
import { toast } from '@/app/shell/ui'
-import { readTauriClipboardText } from '@/app/tauri/clipboard'
-import { isTauri } from '@/app/tauri/env'
-
-async function readClipboardHTML() {
- if (isTauri()) {
- try {
- const text = await readTauriClipboardText()
- if (isDesignClipboardHTML(text ?? '')) return text
- const memory = getInMemoryClipboardHTML(text ?? '')
- return memory && isDesignClipboardHTML(memory) ? memory : null
- } catch (error) {
- console.warn('Tauri clipboard read failed', error)
- const memory = getInMemoryClipboardHTML()
- return memory && isDesignClipboardHTML(memory) ? memory : null
- }
- }
-
- if (
- typeof navigator !== 'undefined' &&
- typeof (navigator as Partial<Navigator>).clipboard?.read === 'function'
- ) {
- try {
- const items = await navigator.clipboard.read()
- for (const item of items) {
- if (!item.types.includes('text/html')) continue
- const text = await (await item.getType('text/html')).text()
- if (text && isDesignClipboardHTML(text)) return text
- }
- } catch (error) {
- console.warn('System clipboard read failed', error)
- }
- }
-
- const memory = getInMemoryClipboardHTML()
- return memory && isDesignClipboardHTML(memory) ? memory : null
-}
export async function pasteClipboardToReplace(store: EditorStore) {
try {
diff --git a/src/app/editor/clipboard/properties.ts b/src/app/editor/clipboard/properties.ts
new file mode 100644
index 000000000..06a92a4cc
--- /dev/null
+++ b/src/app/editor/clipboard/properties.ts
@@ -0,0 +1,33 @@
+import type { EditorStore } from '@/app/editor/active-store'
+import { matchingClipboardSnapshot } from '@/app/editor/clipboard/memory'
+import { readClipboardHTML } from '@/app/editor/clipboard/read'
+import { resolveSystemClipboard } from '@/app/editor/clipboard/system'
+import { notificationMessages } from '@/app/i18n/notifications'
+import { toast } from '@/app/shell/ui'
+
+/** Copy properties: the selection on the system clipboard, marked so Paste skips it, as in Figma. */
+export async function copySelectionProperties(store: EditorStore) {
+ if (store.state.selectedIds.size === 0) return
+ const messages = notificationMessages.get()
+ if (await resolveSystemClipboard().copy(store, { properties: true }))
+ toast.info(messages.copiedProperties)
+ else toast.error(messages.clipboardAccessBlocked)
+}
+
+/** Paste properties: the look of the one copied layer, from here, another tab, or Figma. */
+export async function pasteClipboardProperties(store: EditorStore) {
+ if (store.state.selectedIds.size === 0) return
+ try {
+ const html = await readClipboardHTML()
+ if (!html) {
+ toast.error(notificationMessages.get().clipboardMissingDesignData)
+ return
+ }
+ const snapshot = matchingClipboardSnapshot(html)
+ if (snapshot) await store.pastePropertiesFromSnapshot(snapshot)
+ else await store.pastePropertiesFromHTML(html)
+ } catch (error) {
+ console.warn('Paste properties failed', error)
+ toast.error(notificationMessages.get().clipboardAccessBlocked)
+ }
+}
diff --git a/src/app/editor/clipboard/read.ts b/src/app/editor/clipboard/read.ts
new file mode 100644
index 000000000..d3cec3ec7
--- /dev/null
+++ b/src/app/editor/clipboard/read.ts
@@ -0,0 +1,47 @@
+import { isDesignClipboardHTML } from '@/app/editor/clipboard/html'
+import { getInMemoryClipboardHTML } from '@/app/editor/clipboard/memory'
+import { readTauriClipboardText } from '@/app/tauri/clipboard'
+import { isTauri } from '@/app/tauri/env'
+
+/** The browser's asynchronous clipboard, where this context has one. */
+function browserClipboard(): Pick<Clipboard, 'read'> | undefined {
+ if (typeof navigator === 'undefined') return undefined
+ const { clipboard } = navigator as Partial<Navigator>
+ return typeof clipboard?.read === 'function' ? clipboard : undefined
+}
+
+/** The design layers on the system clipboard, or the last copy made here when it cannot be read. */
+export async function readClipboardHTML(
+ clipboard: Pick<Clipboard, 'read'> | undefined = browserClipboard()
+): Promise<string | null> {
+ if (isTauri()) {
+ try {
+ const text = await readTauriClipboardText()
+ if (isDesignClipboardHTML(text ?? '')) return text
+ const memory = getInMemoryClipboardHTML(text ?? '')
+ return memory && isDesignClipboardHTML(memory) ? memory : null
+ } catch (error) {
+ console.warn('Tauri clipboard read failed', error)
+ const memory = getInMemoryClipboardHTML()
+ return memory && isDesignClipboardHTML(memory) ? memory : null
+ }
+ }
+
+ if (clipboard) {
+ try {
+ const items = await clipboard.read()
+ for (const item of items) {
+ if (!item.types.includes('text/html')) continue
+ const text = await (await item.getType('text/html')).text()
+ if (text && isDesignClipboardHTML(text)) return text
+ }
+ // A readable clipboard without design layers holds something newer than our last copy.
+ return null
+ } catch (error) {
+ console.warn('System clipboard read failed', error)
+ }
+ }
+
+ const memory = getInMemoryClipboardHTML()
+ return memory && isDesignClipboardHTML(memory) ? memory : null
+}
diff --git a/src/app/editor/clipboard/system/browser.ts b/src/app/editor/clipboard/system/browser.ts
index 02d955eb4..f677e6ebf 100644
--- a/src/app/editor/clipboard/system/browser.ts
+++ b/src/app/editor/clipboard/system/browser.ts
@@ -1,5 +1,6 @@
import copy from 'copy-to-clipboard'
+import type { CopyOptions } from '@open-pencil/core/editor'
import type { Vector } from '@open-pencil/scene-graph/primitives'
import type { EditorStore } from '@/app/editor/active-store'
@@ -76,10 +77,14 @@ const browserClipboardIO: BrowserClipboardIO = {
read: readBrowserClipboard
}
-async function copySelection(store: EditorStore, io: BrowserClipboardIO): Promise<boolean> {
+async function copySelection(
+ store: EditorStore,
+ io: BrowserClipboardIO,
+ options?: CopyOptions
+): Promise<boolean> {
try {
if (store.state.selectedIds.size === 0) return false
- const prepared = store.prepareCopy()
+ const prepared = store.prepareCopy(options)
const writing = io.write(prepared)
const [payload, written] = await Promise.all([prepared, writing])
if (!payload.html && !payload.plainText) return false
@@ -120,7 +125,7 @@ export function createBrowserSystemClipboard(
io: BrowserClipboardIO = browserClipboardIO
): SystemClipboard {
return {
- copy: (store) => copySelection(store, io),
+ copy: (store, options) => copySelection(store, io, options),
paste: (store, cursorPos) => pasteSelection(store, cursorPos, io)
}
}
diff --git a/src/app/editor/clipboard/system/index.ts b/src/app/editor/clipboard/system/index.ts
index 7fac96159..8b707a58e 100644
--- a/src/app/editor/clipboard/system/index.ts
+++ b/src/app/editor/clipboard/system/index.ts
@@ -6,7 +6,7 @@ import { tauriSystemClipboard } from '@/app/editor/clipboard/system/tauri'
import type { SystemClipboard } from '@/app/editor/clipboard/system/types'
import { isTauri } from '@/app/tauri/env'
-function resolveSystemClipboard(): SystemClipboard {
+export function resolveSystemClipboard(): SystemClipboard {
return isTauri() ? tauriSystemClipboard : browserSystemClipboard
}
diff --git a/src/app/editor/clipboard/system/tauri.ts b/src/app/editor/clipboard/system/tauri.ts
index bb6d3515b..033cee928 100644
--- a/src/app/editor/clipboard/system/tauri.ts
+++ b/src/app/editor/clipboard/system/tauri.ts
@@ -1,3 +1,4 @@
+import type { CopyOptions } from '@open-pencil/core/editor'
import type { Vector } from '@open-pencil/scene-graph/primitives'
import type { EditorStore } from '@/app/editor/active-store'
@@ -16,10 +17,10 @@ import {
} from '@/app/tauri/clipboard'
import { isTauri } from '@/app/tauri/env'
-async function copySelection(store: EditorStore): Promise<boolean> {
+async function copySelection(store: EditorStore, options?: CopyOptions): Promise<boolean> {
if (!isTauri()) return false
try {
- const payload = await store.prepareCopy()
+ const payload = await store.prepareCopy(options)
const { html, plainText } = payload
if (!html && !plainText) return false
if (html) {
diff --git a/src/app/editor/clipboard/system/types.ts b/src/app/editor/clipboard/system/types.ts
index d03f234da..61c94a6b1 100644
--- a/src/app/editor/clipboard/system/types.ts
+++ b/src/app/editor/clipboard/system/types.ts
@@ -1,11 +1,11 @@
-import type { ClipboardPayload } from '@open-pencil/core/editor'
+import type { ClipboardPayload, CopyOptions } from '@open-pencil/core/editor'
import type { Vector } from '@open-pencil/scene-graph/primitives'
import type { EditorStore } from '@/app/editor/active-store'
export type { ClipboardPayload } from '@open-pencil/core/editor'
export interface SystemClipboard {
- copy(store: EditorStore): Promise<boolean>
+ copy(store: EditorStore, options?: CopyOptions): Promise<boolean>
paste(store: EditorStore, cursorPos?: Vector): Promise<boolean>
}
diff --git a/src/app/i18n/notifications/index.ts b/src/app/i18n/notifications/index.ts
index 4e1eef887..dd5ab7992 100644
--- a/src/app/i18n/notifications/index.ts
+++ b/src/app/i18n/notifications/index.ts
@@ -10,6 +10,7 @@ export const notificationMessageDefaults = {
clipboardMissingDesignData: 'Clipboard does not contain design data.',
clipboardAccessBlocked: 'Clipboard access is blocked in this browser context.',
copiedAs: params('Copied as {format}.'),
+ copiedProperties: 'Copied properties.',
tokensLeftOut: params('Left out of the stylesheet: {names}.'),
designTokensLeftOut: params('Left out of the design tokens: {names}.'),
designTokensImported: params('Imported {count} design tokens.'),
diff --git a/src/app/i18n/notifications/locales/de.json b/src/app/i18n/notifications/locales/de.json
index 1aea28d8a..00eac411d 100644
--- a/src/app/i18n/notifications/locales/de.json
+++ b/src/app/i18n/notifications/locales/de.json
@@ -4,6 +4,7 @@
"clipboardMissingDesignData": "Die Zwischenablage enthält keine Designdaten.",
"clipboardAccessBlocked": "Der Zugriff auf die Zwischenablage ist in diesem Browserkontext blockiert.",
"copiedAs": "Als {format} kopiert.",
+ "copiedProperties": "Eigenschaften kopiert.",
"pngClipboardUnavailable": "Der PNG-Export in die Zwischenablage ist in diesem Browser nicht verfügbar.",
"openFileFailed": "„{name}“ konnte nicht geöffnet werden: {error}",
"importedDOMCSS": "DOM/CSS-Dokument importiert.",
diff --git a/src/app/i18n/notifications/locales/es.json b/src/app/i18n/notifications/locales/es.json
index 4e7a38316..2aa360ae6 100644
--- a/src/app/i18n/notifications/locales/es.json
+++ b/src/app/i18n/notifications/locales/es.json
@@ -4,6 +4,7 @@
"clipboardMissingDesignData": "El portapapeles no contiene datos de diseño.",
"clipboardAccessBlocked": "El acceso al portapapeles está bloqueado en este contexto del navegador.",
"copiedAs": "Copiado como {format}.",
+ "copiedProperties": "Propiedades copiadas.",
"pngClipboardUnavailable": "La exportación PNG al portapapeles no está disponible en este navegador.",
"openFileFailed": "No se pudo abrir «{name}»: {error}",
"importedDOMCSS": "Documento DOM/CSS importado.",
diff --git a/src/app/i18n/notifications/locales/fr.json b/src/app/i18n/notifications/locales/fr.json
index e9aae8966..304e9786a 100644
--- a/src/app/i18n/notifications/locales/fr.json
+++ b/src/app/i18n/notifications/locales/fr.json
@@ -4,6 +4,7 @@
"clipboardMissingDesignData": "Le presse-papiers ne contient aucune donnée de design.",
"clipboardAccessBlocked": "L’accès au presse-papiers est bloqué dans ce contexte de navigateur.",
"copiedAs": "Copié au format {format}.",
+ "copiedProperties": "Propriétés copiées.",
"pngClipboardUnavailable": "L’export PNG vers le presse-papiers n’est pas disponible dans ce navigateur.",
"openFileFailed": "Impossible d’ouvrir « {name} » : {error}",
"importedDOMCSS": "Document DOM/CSS importé.",
diff --git a/src/app/i18n/notifications/locales/it.json b/src/app/i18n/notifications/locales/it.json
index 3e456b9bb..59b4246f1 100644
--- a/src/app/i18n/notifications/locales/it.json
+++ b/src/app/i18n/notifications/locales/it.json
@@ -4,6 +4,7 @@
"clipboardMissingDesignData": "Gli appunti non contengono dati di design.",
"clipboardAccessBlocked": "L’accesso agli appunti è bloccato in questo contesto del browser.",
"copiedAs": "Copiato come {format}.",
+ "copiedProperties": "Proprietà copiate.",
"pngClipboardUnavailable": "L’esportazione PNG negli appunti non è disponibile in questo browser.",
"openFileFailed": "Impossibile aprire «{name}»: {error}",
"importedDOMCSS": "Documento DOM/CSS importato.",
diff --git a/src/app/i18n/notifications/locales/ja.json b/src/app/i18n/notifications/locales/ja.json
index a03e68c31..30705b0ee 100644
--- a/src/app/i18n/notifications/locales/ja.json
+++ b/src/app/i18n/notifications/locales/ja.json
@@ -4,6 +4,7 @@
"clipboardMissingDesignData": "クリップボードにデザインデータがありません。",
"clipboardAccessBlocked": "このブラウザー環境ではクリップボードへのアクセスがブロックされています。",
"copiedAs": "{format} としてコピーしました。",
+ "copiedProperties": "プロパティをコピーしました。",
"pngClipboardUnavailable": "このブラウザーでは PNG をクリップボードに書き出せません。",
"openFileFailed": "「{name}」を開けませんでした: {error}",
"importedDOMCSS": "DOM/CSS ドキュメントをインポートしました。",
diff --git a/src/app/i18n/notifications/locales/pl.json b/src/app/i18n/notifications/locales/pl.json
index 704619a2a..e29ae32d4 100644
--- a/src/app/i18n/notifications/locales/pl.json
+++ b/src/app/i18n/notifications/locales/pl.json
@@ -4,6 +4,7 @@
"clipboardMissingDesignData": "Schowek nie zawiera danych projektu.",
"clipboardAccessBlocked": "Dostęp do schowka jest zablokowany w tym kontekście przeglądarki.",
"copiedAs": "Skopiowano jako {format}.",
+ "copiedProperties": "Skopiowano właściwości.",
"pngClipboardUnavailable": "Eksport PNG do schowka nie jest dostępny w tej przeglądarce.",
"openFileFailed": "Nie udało się otworzyć „{name}”: {error}",
"importedDOMCSS": "Zaimportowano dokument DOM/CSS.",
diff --git a/src/app/i18n/notifications/locales/ru.json b/src/app/i18n/notifications/locales/ru.json
index 41864b6a8..45a05a06f 100644
--- a/src/app/i18n/notifications/locales/ru.json
+++ b/src/app/i18n/notifications/locales/ru.json
@@ -4,6 +4,7 @@
"clipboardMissingDesignData": "В буфере обмена нет данных дизайна.",
"clipboardAccessBlocked": "Доступ к буферу обмена заблокирован в этом контексте браузера.",
"copiedAs": "Скопировано как {format}.",
+ "copiedProperties": "Свойства скопированы.",
"pngClipboardUnavailable": "Экспорт PNG в буфер обмена недоступен в этом браузере.",
"openFileFailed": "Не удалось открыть «{name}»: {error}",
"importedDOMCSS": "Документ DOM/CSS импортирован.",
diff --git a/src/app/i18n/notifications/locales/zh-cn.json b/src/app/i18n/notifications/locales/zh-cn.json
index 992ecfe5b..4fffd1f4a 100644
--- a/src/app/i18n/notifications/locales/zh-cn.json
+++ b/src/app/i18n/notifications/locales/zh-cn.json
@@ -4,6 +4,7 @@
"clipboardMissingDesignData": "剪贴板中没有设计数据。",
"clipboardAccessBlocked": "当前浏览器环境阻止了剪贴板访问。",
"copiedAs": "已复制为 {format}。",
+ "copiedProperties": "已复制属性。",
"pngClipboardUnavailable": "此浏览器不支持将 PNG 导出到剪贴板。",
"openFileFailed": "无法打开“{name}”:{error}",
"importedDOMCSS": "已导入 DOM/CSS 文档。",
diff --git a/src/app/shell/keyboard/registry.ts b/src/app/shell/keyboard/registry.ts
index 820742d07..598f33428 100644
--- a/src/app/shell/keyboard/registry.ts
+++ b/src/app/shell/keyboard/registry.ts
@@ -6,6 +6,10 @@ import { editorCommandMetadata } from '@open-pencil/vue'
import type { EditorCommandId } from '@open-pencil/vue'
import { useComments } from '@/app/comments/use'
+import {
+ copySelectionProperties,
+ pasteClipboardProperties
+} from '@/app/editor/clipboard/properties'
import { requestRenameSelection } from '@/app/editor/selection/rename-dialog'
import { TOOL_SHORTCUTS } from '@/app/editor/session'
import { openSettingsDialog } from '@/app/settings/dialog'
@@ -166,6 +170,16 @@ export function registerKeyboardShortcuts(options: KeyboardShortcutOptions) {
'selection.flipHorizontal',
'selection.flipVertical'
),
+ {
+ id: 'copy-properties',
+ keys: '$mod+Alt+KeyC',
+ run: ({ store }) => void copySelectionProperties(store)
+ },
+ {
+ id: 'paste-properties',
+ keys: '$mod+Alt+KeyV',
+ run: ({ store }) => void pasteClipboardProperties(store)
+ },
{
id: 'export-selection-png',
keys: appMenuTinykeysShortcut('export-selection') ?? '$mod+Shift+KeyE',
diff --git a/tests/app/editor/clipboard/read.test.ts b/tests/app/editor/clipboard/read.test.ts
new file mode 100644
index 000000000..0c739a1b4
--- /dev/null
+++ b/tests/app/editor/clipboard/read.test.ts
@@ -0,0 +1,41 @@
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test'
+
+import { clearInMemoryClipboardHTML, setInMemoryClipboardHTML } from '@/app/editor/clipboard/memory'
+import { readClipboardHTML } from '@/app/editor/clipboard/read'
+
+import { asDouble } from '#tests/helpers/doubles'
+
+const DESIGN = '<span data-buffer="<!--(figma)AAAA(/figma)-->"></span>'
+const LAST_COPY = '<span data-buffer="<!--(figma)BBBB(/figma)-->"></span>'
+
+function item(types: Record<string, string>): ClipboardItem {
+ return asDouble<ClipboardItem>({
+ types: Object.keys(types),
+ getType: async (type: string) => new Blob([types[type] ?? ''], { type })
+ })
+}
+
+beforeEach(() => setInMemoryClipboardHTML(LAST_COPY))
+afterEach(() => clearInMemoryClipboardHTML())
+
+describe('readClipboardHTML', () => {
+ test('reads design layers from the system clipboard', async () => {
+ expect(await readClipboardHTML({ read: async () => [item({ 'text/html': DESIGN })] })).toBe(
+ DESIGN
+ )
+ })
+
+ test('a readable clipboard without design layers is not replaced by the last copy', async () => {
+ const clipboard = { read: async () => [item({ 'text/plain': 'copied elsewhere' })] }
+ expect(await readClipboardHTML(clipboard)).toBeNull()
+ })
+
+ test('falls back to the last copy when the clipboard cannot be read', async () => {
+ const clipboard = {
+ read: async (): Promise<ClipboardItem[]> => {
+ throw new Error('Read permission denied')
+ }
+ }
+ expect(await readClipboardHTML(clipboard)).toBe(LAST_COPY)
+ })
+})
diff --git a/tests/e2e/clipboard/copy-properties.spec.ts b/tests/e2e/clipboard/copy-properties.spec.ts
new file mode 100644
index 000000000..cd6a32802
--- /dev/null
+++ b/tests/e2e/clipboard/copy-properties.spec.ts
@@ -0,0 +1,104 @@
+import { expect, test, useEditorSetup } from '#tests/e2e/fixtures'
+import { expectDefined } from '#tests/helpers/assert'
+
+const editor = useEditorSetup()
+
+const SOURCE = { x: 100, y: 150, width: 120, height: 80 }
+const TARGET = { x: 400, y: 150, width: 120, height: 80 }
+
+test.beforeAll(async () => {
+ await editor.page.context().grantPermissions(['clipboard-read', 'clipboard-write'])
+})
+
+function centre(rect: typeof SOURCE) {
+ return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 }
+}
+
+async function drawRects() {
+ await editor.canvas.clearCanvas()
+ await editor.canvas.drawRect(SOURCE.x, SOURCE.y, SOURCE.width, SOURCE.height)
+ const sourceId = await editor.page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const [id] = store.state.selectedIds
+ if (!id) throw new Error('The drawn rectangle was not selected')
+ store.updateNode(id, { cornerRadius: 12, opacity: 0.5 })
+ return id
+ })
+ await editor.canvas.drawRect(TARGET.x, TARGET.y, TARGET.width, TARGET.height)
+ await editor.canvas.waitForRender()
+ return sourceId
+}
+
+async function selectAt(rect: typeof SOURCE) {
+ const { x, y } = centre(rect)
+ await editor.canvas.click(x, y)
+ await editor.canvas.waitForRender()
+}
+
+function selectedLook() {
+ return editor.page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const [id] = store.state.selectedIds
+ const node = id ? store.graph.getNode(id) : undefined
+ return node ? { id, cornerRadius: node.cornerRadius, opacity: node.opacity } : null
+ })
+}
+
+function layerCount() {
+ return editor.page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ return store.graph.getChildren(store.state.currentPageId).length
+ })
+}
+
+test('Alt+Cmd+C then Alt+Cmd+V moves the look of one layer to another, in one undo step', async () => {
+ const sourceId = await drawRects()
+ const before = expectDefined(await selectedLook(), 'target look')
+ expect(before.cornerRadius).toBe(0)
+
+ await selectAt(SOURCE)
+ expect((await selectedLook())?.id).toBe(sourceId)
+ await editor.page.keyboard.press('ControlOrMeta+Alt+KeyC')
+ await expect(editor.page.getByText('Copied properties.')).toBeVisible()
+
+ await selectAt(TARGET)
+ await editor.page.keyboard.press('ControlOrMeta+Alt+KeyV')
+ await expect.poll(selectedLook).toEqual({ id: before.id, cornerRadius: 12, opacity: 0.5 })
+
+ // Paste skips what Copy properties wrote, as in Figma.
+ const layers = await layerCount()
+ await editor.page.keyboard.press('ControlOrMeta+KeyV')
+ await editor.canvas.waitForRender()
+ expect(await layerCount()).toBe(layers)
+
+ await editor.page.keyboard.press('ControlOrMeta+KeyZ')
+ await editor.canvas.waitForRender()
+ expect(await selectedLook()).toEqual(before)
+})
+
+test('Paste properties reads an ordinary copy of a layer', async () => {
+ await drawRects()
+ await selectAt(SOURCE)
+ await editor.page.keyboard.press('ControlOrMeta+KeyC')
+ await selectAt(TARGET)
+ await editor.page.keyboard.press('ControlOrMeta+Alt+KeyV')
+ await expect.poll(selectedLook).toMatchObject({ cornerRadius: 12, opacity: 0.5 })
+})
+
+test('the Copy/Paste as menu copies and pastes properties', async () => {
+ await drawRects()
+ const box = expectDefined(await editor.canvas.canvas.boundingBox(), 'canvas bounds')
+ const fromMenu = async (rect: typeof SOURCE, testId: string) => {
+ const { x, y } = centre(rect)
+ await editor.page.mouse.click(box.x + x, box.y + y, { button: 'right' })
+ await editor.page.getByTestId('context-copy-paste-as').click({ force: true })
+ await editor.page.getByTestId(testId).click()
+ }
+
+ await fromMenu(SOURCE, 'context-copy-properties')
+ await fromMenu(TARGET, 'context-paste-properties')
+ await expect.poll(selectedLook).toMatchObject({ cornerRadius: 12, opacity: 0.5 })
+})
diff --git a/tests/engine/clipboard/figma/codec.test.ts b/tests/engine/clipboard/figma/codec.test.ts
index 082b8eb61..82b7f988f 100644
--- a/tests/engine/clipboard/figma/codec.test.ts
+++ b/tests/engine/clipboard/figma/codec.test.ts
@@ -27,6 +27,13 @@ test('Fig clipboard codec preserves prepared node changes and binary blobs', asy
expect(parsed?.blobs[0]).toBeInstanceOf(Uint8Array)
})
+test('Fig clipboard carries the Copy properties marker that Figma writes', async () => {
+ await initCodec()
+ expect((await parseFigmaClipboard(encodeFigmaClipboard([], [], 1)))?.assetType).toBe('UNKNOWN')
+ const properties = encodeFigmaClipboard([], [], 1, 'STYLE_PROPERTIES')
+ expect((await parseFigmaClipboard(properties))?.assetType).toBe('STYLE_PROPERTIES')
+})
+
test('Fig clipboard with malformed or mistyped metadata is ignored', async () => {
await initCodec()
const html = encodeFigmaClipboard([], [], 123)