Skip to content

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

fix(clipboard): fetch pasted Figma images on desktop

Danila Poyarkovfc855894383c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 77440eb56..79387b8a2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -42,6 +42,7 @@
- Preserve imported Figma text sizing more accurately, especially auto-sized text inside auto-layout frames.
- Match Figma auto-layout reflow when deleting children, hiding optional instance slots, or syncing component changes.
- Fix desktop clipboard copy, cut, and paste when browser clipboard events are unavailable.
+- Fetch image fills when pasting from Figma in the desktop app and warn when referenced images remain unavailable.
- Fix desktop "Share This File" links so they use the public app URL.
- Fix collaborators joining a room without receiving the current document contents.
- Fix `.fig` round-trips that could corrupt files because of duplicate generated IDs.
diff --git a/packages/core/src/editor/clipboard.ts b/packages/core/src/editor/clipboard.ts
index 78d321b96..5dbc39d73 100644
--- a/packages/core/src/editor/clipboard.ts
+++ b/packages/core/src/editor/clipboard.ts
@@ -99,6 +99,7 @@ export function createClipboardActions(ctx: EditorContext) {
const pasteTarget = replacementTargets[0]?.parentId ?? resolvePasteTarget(ctx)
const created = importClipboardNodes(figma.nodes, ctx.graph, pasteTarget, 0, 0, figma.blobs)
if (created.length > 0) {
+ await hydrateFigmaClipboardImages(figma.meta.fileKey, created)
if (replacementTargets.length > 0) {
replaceTargetsWithCreated(
ctx,
@@ -173,11 +174,47 @@ export function createClipboardActions(ctx: EditorContext) {
return created
}
+ function missingImageHashes(nodeIds: string[]) {
+ const hashes = new Set<string>()
+ for (const node of collectSubtrees(ctx.graph, nodeIds)) {
+ for (const fill of node.fills) {
+ if (fill.type === 'IMAGE' && fill.imageHash && !ctx.graph.images.has(fill.imageHash)) {
+ hashes.add(fill.imageHash)
+ }
+ }
+ }
+ return [...hashes]
+ }
+
+ async function hydrateFigmaClipboardImages(fileKey: string, nodeIds: string[]) {
+ const hashes = missingImageHashes(nodeIds)
+ if (hashes.length === 0) return
+
+ const resolver = ctx.resolveFigmaClipboardImages
+ if (resolver) {
+ try {
+ const images = await resolver(fileKey, hashes)
+ for (const hash of hashes) {
+ const bytes = images.get(hash)
+ if (bytes) ctx.graph.images.set(hash, bytes)
+ }
+ } catch (error) {
+ console.warn('Failed to fetch Figma clipboard images', error)
+ }
+ }
+
+ const missing = missingImageHashes(nodeIds).length
+ if (missing > 0) {
+ ctx.emitEditorEvent('clipboard:images-missing', {
+ total: hashes.length,
+ missing,
+ fetchAttempted: resolver !== null
+ })
+ }
+ }
+
function warnMissingImages(nodeIds: string[]) {
- const allNodes = collectSubtrees(ctx.graph, nodeIds)
- return allNodes.some((n) =>
- n.fills.some((f) => f.type === 'IMAGE' && f.imageHash && !ctx.graph.images.has(f.imageHash))
- )
+ return missingImageHashes(nodeIds).length > 0
}
function deleteSelected() {
diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.ts
index f36dbc5b6..8575cf8b4 100644
--- a/packages/core/src/editor/create.ts
+++ b/packages/core/src/editor/create.ts
@@ -138,6 +138,7 @@ export function createEditor(options?: EditorOptions) {
undo,
state,
loadFont: _loadFont,
+ resolveFigmaClipboardImages: options?.resolveFigmaClipboardImages ?? null,
getViewportSize: _getViewportSize,
getCk: () => _ck,
getRenderer: () => _renderer,
diff --git a/packages/core/src/editor/index.ts b/packages/core/src/editor/index.ts
index 6f266d20c..b45aef294 100644
--- a/packages/core/src/editor/index.ts
+++ b/packages/core/src/editor/index.ts
@@ -4,10 +4,12 @@ export { createTextActions } from './text'
export { EDITOR_TOOLS, TOOL_SHORTCUTS } from './tool-registry'
export type { EditorToolDef } from './tool-registry'
export type {
+ ClipboardImageResolution,
EditorContext,
EditorEventName,
EditorEvents,
EditorOptions,
EditorState,
+ FigmaClipboardImageResolver,
Tool
} from './types'
diff --git a/packages/core/src/editor/types.ts b/packages/core/src/editor/types.ts
index 313ebf131..0abf0cf86 100644
--- a/packages/core/src/editor/types.ts
+++ b/packages/core/src/editor/types.ts
@@ -87,6 +87,17 @@ export interface EditorState {
cursorCanvasY?: number | null
}
+export interface ClipboardImageResolution {
+ total: number
+ missing: number
+ fetchAttempted: boolean
+}
+
+export type FigmaClipboardImageResolver = (
+ fileKey: string,
+ hashes: string[]
+) => Promise<ReadonlyMap<string, Uint8Array>>
+
export interface EditorEvents extends SceneGraphEvents {
'render:requested': (versions: { renderVersion: number; sceneVersion: number }) => void
'repaint:requested': (versions: { renderVersion: number; sceneVersion: number }) => void
@@ -94,6 +105,7 @@ export interface EditorEvents extends SceneGraphEvents {
'selection:changed': (selectedIds: string[], previousIds: string[]) => void
'tool:changed': (tool: Tool, previousTool: Tool) => void
'page:changed': (pageId: string, previousPageId: string) => void
+ 'clipboard:images-missing': (resolution: ClipboardImageResolution) => void
'viewport:changed': (
viewport: { panX: number; panY: number; zoom: number },
previous: { panX: number; panY: number; zoom: number }
@@ -106,6 +118,7 @@ export interface EditorOptions {
graph?: SceneGraph
state?: EditorState
loadFont?: (family: string, style: string, characters?: string) => Promise<ArrayBuffer | null>
+ resolveFigmaClipboardImages?: FigmaClipboardImageResolver
getViewportSize?: () => { width: number; height: number }
skipInitialGraphSetup?: boolean
}
@@ -116,6 +129,7 @@ export interface EditorContext {
undo: UndoManager
state: EditorState
loadFont: (family: string, style: string, characters?: string) => Promise<ArrayBuffer | null>
+ resolveFigmaClipboardImages: FigmaClipboardImageResolver | null
getViewportSize: () => { width: number; height: number }
getCk: () => CanvasKit | null
getRenderer: () => SkiaRenderer | null
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 8a796b53d..be26a978a 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -7,11 +7,13 @@ export * from './constants'
export { createDefaultEditorState, createEditor, EDITOR_TOOLS, TOOL_SHORTCUTS } from './editor'
export type {
+ ClipboardImageResolution,
Editor,
EditorContext,
EditorOptions,
EditorState,
EditorToolDef,
+ FigmaClipboardImageResolver,
Tool
} from './editor'
diff --git a/src/app/editor/clipboard/figma-images.ts b/src/app/editor/clipboard/figma-images.ts
new file mode 100644
index 000000000..4b87b7e37
--- /dev/null
+++ b/src/app/editor/clipboard/figma-images.ts
@@ -0,0 +1,83 @@
+import { tauriFetch } from '@/app/tauri/http'
+
+type ClipboardImageFetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>
+
+type FigmaImageURLs = Record<string, string>
+
+const IMAGE_FETCH_CONCURRENCY = 6
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
+}
+
+function imageURLsFromBatchResponse(value: unknown): FigmaImageURLs {
+ if (
+ !isRecord(value) ||
+ value.error === true ||
+ (typeof value.status === 'number' && value.status !== 200) ||
+ !isRecord(value.meta)
+ ) {
+ throw new Error('Figma returned an invalid image response')
+ }
+ const urls = value.meta.s3_urls
+ if (!isRecord(urls)) throw new Error('Figma returned an invalid image URL map')
+
+ const result: FigmaImageURLs = {}
+ for (const [hash, url] of Object.entries(urls)) {
+ if (typeof url === 'string') result[hash] = url
+ }
+ return result
+}
+
+async function sha1Hex(bytes: Uint8Array): Promise<string> {
+ const digest = await crypto.subtle.digest('SHA-1', Uint8Array.from(bytes))
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('')
+}
+
+export async function resolveFigmaClipboardImages(
+ fileKey: string,
+ hashes: string[],
+ fetcher: ClipboardImageFetch = tauriFetch
+): Promise<ReadonlyMap<string, Uint8Array>> {
+ const uniqueHashes = [...new Set(hashes)]
+ if (uniqueHashes.length === 0) return new Map()
+
+ const batchResponse = await fetcher(
+ `https://www.figma.com/file/${encodeURIComponent(fileKey)}/image/batch`,
+ {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ sha1s: uniqueHashes, needs_compressed_textures: false })
+ }
+ )
+ if (!batchResponse.ok) {
+ throw new Error(`Figma image request failed with status ${batchResponse.status}`)
+ }
+
+ const payload: unknown = await batchResponse.json()
+ const urls = imageURLsFromBatchResponse(payload)
+ const images = new Map<string, Uint8Array>()
+
+ for (let offset = 0; offset < uniqueHashes.length; offset += IMAGE_FETCH_CONCURRENCY) {
+ const batch = uniqueHashes.slice(offset, offset + IMAGE_FETCH_CONCURRENCY)
+ await Promise.all(
+ batch.map(async (hash) => {
+ const url = urls[hash]
+ if (!url) return
+ try {
+ const response = await fetcher(url)
+ if (!response.ok) throw new Error(`status ${response.status}`)
+ const bytes = new Uint8Array(await response.arrayBuffer())
+ if ((await sha1Hex(bytes)) !== hash.toLowerCase()) {
+ throw new Error('SHA-1 mismatch')
+ }
+ images.set(hash, bytes)
+ } catch (error) {
+ console.warn(`Failed to fetch pasted Figma image ${hash}`, error)
+ }
+ })
+ )
+ }
+
+ return images
+}
diff --git a/src/app/editor/clipboard/notifications.ts b/src/app/editor/clipboard/notifications.ts
new file mode 100644
index 000000000..20eaedf19
--- /dev/null
+++ b/src/app/editor/clipboard/notifications.ts
@@ -0,0 +1,28 @@
+import type { ClipboardImageResolution, Editor } from '@open-pencil/core/editor'
+
+import { toast } from '@/app/shell/ui'
+
+function imageCount(count: number) {
+ return `${count} image${count === 1 ? '' : 's'}`
+}
+
+export function notifyClipboardImageResolution({
+ total,
+ missing,
+ fetchAttempted
+}: ClipboardImageResolution) {
+ if (!fetchAttempted) {
+ toast.warning(
+ `Pasted design includes ${imageCount(total)} that cannot be loaded in the web app. Use the desktop app to include ${total === 1 ? 'it' : 'them'}.`
+ )
+ return
+ }
+
+ toast.error(
+ `Failed to fetch ${imageCount(missing)} from Figma. Check that the source file is accessible and try again.`
+ )
+}
+
+export function bindClipboardNotifications(editor: Editor) {
+ return editor.onEditorEvent('clipboard:images-missing', notifyClipboardImageResolution)
+}
diff --git a/src/app/editor/session/create.ts b/src/app/editor/session/create.ts
index 90177381b..9560691f3 100644
--- a/src/app/editor/session/create.ts
+++ b/src/app/editor/session/create.ts
@@ -9,6 +9,8 @@ import {
setActiveEditorStore,
useEditorStore
} from '@/app/editor/active-store'
+import { resolveFigmaClipboardImages } from '@/app/editor/clipboard/figma-images'
+import { bindClipboardNotifications } from '@/app/editor/clipboard/notifications'
import { loadFont } from '@/app/editor/fonts'
import {
createEditorComputedRefs,
@@ -16,6 +18,7 @@ import {
defineEditorStoreAccessors
} from '@/app/editor/session/modules'
import { createInitialAppEditorState, type AppEditorState } from '@/app/editor/session/types'
+import { isTauri } from '@/app/tauri/env'
export { EDITOR_TOOLS as TOOLS, TOOL_SHORTCUTS } from '@open-pencil/core/editor'
export type { EditorToolDef as ToolDef, Tool } from '@open-pencil/core/editor'
@@ -30,6 +33,7 @@ export function createEditorStore(initialGraph?: SceneGraph) {
graph,
state,
loadFont,
+ resolveFigmaClipboardImages: isTauri() ? resolveFigmaClipboardImages : undefined,
skipInitialGraphSetup: !!initialGraph,
getViewportSize: () =>
viewportSize.width > 0 && viewportSize.height > 0
@@ -37,6 +41,7 @@ export function createEditorStore(initialGraph?: SceneGraph) {
: { width: window.innerWidth, height: window.innerHeight }
})
const io = new IORegistry(BUILTIN_IO_FORMATS)
+ bindClipboardNotifications(editor)
if (initialGraph) {
editor.subscribeToGraph()
diff --git a/tests/engine/app/clipboard/figma-images.test.ts b/tests/engine/app/clipboard/figma-images.test.ts
new file mode 100644
index 000000000..4a19ab064
--- /dev/null
+++ b/tests/engine/app/clipboard/figma-images.test.ts
@@ -0,0 +1,83 @@
+import { describe, expect, spyOn, test } from 'bun:test'
+
+import { resolveFigmaClipboardImages } from '@/app/editor/clipboard/figma-images'
+
+import { expectDefined } from '#tests/helpers/assert'
+
+async function sha1Hex(bytes: Uint8Array) {
+ const digest = await crypto.subtle.digest('SHA-1', Uint8Array.from(bytes))
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('')
+}
+
+describe('resolveFigmaClipboardImages', () => {
+ test('resolves signed URLs, verifies bytes, and deduplicates hashes', async () => {
+ const bytes = new Uint8Array([1, 2, 3])
+ const hash = await sha1Hex(bytes)
+ const requests: Array<{ url: string; init?: RequestInit }> = []
+ const fetcher = async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input)
+ requests.push({ url, init })
+ if (url.includes('/image/batch')) {
+ return Response.json({
+ error: false,
+ status: 200,
+ meta: { s3_urls: { [hash]: 'https://s3-alpha-sig.figma.com/image' } }
+ })
+ }
+ return new Response(Uint8Array.from(bytes))
+ }
+
+ const images = await resolveFigmaClipboardImages('file/key', [hash, hash], fetcher)
+
+ expect(images.get(hash)).toEqual(bytes)
+ expect(requests.map(({ url }) => url)).toEqual([
+ 'https://www.figma.com/file/file%2Fkey/image/batch',
+ 'https://s3-alpha-sig.figma.com/image'
+ ])
+ const body = expectDefined(requests[0].init?.body, 'batch request body')
+ expect(JSON.parse(String(body))).toEqual({
+ sha1s: [hash],
+ needs_compressed_textures: false
+ })
+ })
+
+ test('drops a response whose bytes do not match the Figma hash', async () => {
+ const warn = spyOn(console, 'warn').mockImplementation(() => undefined)
+ const fetcher = async (input: RequestInfo | URL) => {
+ if (String(input).includes('/image/batch')) {
+ return Response.json({
+ error: false,
+ status: 200,
+ meta: {
+ s3_urls: {
+ '1111111111111111111111111111111111111111': 'https://s3-alpha-sig.figma.com/image'
+ }
+ }
+ })
+ }
+ return new Response(new Uint8Array([9, 9, 9]))
+ }
+
+ const images = await resolveFigmaClipboardImages(
+ 'file-key',
+ ['1111111111111111111111111111111111111111'],
+ fetcher
+ )
+
+ expect(images.size).toBe(0)
+ expect(warn).toHaveBeenCalledTimes(1)
+ warn.mockRestore()
+ })
+
+ test('rejects failed and malformed batch responses', async () => {
+ await expect(
+ resolveFigmaClipboardImages('file-key', ['hash'], async () =>
+ Response.json({}, { status: 503 })
+ )
+ ).rejects.toThrow('status 503')
+
+ await expect(
+ resolveFigmaClipboardImages('file-key', ['hash'], async () => Response.json({ error: true }))
+ ).rejects.toThrow('invalid image response')
+ })
+})
diff --git a/tests/engine/app/clipboard/notifications.test.ts b/tests/engine/app/clipboard/notifications.test.ts
new file mode 100644
index 000000000..bc16a61b4
--- /dev/null
+++ b/tests/engine/app/clipboard/notifications.test.ts
@@ -0,0 +1,32 @@
+import { afterEach, describe, expect, test } from 'bun:test'
+
+import { notifyClipboardImageResolution } from '@/app/editor/clipboard/notifications'
+import { toast } from '@/app/shell/ui'
+
+afterEach(() => {
+ toast.toasts.value = []
+})
+
+describe('clipboard image notifications', () => {
+ test('warns web users when pasted images cannot be fetched', () => {
+ notifyClipboardImageResolution({ total: 2, missing: 2, fetchAttempted: false })
+
+ expect(toast.toasts.value).toHaveLength(1)
+ expect(toast.toasts.value[0]).toMatchObject({
+ variant: 'warning',
+ message:
+ 'Pasted design includes 2 images that cannot be loaded in the web app. Use the desktop app to include them.'
+ })
+ })
+
+ test('shows an actionable desktop error for partial failures', () => {
+ notifyClipboardImageResolution({ total: 3, missing: 1, fetchAttempted: true })
+
+ expect(toast.toasts.value).toHaveLength(1)
+ expect(toast.toasts.value[0]).toMatchObject({
+ variant: 'error',
+ message:
+ 'Failed to fetch 1 image from Figma. Check that the source file is accessible and try again.'
+ })
+ })
+})
diff --git a/tests/engine/editor/clipboard/figma-images.test.ts b/tests/engine/editor/clipboard/figma-images.test.ts
new file mode 100644
index 000000000..d5a2921b5
--- /dev/null
+++ b/tests/engine/editor/clipboard/figma-images.test.ts
@@ -0,0 +1,97 @@
+import { beforeAll, describe, expect, test } from 'bun:test'
+
+import { initCodec } from '@open-pencil/core'
+import { buildFigmaClipboardHTML } from '@open-pencil/core/clipboard'
+import { createEditor } from '@open-pencil/core/editor'
+import type { ClipboardImageResolution } from '@open-pencil/core/editor'
+
+import { expectDefined } from '#tests/helpers/assert'
+
+const IMAGE_HASH_A = '1111111111111111111111111111111111111111'
+const IMAGE_HASH_B = '2222222222222222222222222222222222222222'
+
+async function imageClipboardHtml(hashes: string[]) {
+ const source = createEditor()
+ const frame = source.graph.createNode('FRAME', source.state.currentPageId, {
+ name: 'Images',
+ width: 200,
+ height: 200
+ })
+ for (const [index, hash] of hashes.entries()) {
+ source.graph.createNode('RECTANGLE', frame.id, {
+ name: `Image ${index}`,
+ x: index * 20,
+ width: 20,
+ height: 20,
+ fills: [
+ {
+ type: 'IMAGE',
+ imageHash: hash,
+ imageScaleMode: 'FILL',
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ opacity: 1,
+ visible: true
+ }
+ ]
+ })
+ }
+ return expectDefined(await buildFigmaClipboardHTML([frame], source.graph), 'Figma clipboard HTML')
+}
+
+describe('Figma clipboard images', () => {
+ beforeAll(async () => {
+ await initCodec()
+ })
+
+ test('resolves and stores missing images before completing paste', async () => {
+ const html = await imageClipboardHtml([IMAGE_HASH_A, IMAGE_HASH_A])
+ const imageBytes = new Uint8Array([1, 2, 3])
+ const calls: Array<{ fileKey: string; hashes: string[] }> = []
+ const resolutions: ClipboardImageResolution[] = []
+ const editor = createEditor({
+ resolveFigmaClipboardImages: async (fileKey, hashes) => {
+ calls.push({ fileKey, hashes })
+ return new Map([[IMAGE_HASH_A, imageBytes]])
+ }
+ })
+ editor.onEditorEvent('clipboard:images-missing', (resolution) => {
+ resolutions.push(resolution)
+ })
+
+ await editor.pasteFromHTML(html)
+
+ expect(calls).toEqual([{ fileKey: 'openpencil', hashes: [IMAGE_HASH_A] }])
+ expect(editor.graph.images.get(IMAGE_HASH_A)).toEqual(imageBytes)
+ expect(resolutions).toEqual([])
+ })
+
+ test('reports images that cannot be fetched without a resolver', async () => {
+ const html = await imageClipboardHtml([IMAGE_HASH_A])
+ const resolutions: ClipboardImageResolution[] = []
+ const editor = createEditor()
+ editor.onEditorEvent('clipboard:images-missing', (resolution) => {
+ resolutions.push(resolution)
+ })
+
+ await editor.pasteFromHTML(html)
+
+ expect(resolutions).toEqual([{ total: 1, missing: 1, fetchAttempted: false }])
+ })
+
+ test('stores partial results and reports remaining images', async () => {
+ const html = await imageClipboardHtml([IMAGE_HASH_A, IMAGE_HASH_B])
+ const editor = createEditor({
+ resolveFigmaClipboardImages: async () => new Map([[IMAGE_HASH_A, new Uint8Array([4, 5, 6])]])
+ })
+ const resolutions: ClipboardImageResolution[] = []
+ editor.onEditorEvent('clipboard:images-missing', (resolution) => {
+ resolutions.push(resolution)
+ })
+
+ await editor.pasteFromHTML(html)
+
+ expect(editor.graph.images.has(IMAGE_HASH_A)).toBe(true)
+ expect(editor.graph.images.has(IMAGE_HASH_B)).toBe(false)
+ expect(resolutions).toEqual([{ total: 2, missing: 1, fetchAttempted: true }])
+ })
+})