Skip to content

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

feat: open documents dropped onto the window (#906)

Danila Poyarkov7c4d9aa20d86
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9d82626f8..441919467 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -25,6 +25,7 @@
### Added
+- Open a `.fig`, `.pen`, or other supported document by dragging it onto the window, where it opens in a new tab as File → Open does. Images and SVG files dropped on the canvas are still placed, and other files report that they can't be opened instead of being ignored.
- Pass an ID generator to `new SceneGraph()` from `@open-pencil/scene-graph` to choose the IDs of the nodes, variables, collections, and modes the graph creates, including modes added later with `createMode`; generated IDs skip any node, variable, collection, or mode ID already in the graph, and an exhausted generator throws instead of hanging. `createComponentPropertyId` gives new component properties the `prop:` IDs the editor, plugin API, and design JSX share.
- Diagnose failures from Settings → Diagnostics. Uncaught errors, unhandled rejections, component errors, failed AI chats, and AI tool calls that broke inside OpenPencil are recorded with their message and stack, and other failed tool calls as warnings. Messages and stacks are scrubbed of URL queries and credentials, API keys and tokens, email addresses, and home folder names, and provider errors keep no message. Each event has a specific label, such as *Tool: render · 162 ms* or *Error: TypeError*, expands to its details, and can be filtered by level and category and paged; copied diagnostics include the app version and browser.
- Import `resolvePasteTarget` from `@open-pencil/core/editor` to place ordinary pasted or dropped content in an embedding app in the same container the editor would choose. It takes the editor `createEditor` returns. Replacement paste is not covered: it inserts into the selected target's parent.
diff --git a/packages/docs/user-guide/exporting.md b/packages/docs/user-guide/exporting.md
index 753298927..b504c6592 100644
--- a/packages/docs/user-guide/exporting.md
+++ b/packages/docs/user-guide/exporting.md
@@ -56,6 +56,8 @@ OpenPencil uses the .fig format for full documents — the same binary format as
A file picker dialog opens, filtered for `.fig` and `.pen` files. On the desktop app, this uses the native OS dialog.
+You can also drag a `.fig`, `.pen`, or other supported document onto the window; it opens in a new tab. Images and SVG files dropped on the canvas are placed in the document instead, and any other file reports that it can't be opened.
+
### Saving Files
| Action | Mac | Windows / Linux |
diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.ts
index d283971d7..7a083ca2d 100644
--- a/packages/vue/src/index.ts
+++ b/packages/vue/src/index.ts
@@ -28,7 +28,11 @@ export type { CanvasIssueMarkerOptions } from '#vue/canvas/issues/use'
export type { CanvasLabelEdit, CanvasLabelKind } from '#vue/canvas/labels/edit'
export { useCanvasVirtualReference } from '#vue/canvas/overlays/useCanvasVirtualReference'
export { useTextEdit } from '#vue/canvas/text-edit/use'
-export { useCanvasDrop, extractImageFilesFromClipboard } from '#vue/canvas/drop/use'
+export {
+ useCanvasDrop,
+ extractImageFilesFromClipboard,
+ filterCanvasFiles
+} from '#vue/canvas/drop/use'
/** Low-level selection, graph, and derived-state helpers. */
export { useNodeProps, MIXED } from '#vue/controls/node-props/use'
diff --git a/src/app/shell/document-drop.ts b/src/app/shell/document-drop.ts
new file mode 100644
index 000000000..e8a694582
--- /dev/null
+++ b/src/app/shell/document-drop.ts
@@ -0,0 +1,68 @@
+import { useEventListener } from '@vueuse/core'
+
+import { filterCanvasFiles } from '@open-pencil/vue'
+
+import { openDesignFile, openDesignFileBatch } from '@/app/shell/menu/files'
+
+interface DroppedFile {
+ file: File
+ handle: Promise<FileSystemFileHandle | null>
+}
+
+function hasFiles(event: DragEvent): boolean {
+ return event.dataTransfer?.types.includes('Files') ?? false
+}
+
+/** A file handle lets the tab save back to the dropped file; only Chromium provides one. */
+async function fileHandle(item: DataTransferItem): Promise<FileSystemFileHandle | null> {
+ if (!item.getAsFileSystemHandle) return null
+ try {
+ const handle = await item.getAsFileSystemHandle()
+ return handle instanceof FileSystemFileHandle ? handle : null
+ } catch {
+ return null
+ }
+}
+
+/**
+ * The dropped files and their handles. The drag data is only readable while the drop event
+ * runs, so every file and handle request is taken before anything awaits.
+ */
+function droppedFiles(transfer: DataTransfer): DroppedFile[] {
+ const dropped: DroppedFile[] = []
+ for (const item of transfer.items) {
+ if (item.kind !== 'file') continue
+ const file = item.getAsFile()
+ if (file) dropped.push({ file, handle: fileHandle(item) })
+ }
+ return dropped
+}
+
+/**
+ * Opens documents dropped anywhere on the window in new tabs, as File → Open does. Images and
+ * SVG files stay with the canvas, which places them; any other file reports that it cannot be
+ * opened instead of being ignored.
+ */
+export function useDocumentDrop() {
+ useEventListener(window, 'dragover', (event: DragEvent) => {
+ if (!hasFiles(event)) return
+ event.preventDefault()
+ if (event.dataTransfer) event.dataTransfer.dropEffect = 'copy'
+ })
+
+ useEventListener(window, 'drop', (event: DragEvent) => {
+ if (!event.dataTransfer || !hasFiles(event)) return
+ // Without this the browser would navigate away to show the file.
+ event.preventDefault()
+ // Classify each file itself: `getAsFile()` may return a new `File`, not one from `files`.
+ const documents = droppedFiles(event.dataTransfer).filter(
+ ({ file }) => filterCanvasFiles([file]).length === 0
+ )
+ if (documents.length === 0) return
+ void openDesignFileBatch(
+ documents,
+ ({ file }) => file.name,
+ async ({ file, handle }) => openDesignFile(file, (await handle) ?? undefined)
+ )
+ })
+}
diff --git a/src/app/shell/menu/files.ts b/src/app/shell/menu/files.ts
index de16a151a..0266272c1 100644
--- a/src/app/shell/menu/files.ts
+++ b/src/app/shell/menu/files.ts
@@ -38,13 +38,19 @@ fileDialog.onChange((files) => {
void openDesignFileBatch(
files,
(file) => file.name,
- (file) => {
- assertSupportedDesignFile(file.name)
- return openFileInNewTab(file)
- }
+ (file) => openDesignFile(file)
)
})
+/**
+ * Opens a picked or dropped document in a new tab, rejecting formats OpenPencil cannot read.
+ * A file system handle, when the browser provides one, lets the tab save back to the file.
+ */
+export function openDesignFile(file: File, handle?: FileSystemFileHandle): Promise<void> {
+ assertSupportedDesignFile(file.name)
+ return openFileInNewTab(file, handle)
+}
+
if (IS_BROWSER && 'window' in globalThis) {
setOpenPencilOpenFileHandler(async (path: string) => {
await openBrowserFileFromURL(resolveBrowserFileURL(path))
diff --git a/src/global.d.ts b/src/global.d.ts
index ab6c59985..b61bebdc5 100644
--- a/src/global.d.ts
+++ b/src/global.d.ts
@@ -14,6 +14,11 @@ declare global {
suggestedName?: string
}
+ interface DataTransferItem {
+ /** File System Access drag support; Chromium only. */
+ getAsFileSystemHandle?(): Promise<FileSystemHandle | null>
+ }
+
interface Window {
openPencil?: OpenPencilWindowAPI
showOpenFilePicker?(options?: FilePickerOptions): Promise<FileSystemFileHandle[]>
diff --git a/src/views/WorkspaceView.vue b/src/views/WorkspaceView.vue
index 04b15a951..355bcafbf 100644
--- a/src/views/WorkspaceView.vue
+++ b/src/views/WorkspaceView.vue
@@ -15,6 +15,7 @@ import { openWebLinkFromLocation, withoutWebLinkParams } from '@/app/document/io
import { focusNodesByName } from '@/app/editor/selection/focus'
import { notificationMessages } from '@/app/i18n/notifications'
import { appRuntimeConfig } from '@/app/runtime/config'
+import { useDocumentDrop } from '@/app/shell/document-drop'
import { useKeyboard } from '@/app/shell/keyboard/use'
import { useEditorMenu } from '@/app/shell/menu/use'
import { toast } from '@/app/shell/ui'
@@ -56,6 +57,7 @@ if (createdInitialTab && route.meta.demo && !appRuntimeConfig.test) {
useHead({ title: route.meta.demo ? 'Demo' : undefined })
useKeyboard()
useEditorMenu()
+useDocumentDrop()
const collab = useCollab(getActiveStore)
provide(COLLAB_KEY, collab)
diff --git a/tests/e2e/app/document-drop.spec.ts b/tests/e2e/app/document-drop.spec.ts
new file mode 100644
index 000000000..1a88c816c
--- /dev/null
+++ b/tests/e2e/app/document-drop.spec.ts
@@ -0,0 +1,64 @@
+import { readFile } from 'node:fs/promises'
+
+import { expect, test, type Page } from '@playwright/test'
+
+import { CanvasHelper } from '#tests/helpers/canvas'
+
+/** Drops files on the canvas the way a drag from the desktop delivers them. */
+async function dropOnCanvas(page: Page, files: Array<{ name: string; bytes: number[] }>) {
+ await page.getByTestId('canvas-element').evaluate((canvas, dropped) => {
+ const bounds = canvas.getBoundingClientRect()
+ const transfer = new DataTransfer()
+ for (const { name, bytes } of dropped)
+ transfer.items.add(new File([new Uint8Array(bytes)], name))
+ const options = {
+ bubbles: true,
+ cancelable: true,
+ clientX: bounds.left + 200,
+ clientY: bounds.top + 200,
+ dataTransfer: transfer
+ }
+ canvas.dispatchEvent(new DragEvent('dragover', options))
+ canvas.dispatchEvent(new DragEvent('drop', options))
+ }, files)
+}
+
+test('a document dropped on the canvas opens in a new tab', async ({ page }) => {
+ await page.goto('/?test')
+ await new CanvasHelper(page).waitForInit()
+ const tabs = page.getByRole('tablist').filter({ has: page.getByTestId('tabbar-tab') })
+
+ const bytes = [...(await readFile('tests/fixtures/circle-text.fig'))]
+ await dropOnCanvas(page, [{ name: 'circle-text.fig', bytes }])
+
+ await expect(tabs.getByRole('tab').last()).toContainText('circle-text')
+ await expect(tabs.getByRole('tab').last()).toHaveAttribute('aria-selected', 'true')
+})
+
+test('a dropped file that is neither a document nor an image reports that it cannot open', async ({
+ page
+}) => {
+ await page.goto('/?test')
+ await new CanvasHelper(page).waitForInit()
+ const tabs = page.getByRole('tablist').filter({ has: page.getByTestId('tabbar-tab') })
+
+ await dropOnCanvas(page, [{ name: 'notes.txt', bytes: [...new TextEncoder().encode('hello')] }])
+
+ await expect(page.getByText('Could not open “notes.txt”', { exact: false })).toBeVisible()
+ await expect(tabs.getByRole('tab')).toHaveCount(1)
+})
+
+test('an SVG dropped on the canvas is placed, not opened as a document', async ({ page }) => {
+ await page.goto('/?test')
+ await new CanvasHelper(page).waitForInit()
+ const tabs = page.getByRole('tablist').filter({ has: page.getByTestId('tabbar-tab') })
+ const tabName = (await tabs.getByRole('tab').first().textContent()) ?? ''
+ const svg = '<svg width="20" height="20"><rect width="20" height="20" fill="#f00"/></svg>'
+
+ await dropOnCanvas(page, [{ name: 'mark.svg', bytes: [...new TextEncoder().encode(svg)] }])
+
+ await expect(page.getByTestId('layers-item').filter({ hasText: 'mark' })).toHaveCount(1)
+ await expect(page.getByText('Could not open', { exact: false })).toHaveCount(0)
+ await expect(tabs.getByRole('tab')).toHaveCount(1)
+ await expect(tabs.getByRole('tab').first()).toHaveText(tabName)
+})