diff --git a/apps/docs/electron.vite.config.ts b/apps/docs/electron.vite.config.ts index d2c9041..a7d0713 100644 --- a/apps/docs/electron.vite.config.ts +++ b/apps/docs/electron.vite.config.ts @@ -21,7 +21,11 @@ export default defineConfig({ ], resolve: { alias: localAlias }, }, - preload: {}, + preload: { + // Sandboxed preload scripts cannot require arbitrary npm packages at + // runtime, so the drop-open bridge must be bundled, not externalized. + plugins: [externalizeDepsPlugin({ exclude: ['@genoffice/electron-utils'] })], + }, renderer: { plugins: [react()], resolve: { alias: localAlias }, diff --git a/apps/docs/src/preload/index.ts b/apps/docs/src/preload/index.ts index dc4fbda..0f1076e 100644 --- a/apps/docs/src/preload/index.ts +++ b/apps/docs/src/preload/index.ts @@ -10,6 +10,7 @@ import type { UiTheme, } from '../shared/ipc' import type { ProjectApi } from '@genoffice/project-store' +import { installDropOpenBridge } from '@genoffice/electron-utils/drop-open' const api: DesktopApi = { getLanguage: () => ipcRenderer.invoke('app:get-language'), @@ -167,3 +168,6 @@ const projectApi: ProjectApi = { contextBridge.exposeInMainWorld('desktop', api) contextBridge.exposeInMainWorld('projectApi', projectApi) + +// open documents dragged from the OS onto this tab as a new shell tab +installDropOpenBridge() diff --git a/apps/markdown/electron.vite.config.ts b/apps/markdown/electron.vite.config.ts index b409449..c3f0a10 100644 --- a/apps/markdown/electron.vite.config.ts +++ b/apps/markdown/electron.vite.config.ts @@ -24,7 +24,8 @@ export default defineConfig({ plugins: [externalizeDepsPlugin({ exclude: ['@genoffice/i18n', '@genoffice/electron-utils'] })], }, preload: { - plugins: [externalizeDepsPlugin({ exclude: ['@genoffice/i18n'] })], + // same bundling requirement as main (see comment above) + plugins: [externalizeDepsPlugin({ exclude: ['@genoffice/i18n', '@genoffice/electron-utils'] })], }, renderer: { plugins: [react()], diff --git a/apps/markdown/src/preload/index.ts b/apps/markdown/src/preload/index.ts index 5ab2c7a..75e968b 100644 --- a/apps/markdown/src/preload/index.ts +++ b/apps/markdown/src/preload/index.ts @@ -2,6 +2,7 @@ import { contextBridge, ipcRenderer } from 'electron' import type { Lang } from '@genoffice/i18n' import type { AiStreamChunk } from '@genoffice/ai-provider' import type { ProjectApi } from '@genoffice/project-store' +import { installDropOpenBridge } from '@genoffice/electron-utils/drop-open' import { AI_CHANNELS, MARKDOWN_CHANNELS } from '../shared/ipc' import type { ExportFormat, MarkdownApi, SaveMode, UiTheme } from '../shared/ipc' @@ -84,3 +85,6 @@ const projectApi: Pick ipcRenderer.invoke('app:get-language'), @@ -591,6 +592,9 @@ const projectApi: ProjectApi = { } contextBridge.exposeInMainWorld('projectApi', projectApi) +// open documents dragged from the OS onto this tab as a new shell tab +installDropOpenBridge() + function parseWorkbookFile(input: unknown): WorkbookFile { if (!isRecord(input)) throw new Error('Invalid workbook response.') const { diff --git a/apps/shell/src/main/dropped-files.ts b/apps/shell/src/main/dropped-files.ts new file mode 100644 index 0000000..e315c6b --- /dev/null +++ b/apps/shell/src/main/dropped-files.ts @@ -0,0 +1,28 @@ +/// Payload handling for OS file drops (installDropOpenBridge in preloads). +/// Kept in its own module so the decision logic is unit-testable without +/// booting the whole shell main process. +import { partitionDropPayload } from '@genoffice/electron-utils' + +export interface DroppedFilesDeps { + /** the normal File > Open pipeline; false = the path didn't open */ + openDocumentPath: (path: string) => boolean + /** bring the shell window forward (the drop may land in a detached editor) */ + revealShellWindow: () => void + /** the shared warning box; receives a localized message */ + showWarning: (message: string) => void + /** localized template for one-or-more unsupported extensions */ + unsupportedMessage: (exts: string[]) => string +} + +/** + * Open each openable path (last drop wins activation), reveal the shell if + * anything opened, and surface one combined warning for known-but-unsupported + * formats instead of letting them disappear silently. + */ +export function handleDroppedFiles(raw: unknown, deps: DroppedFilesDeps): void { + const { supported, unsupportedExts } = partitionDropPayload(raw) + let opened = false + for (const path of supported) opened = deps.openDocumentPath(path) || opened + if (opened) deps.revealShellWindow() + if (unsupportedExts.length > 0) deps.showWarning(deps.unsupportedMessage(unsupportedExts)) +} diff --git a/apps/shell/src/main/index.ts b/apps/shell/src/main/index.ts index d9a52b2..1c59a00 100644 --- a/apps/shell/src/main/index.ts +++ b/apps/shell/src/main/index.ts @@ -37,6 +37,7 @@ import menuHomeIcon2x from './assets/menu-home@2x.png?asset' import { createI18n, isLang, normalizeLang, setUiLang, type Lang } from '@genoffice/i18n' import { DEFAULT_SAVE_DIR_KEY, + DROP_OPEN_CHANNEL, GITHUB_REPO_URL, appMenuLabels, contextMenuLabels, @@ -76,6 +77,7 @@ import { readCloudProjectsStore, syncCloudProjects, } from './cloud-projects' +import { handleDroppedFiles } from './dropped-files' import { ProjectStore } from '@genoffice/project-store' import { ensureGenofficeLogin, @@ -2579,7 +2581,12 @@ function unsupportedFileIn(argv: string[]): string | null { function notifyUnsupportedFile(filePath: string): void { const ext = extname(filePath).slice(1).toLowerCase() || basename(filePath) - const options = { type: 'warning' as const, message: tm('errUnsupportedExt', { ext }) } + showAppWarning(tm('errUnsupportedExt', { ext })) +} + +/** shell-hosted warning box; focused when a shell window exists, standalone otherwise */ +function showAppWarning(message: string): void { + const options = { type: 'warning' as const, message } if (shellWindow) { shellWindow.show() shellWindow.focus() @@ -2589,6 +2596,22 @@ function notifyUnsupportedFile(filePath: string): void { } } +/** + * Files dropped from the OS into any renderer arrive via installDropOpenBridge + * and route through the normal File > Open pipeline; detached editor windows + * can host the drop target, so the shell must reveal itself after opening. + */ +function registerDroppedFilesIpc(): void { + ipcMain.on(DROP_OPEN_CHANNEL, (_event, raw: unknown) => + handleDroppedFiles(raw, { + openDocumentPath, + revealShellWindow, + showWarning: showAppWarning, + unsupportedMessage: (exts) => tm('errUnsupportedExt', { ext: exts.join(', ') }), + }), + ) +} + /** the single router: extension decides which module owns the file; false = nothing opened */ function openDocumentPath(filePath: string): boolean { const opened = routeDocumentPath(filePath) @@ -4127,6 +4150,7 @@ registerProjectIpc() registerDocsIpc() registerHomeIpc() registerTabsIpc() +registerDroppedFilesIpc() // sheets' project:resolveChat goes through the handler registered by docs-main; the sessionId reverse lookup hooks in here setSessionPathResolver(resolveSheetsSessionPath) diff --git a/apps/shell/src/preload/index.ts b/apps/shell/src/preload/index.ts index 022ae48..695efd5 100644 --- a/apps/shell/src/preload/index.ts +++ b/apps/shell/src/preload/index.ts @@ -2,6 +2,7 @@ import { contextBridge, ipcRenderer } from 'electron' import type { IpcRendererEvent } from 'electron' import { AI_PROVIDERS, getProviderAdapter } from '@genoffice/ai-provider' import type { AiSettings } from '@genoffice/ai-provider' +import { installDropOpenBridge } from '@genoffice/electron-utils/drop-open' import type { AccountLoginEvent, AccountStatus, @@ -357,3 +358,6 @@ const tabsApi: TabsApi = { } contextBridge.exposeInMainWorld('aiOfficeTabs', tabsApi) + +// open documents dragged from the OS anywhere over Home or the tab strip +installDropOpenBridge() diff --git a/apps/shell/src/renderer/src/Home.tsx b/apps/shell/src/renderer/src/Home.tsx index c6872ab..7c9c450 100644 --- a/apps/shell/src/renderer/src/Home.tsx +++ b/apps/shell/src/renderer/src/Home.tsx @@ -1048,6 +1048,70 @@ function CloudProjectsView() { ) } +// ── Drop-to-open overlay ──────────────────────────────── + +/** + * Full-window affordance while OS files hover over Home. Purely visual — the + * actual open is owned by the preload drop bridge (installDropOpenBridge), so + * this overlay stays pointer-events:none and never handles events itself. + * `dragover` fires continuously while hovering and stops on leave/cancel, so + * a short debounce is enough to show/hide without counting enter/leave pairs. + */ +function DropToOpenOverlay(): ReactElement | null { + const [visible, setVisible] = useState(false) + useEffect(() => { + let hideTimer: ReturnType | undefined + const hasFiles = (ev: DragEvent): boolean => ev.dataTransfer?.types.includes('Files') ?? false + // NB: the preload drop bridge also listens here and cancels file drags, so + // defaultPrevented can't discriminate anything at this layer — only zones + // that stopPropagation (none on Home) would keep us out entirely. + const onDragOver = (ev: DragEvent) => { + if (!hasFiles(ev)) return + clearTimeout(hideTimer) + setVisible(true) + hideTimer = setTimeout(() => setVisible(false), 120) + } + const onHide = () => { + clearTimeout(hideTimer) + setVisible(false) + } + window.addEventListener('dragover', onDragOver) + window.addEventListener('drop', onHide) + window.addEventListener('blur', onHide) + return () => { + clearTimeout(hideTimer) + window.removeEventListener('dragover', onDragOver) + window.removeEventListener('drop', onHide) + window.removeEventListener('blur', onHide) + } + }, []) + const { t } = useI18n() + if (!visible) return null + return ( + + ) +} + // ── Main component ────────────────────────────────────── export function Home() { @@ -2177,6 +2241,8 @@ export function Home() { )} + + ) } diff --git a/apps/shell/src/renderer/src/home.css b/apps/shell/src/renderer/src/home.css index d26aa33..a89ae5a 100644 --- a/apps/shell/src/renderer/src/home.css +++ b/apps/shell/src/renderer/src/home.css @@ -1777,6 +1777,52 @@ body.vib .home { transform: rotate(360deg); } } + +/* Drag-over affordance while OS files hover anywhere over the window (the + open itself is handled by the preload drop bridge, not this overlay) */ +.home-drop-overlay { + position: fixed; + inset: 0; + z-index: 300; /* above modals (100): a drag in progress always leads */ + display: flex; + align-items: center; + justify-content: center; + background: var(--color-bg-overlay); + /* never intercepts events — the drop must land on the page underneath */ + pointer-events: none; +} + +.home-drop-card { + display: flex; + flex-direction: column; + align-items: center; + gap: 10px; + padding: 36px 56px; + background: var(--surface); + border: 2px dashed var(--accent); + border-radius: var(--radius-16); + box-shadow: var(--shadow-modal-strong); + color: var(--accent); + animation: menu-in 0.12s ease; +} + +.home-drop-card h2 { + margin: 0; + color: var(--text); + font-size: 17px; + font-weight: 600; +} + +.home-drop-card p { + margin: 0; + color: var(--text-muted); + font-size: 12px; + max-width: 360px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + /* Motion accessibility: suppress all animation for users who opt out */ @media (prefers-reduced-motion: reduce) { *, diff --git a/apps/shell/src/renderer/src/strings.ts b/apps/shell/src/renderer/src/strings.ts index 7a17e7d..63a0fea 100644 --- a/apps/shell/src/renderer/src/strings.ts +++ b/apps/shell/src/renderer/src/strings.ts @@ -38,6 +38,7 @@ export const strings = { newMarkdown: 'AI Markdown', newPdf: 'AI PDF', openLocal: '打开本地文件', + dropToOpenTitle: '松开以打开文件', greetMorning: '早上好', greetAfternoon: '下午好', greetEvening: '晚上好', @@ -233,6 +234,7 @@ export const strings = { newMarkdown: 'AI Markdown', newPdf: 'AI PDF', openLocal: 'Open Local File', + dropToOpenTitle: 'Drop to open', greetMorning: 'Good morning', greetAfternoon: 'Good afternoon', greetEvening: 'Good evening', @@ -430,6 +432,7 @@ export const strings = { newMarkdown: 'AI Markdown', newPdf: 'AI PDF', openLocal: 'ローカルファイルを開く', + dropToOpenTitle: 'ドロップして開く', greetMorning: 'おはようございます', greetAfternoon: 'こんにちは', greetEvening: 'こんばんは', @@ -638,6 +641,7 @@ export const strings = { newMarkdown: 'AI Markdown', newPdf: 'AI PDF', openLocal: '로컬 파일 열기', + dropToOpenTitle: '놓아서 파일 열기', greetMorning: '좋은 아침이에요', greetAfternoon: '안녕하세요', greetEvening: '좋은 저녁이에요', @@ -844,6 +848,7 @@ export const strings = { newMarkdown: 'AI Markdown', newPdf: 'AI PDF', openLocal: 'Ouvrir un fichier local', + dropToOpenTitle: 'Déposer pour ouvrir', greetMorning: 'Bonjour', greetAfternoon: 'Bonjour', greetEvening: 'Bonsoir', @@ -1053,6 +1058,7 @@ export const strings = { newMarkdown: 'AI Markdown', newPdf: 'AI PDF', openLocal: 'Lokale Datei öffnen', + dropToOpenTitle: 'Zum Öffnen ablegen', greetMorning: 'Guten Morgen', greetAfternoon: 'Guten Tag', greetEvening: 'Guten Abend', @@ -1264,6 +1270,7 @@ export const strings = { newMarkdown: 'AI Markdown', newPdf: 'AI PDF', openLocal: 'Abrir archivo local', + dropToOpenTitle: 'Suelta para abrir', greetMorning: 'Buenos días', greetAfternoon: 'Buenas tardes', greetEvening: 'Buenas noches', @@ -1472,6 +1479,7 @@ export const strings = { newMarkdown: 'AI Markdown', newPdf: 'AI PDF', openLocal: 'เปิดไฟล์ในเครื่อง', + dropToOpenTitle: 'วางเพื่อเปิดไฟล์', greetMorning: 'สวัสดีตอนเช้า', greetAfternoon: 'สวัสดีตอนบ่าย', greetEvening: 'สวัสดีตอนเย็น', @@ -1676,6 +1684,7 @@ export const strings = { newMarkdown: 'AI Markdown', newPdf: 'AI PDF', openLocal: 'Buka File Lokal', + dropToOpenTitle: 'Lepaskan untuk membuka', greetMorning: 'Selamat pagi', greetAfternoon: 'Selamat siang', greetEvening: 'Selamat malam', @@ -1881,6 +1890,7 @@ export const strings = { newMarkdown: 'AI Markdown', newPdf: 'AI PDF', openLocal: 'Открыть локальный файл', + dropToOpenTitle: 'Отпустите, чтобы открыть', greetMorning: 'Доброе утро', greetAfternoon: 'Добрый день', greetEvening: 'Добрый вечер', @@ -2087,6 +2097,7 @@ export const strings = { newMarkdown: 'AI Markdown', newPdf: 'AI PDF', openLocal: 'فتح ملف محلي', + dropToOpenTitle: 'أفلت للفتح', greetMorning: 'صباح الخير', greetAfternoon: 'مساء الخير', greetEvening: 'مساء الخير', @@ -2288,6 +2299,7 @@ export const strings = { newMarkdown: 'AI Markdown', newPdf: 'AI PDF', openLocal: 'Abrir arquivo local', + dropToOpenTitle: 'Solte para abrir', greetMorning: 'Bom dia', greetAfternoon: 'Boa tarde', greetEvening: 'Boa noite', @@ -2485,6 +2497,7 @@ export const strings = { newMarkdown: 'AI Markdown', newPdf: 'AI PDF', openLocal: 'Apri file locale', + dropToOpenTitle: 'Rilascia per aprire', greetMorning: 'Buongiorno', greetAfternoon: 'Buon pomeriggio', greetEvening: 'Buonasera', @@ -2681,6 +2694,7 @@ export const strings = { newMarkdown: 'AI Markdown', newPdf: 'AI PDF', openLocal: 'Otwórz plik lokalny', + dropToOpenTitle: 'Upuść, aby otworzyć', greetMorning: 'Dzień dobry', greetAfternoon: 'Dzień dobry', greetEvening: 'Dobry wieczór', @@ -2879,6 +2893,7 @@ export const strings = { newMarkdown: 'AI Markdown', newPdf: 'AI PDF', openLocal: 'Lokaal bestand openen', + dropToOpenTitle: 'Loslaten om te openen', greetMorning: 'Goedemorgen', greetAfternoon: 'Goedemiddag', greetEvening: 'Goedenavond', @@ -3075,6 +3090,7 @@ export const strings = { newMarkdown: 'AI Markdown', newPdf: 'AI PDF', openLocal: 'Buka Fail Setempat', + dropToOpenTitle: 'Lepaskan untuk membuka', greetMorning: 'Selamat pagi', greetAfternoon: 'Selamat tengah hari', greetEvening: 'Selamat petang', @@ -3270,6 +3286,7 @@ export const strings = { newMarkdown: 'AI Markdown', newPdf: 'AI PDF', openLocal: 'פתיחת קובץ מקומי', + dropToOpenTitle: 'שחרר כדי לפתוח', greetMorning: 'בוקר טוב', greetAfternoon: 'צהריים טובים', greetEvening: 'ערב טוב', @@ -3461,6 +3478,7 @@ export const strings = { newMarkdown: 'AI Markdown', newPdf: 'AI PDF', openLocal: 'स्थानीय फ़ाइल खोलें', + dropToOpenTitle: 'खोलने के लिए छोड़ें', greetMorning: 'सुप्रभात', greetAfternoon: 'नमस्ते', greetEvening: 'शुभ संध्या', @@ -3657,6 +3675,7 @@ export const strings = { newMarkdown: 'AI Markdown', newPdf: 'AI PDF', openLocal: '開啟本機檔案', + dropToOpenTitle: '放開以開啟檔案', greetMorning: '早安', greetAfternoon: '午安', greetEvening: '晚安', diff --git a/apps/shell/tests/dropped-files.test.ts b/apps/shell/tests/dropped-files.test.ts new file mode 100644 index 0000000..07cd51e --- /dev/null +++ b/apps/shell/tests/dropped-files.test.ts @@ -0,0 +1,75 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { handleDroppedFiles } from '../src/main/dropped-files' +import type { DroppedFilesDeps } from '../src/main/dropped-files' + +function fakeDeps(overrides: Partial = {}): DroppedFilesDeps & { + opened: string[] + revealed: ReturnType + warned: string[] +} { + const opened: string[] = [] + const revealed = vi.fn() + const warned: string[] = [] + return { + opened, + revealed, + warned, + openDocumentPath: vi.fn((path: string) => { + opened.push(path) + return true + }), + revealShellWindow: revealed, + showWarning: vi.fn((message: string) => { + warned.push(message) + }), + unsupportedMessage: (exts) => `unsupported: ${exts.join(', ')}`, + ...overrides, + } +} + +describe('handleDroppedFiles', () => { + beforeEach(() => vi.clearAllMocks()) + + it('opens every supported path and reveals the shell', () => { + const deps = fakeDeps() + handleDroppedFiles(['/tmp/a.docx', '/tmp/b.xlsx'], deps) + expect(deps.opened).toEqual(['/tmp/a.docx', '/tmp/b.xlsx']) + expect(deps.revealed).toHaveBeenCalledOnce() + expect(deps.warned).toEqual([]) + }) + + it('still reveals the shell when a path is already open in a tab', () => { + const deps = fakeDeps({ + // routeDocumentPath activates the existing tab and returns true either way + openDocumentPath: vi.fn(() => true), + }) + handleDroppedFiles(['/tmp/a.docx'], deps) + expect(deps.revealed).toHaveBeenCalledOnce() + }) + + it('warns once with the combined extensions for known-unsupported drops', () => { + const deps = fakeDeps() + handleDroppedFiles(['/tmp/old.doc', '/tmp/deck.pages', '/tmp/note.rtf'], deps) + expect(deps.opened).toEqual([]) + expect(deps.revealed).not.toHaveBeenCalled() + expect(deps.warned).toEqual(['unsupported: doc, pages, rtf']) + }) + + it('opens the supported files and warns about the rest in a mixed drop', () => { + const deps = fakeDeps() + handleDroppedFiles(['/tmp/new.docx', '/tmp/old.doc'], deps) + expect(deps.opened).toEqual(['/tmp/new.docx']) + expect(deps.revealed).toHaveBeenCalledOnce() + expect(deps.warned).toEqual(['unsupported: doc']) + }) + + it('ignores junk payloads and unrecognized file types entirely', () => { + const deps = fakeDeps() + handleDroppedFiles(null, deps) + handleDroppedFiles(['/tmp/photo.png', 42, ''], deps) + expect(deps.opened).toEqual([]) + expect(deps.revealed).not.toHaveBeenCalled() + expect(deps.warned).toEqual([]) + }) +}) diff --git a/apps/shell/tests/preload-analytics.test.ts b/apps/shell/tests/preload-analytics.test.ts index 8bbd708..b8883dd 100644 --- a/apps/shell/tests/preload-analytics.test.ts +++ b/apps/shell/tests/preload-analytics.test.ts @@ -20,6 +20,9 @@ vi.mock('electron', () => ({ on: electronMocks.on, removeListener: electronMocks.removeListener, }, + // the preload imports @genoffice/electron-utils (drop-open bridge), which + // binds webUtils at module scope even though node env never installs it + webUtils: { getPathForFile: () => '' }, })) import '../src/preload/index' diff --git a/apps/slides/electron.vite.config.ts b/apps/slides/electron.vite.config.ts index cbff21a..89905cb 100644 --- a/apps/slides/electron.vite.config.ts +++ b/apps/slides/electron.vite.config.ts @@ -50,7 +50,8 @@ export default defineConfig({ ], }, preload: { - plugins: [externalizeDepsPlugin()], + // electron-utils ships raw TS source — must be bundled, not left external + plugins: [externalizeDepsPlugin({ exclude: ['@genoffice/electron-utils'] })], }, renderer: { resolve: { alias: workspaceAlias }, diff --git a/apps/slides/src/preload/index.ts b/apps/slides/src/preload/index.ts index ba7b361..0d70e69 100644 --- a/apps/slides/src/preload/index.ts +++ b/apps/slides/src/preload/index.ts @@ -2,6 +2,7 @@ import { contextBridge, ipcRenderer, webUtils } from 'electron' import type { IpcRendererEvent } from 'electron' import type { RenderSlide } from '@genoffice/pptx-render' import type { ProjectApi } from '@genoffice/project-store' +import { installDropOpenBridge } from '@genoffice/electron-utils/drop-open' import type { AddChartOp, AddElementOp, @@ -448,3 +449,6 @@ const projectApi: ProjectApi = { getTimeline: (args) => ipcRenderer.invoke('project:timeline', args), } contextBridge.exposeInMainWorld('projectApi', projectApi) + +// open documents dragged from the OS onto this tab as a new shell tab +installDropOpenBridge() diff --git a/packages/electron-utils/package.json b/packages/electron-utils/package.json index b9761ce..2952630 100644 --- a/packages/electron-utils/package.json +++ b/packages/electron-utils/package.json @@ -6,7 +6,8 @@ "type": "module", "description": "Shared helpers for the Electron main processes (no Electron dependency, pure TS)", "exports": { - ".": "./src/index.ts" + ".": "./src/index.ts", + "./drop-open": "./src/drop-open.ts" }, "scripts": { "typecheck": "tsc --noEmit", diff --git a/packages/electron-utils/src/drop-open.ts b/packages/electron-utils/src/drop-open.ts new file mode 100644 index 0000000..5fb18a7 --- /dev/null +++ b/packages/electron-utils/src/drop-open.ts @@ -0,0 +1,119 @@ +/// Drag & drop a local document file anywhere in the app window to open it. +/// +/// Renderers share one main process (the shell hosts every editor view), so the +/// bridge only has to resolve dropped files to paths and send them over ONE +/// channel; the shell routes each path through its normal open pipeline. The +/// installer runs inside preloads, where `webUtils.getPathForFile` is callable +/// and DOM listeners see real OS drops — paths never cross contextBridge. +/// +/// Ownership contract with page-level drop zones: a zone that handles its own +/// file drops (AI attachment panels, slides image insert) cancels the event +/// before it bubbles here (`defaultPrevented`), and this bridge stays out of +/// the way. Text/media drags without OS files are untouched. +import { ipcRenderer, webUtils } from 'electron' + +export const DROP_OPEN_CHANNEL = 'app:open-dropped-files' + +/** Extensions routed by apps/shell routeDocumentPath — keep in sync there and + * with OPEN_DIALOG_EXTENSIONS / OPEN_LOCAL_EXTENSIONS on the home screen. */ +export const OPENABLE_DOC_RE = /\.(docx|xlsx|xlsm|xls|csv|pptx|pdf|md|markdown)$/i + +/** Recognized-but-unsupported formats: kept in the sent payload so the shell + * can show its "not supported" dialog instead of dropping them silently. + * Mirrors UNSUPPORTED_DOC_RE in apps/shell/src/main/index.ts. */ +export const KNOWN_UNSUPPORTED_DOC_RE = /\.(doc|rtf|odt|ppt|pps|odp|ods|xlsb|pages|key|numbers)$/i + +/** upper bound on how many files one drop may ask to open */ +const MAX_DROPPED_FILES = 20 + +/** the resolver signature webUtils.getPathForFile satisfies; injectable for tests */ +type PathResolver = (file: File) => string + +/** + * Resolve an event's dropped files to local paths. Returns null when the drag + * carries no OS files at all (internal text/element drags), or [] when it does + * but none resolve (directories, virtual entries) — both mean "not ours". + */ +export function droppableFilePaths( + ev: Pick, + getPathForFile: PathResolver, +): string[] | null { + const transfer = ev.dataTransfer + if (!transfer || !transfer.types.includes('Files')) return null + const paths: string[] = [] + for (const file of Array.from(transfer.files)) { + // non-empty guard covers virtual entries (e.g. page-referenced blobs) that resolve to '' + const path = getPathForFile(file).trim() + if (path) paths.push(path) + } + return paths +} + +/** + * Sanitize + classify a raw IPC payload: strings only, trimmed, deduped, + * capped, then split into directly-openable paths and known-unsupported + * extensions (unique, first-seen order). Anything unrecognized (.png, .zip, + * nonexistent junk from a hostile sender) falls out silently. + */ +export function partitionDropPayload(raw: unknown): { + supported: string[] + unsupportedExts: string[] +} { + const supported: string[] = [] + const unsupportedExts: string[] = [] + if (!Array.isArray(raw)) return { supported, unsupportedExts } + const seen = new Set() + for (const entry of raw as unknown[]) { + if (typeof entry !== 'string') continue + const path = entry.trim() + if (!path || seen.has(path)) continue + seen.add(path) + if (OPENABLE_DOC_RE.test(path)) { + // keep scanning for unsupported entries even after hitting the open cap + if (supported.length < MAX_DROPPED_FILES) supported.push(path) + } else if (KNOWN_UNSUPPORTED_DOC_RE.test(path)) { + const ext = path.slice(path.lastIndexOf('.') + 1).toLowerCase() + if (!unsupportedExts.includes(ext)) unsupportedExts.push(ext) + } + } + return { supported, unsupportedExts } +} + +/** Symbol.for keeps repeated installs idempotent when several bundled copies of + * this module end up in one process (mirrors navigation-guard). */ +const INSTALLED = Symbol.for('genoffice.drop-open-installed') + +/** + * Preload-side hook: makes `drop` fire for document drags anywhere in the + * page and forwards recognized files to the shell's router. Intentionally not + * exposed through contextBridge — page code cannot spoof these events with + * arbitrary paths because payload construction happens here in the preload + * world only. + */ +export function installDropOpenBridge(): void { + const holder = globalThis as Record + if (typeof window === 'undefined' || holder[INSTALLED]) return + holder[INSTALLED] = true + + // Without a canceled dragover Chromium never fires `drop`; canceling here is + // what lets a document-drag land anywhere that isn't already a drop zone. + window.addEventListener('dragover', (ev: DragEvent) => { + if (ev.defaultPrevented) return + if (!ev.dataTransfer?.types.includes('Files')) return + ev.preventDefault() + }) + + window.addEventListener('drop', (ev: DragEvent) => { + // first: something in the page already claimed this drop (image insert, + // AI attachments...) — never second-guess it + if (ev.defaultPrevented) return + const paths = droppableFilePaths(ev, (file) => webUtils.getPathForFile(file)) + if (!paths) return + // only recognized documents ride along; stray images/folders are swallowed + // here so they neither navigate the page nor produce open attempts + const payload = paths.filter((p) => OPENABLE_DOC_RE.test(p) || KNOWN_UNSUPPORTED_DOC_RE.test(p)) + ev.preventDefault() + if (payload.length === 0) return + ipcRenderer.send(DROP_OPEN_CHANNEL, payload.slice(0, MAX_DROPPED_FILES)) + }) +} diff --git a/packages/electron-utils/src/index.ts b/packages/electron-utils/src/index.ts index 8c855e5..b3b661c 100644 --- a/packages/electron-utils/src/index.ts +++ b/packages/electron-utils/src/index.ts @@ -24,6 +24,14 @@ export { type PathProvider, } from './default-save-dir' export { installNavigationGuard } from './navigation-guard' +export { + DROP_OPEN_CHANNEL, + droppableFilePaths, + installDropOpenBridge, + KNOWN_UNSUPPORTED_DOC_RE, + OPENABLE_DOC_RE, + partitionDropPayload, +} from './drop-open' export { safeExternalUrl, type SafeExternalUrlOptions } from './safe-external-url' export { fetchWithSsrfGuard, diff --git a/packages/electron-utils/tests/drop-open.test.ts b/packages/electron-utils/tests/drop-open.test.ts new file mode 100644 index 0000000..d51a1bc --- /dev/null +++ b/packages/electron-utils/tests/drop-open.test.ts @@ -0,0 +1,264 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { + DROP_OPEN_CHANNEL, + droppableFilePaths, + installDropOpenBridge, + partitionDropPayload, +} from '../src/drop-open' + +// ---- electron mock (module under test imports ipcRenderer/webUtils eagerly) ---- + +const electronMocks = vi.hoisted(() => ({ + send: vi.fn(), + getPathForFile: vi.fn(), +})) + +vi.mock('electron', () => ({ + ipcRenderer: { send: electronMocks.send }, + webUtils: { getPathForFile: electronMocks.getPathForFile }, +})) + +// ---- tiny DOM fakes ---- + +interface RecordedEvent { + type: string + handler: (ev: unknown) => void +} + +/** minimal stand-in for `window` recording every listener registration */ +function fakeWindow(): { + recorded: RecordedEvent[] + fire(type: string, ev: Record): void +} { + const recorded: RecordedEvent[] = [] + const target = { + recorded, + addEventListener(type: string, handler: (ev: unknown) => void) { + recorded.push({ type, handler }) + }, + removeEventListener() {}, + fire(type: string, ev: Record) { + for (const r of recorded.filter((r) => r.type === type)) r.handler(ev) + }, + } + return target +} + +type GlobalWithWindow = { window?: unknown } + +/** the idempotence flag lives on globalThis; clear it between installs */ +function resetInstallFlag(): void { + delete (globalThis as Record)[ + Symbol.for('genoffice.drop-open-installed') + ] +} + +/** DragEvent-shaped literal; only the fields the bridge touches are provided */ +function fileDrag(paths: Array, prevented = false): Record { + return { + defaultPrevented: prevented, + preventDefault: vi.fn(), + stopPropagation: vi.fn(), + dataTransfer: { + types: ['Files'], + files: paths.map((p) => ({ name: p.split('/').pop() ?? '?' })), + }, + } +} + +beforeEach(() => { + electronMocks.send.mockClear() + electronMocks.getPathForFile.mockReset() + resetInstallFlag() +}) + +describe('droppableFilePaths', () => { + const resolveByName = + (map: Record) => + (file: File): string => + map[(file as { name: string }).name] ?? '' + + it('returns null when there is no dataTransfer or no Files kind', () => { + expect(droppableFilePaths({ dataTransfer: null }, () => '')).toBeNull() + expect( + droppableFilePaths( + { dataTransfer: { types: ['text/plain'], files: [] } as unknown as DataTransfer }, + () => '', + ), + ).toBeNull() + }) + + it('maps every dropped file through the resolver in order', () => { + const result = droppableFilePaths(fileDrag(['a.docx', 'b.pdf']) as never, () => '/tmp') + expect(result).toEqual(['/tmp', '/tmp']) + }) + + it('drops empty resolutions from virtual entries instead of failing', () => { + const result = droppableFilePaths( + fileDrag(['shot.png', 'doc.docx']) as never, + resolveByName({ 'shot.png': '', 'doc.docx': '/tmp/doc.docx' }), + ) + expect(result).toEqual(['/tmp/doc.docx']) + }) +}) + +describe('partitionDropPayload', () => { + it('rejects non-array payloads outright', () => { + expect(partitionDropPayload(null)).toEqual({ supported: [], unsupportedExts: [] }) + expect(partitionDropPayload('a.docx')).toEqual({ supported: [], unsupportedExts: [] }) + expect(partitionDropPayload({ 0: 'a.docx' })).toEqual({ supported: [], unsupportedExts: [] }) + }) + + it('ignores non-string entries, whitespace-only strings, and duplicates', () => { + const result = partitionDropPayload([' a.docx ', 'a.docx', 42, null, '', ' ', 'b.xlsx']) + expect(result.supported).toEqual(['a.docx', 'b.xlsx']) + expect(result.unsupportedExts).toEqual([]) + }) + + it('classifies openable extensions case-insensitively', () => { + const result = partitionDropPayload(['REPORT.DOCX', 'data.CSV', 'notes.MarkDown']) + expect(result.supported).toEqual(['REPORT.DOCX', 'data.CSV', 'notes.MarkDown']) + }) + + it('collects known-unsupported extensions uniquely, first-seen order', () => { + const result = partitionDropPayload(['old.doc', 'x.pages', 'y.rtf', 'z.doc']) + expect(result.supported).toEqual([]) + expect(result.unsupportedExts).toEqual(['doc', 'pages', 'rtf']) + }) + + it('caps the number of openable files at 20', () => { + const many = Array.from({ length: 30 }, (_, i) => `/tmp/f${i}.docx`) + expect(partitionDropPayload(many).supported.length).toBe(20) + }) + + it('keeps the original order so the last file wins activation', () => { + const result = partitionDropPayload(['/a.docx', '/b/c.csv', '/d.md']) + expect(result.supported).toEqual(['/a.docx', '/b/c.csv', '/d.md']) + }) +}) + +describe('installDropOpenBridge', () => { + function install(): ReturnType { + const win = fakeWindow() + ;(globalThis as GlobalWithWindow).window = win + installDropOpenBridge() + return win + } + + function uninstall(win: ReturnType): void { + delete (globalThis as GlobalWithWindow).window + void win + resetInstallFlag() + } + + it('registers exactly one dragover and one drop listener', () => { + const win = install() + try { + expect(win.recorded.map((r) => r.type)).toEqual(['dragover', 'drop']) + } finally { + uninstall(win) + } + }) + + it('is idempotent within the same process', () => { + const win = install() + try { + installDropOpenBridge() + expect(win.recorded.length).toBe(2) + } finally { + uninstall(win) + } + }) + + it('cancels dragover for file drags so Chromium fires drop', () => { + const win = install() + try { + const ev = fileDrag(['a.docx']) + win.fire('dragover', ev) + expect(ev.preventDefault).toHaveBeenCalledOnce() + } finally { + uninstall(win) + } + }) + + it('leaves dragover alone for non-file drags and page-handled events', () => { + const win = install() + try { + const text = { + defaultPrevented: false, + preventDefault: vi.fn(), + dataTransfer: { types: ['text/plain'], files: [] }, + } + win.fire('dragover', text) + expect(text.preventDefault).not.toHaveBeenCalled() + + const claimed = fileDrag(['a.docx'], true) + win.fire('dragover', claimed) + expect(claimed.preventDefault).not.toHaveBeenCalled() + } finally { + uninstall(win) + } + }) + + it('sends resolved document paths over the channel and cancels the native drop', async () => { + electronMocks.getPathForFile.mockImplementation((f: { name: string }) => `/tmp/${f.name}`) + const win = install() + try { + const ev = fileDrag(['report.docx', 'plan.md', 'photo.png']) + win.fire('drop', ev) + await vi.waitFor(() => + expect(electronMocks.send).toHaveBeenCalledWith(DROP_OPEN_CHANNEL, [ + '/tmp/report.docx', + '/tmp/plan.md', + ]), + ) + expect(ev.preventDefault).toHaveBeenCalled() + } finally { + uninstall(win) + } + }) + + it('stays silent when the page already handled the drop', async () => { + electronMocks.getPathForFile.mockImplementation((f: { name: string }) => `/tmp/${f.name}`) + const win = install() + try { + const ev = fileDrag(['report.docx'], true) + win.fire('drop', ev) + await Promise.resolve() + expect(electronMocks.send).not.toHaveBeenCalled() + } finally { + uninstall(win) + } + }) + + it('swallows unresolvable/non-document drops without sending anything', async () => { + electronMocks.getPathForFile.mockReturnValue('') + const win = install() + try { + const virtual = fileDrag(['remote.html']) + win.fire('drop', virtual) + const images = fileDrag(['a.png', 'b.jpg']) + win.fire('drop', images) + await Promise.resolve() + expect(electronMocks.send).not.toHaveBeenCalled() + expect(images.preventDefault).toHaveBeenCalled() + } finally { + uninstall(win) + } + }) + + it('forwards known-unsupported docs too so the shell can explain why', async () => { + electronMocks.getPathForFile.mockImplementation((f: { name: string }) => `/tmp/${f.name}`) + const win = install() + try { + const ev = fileDrag(['legacy.doc']) + win.fire('drop', ev) + await vi.waitFor(() => + expect(electronMocks.send).toHaveBeenCalledWith(DROP_OPEN_CHANNEL, ['/tmp/legacy.doc']), + ) + } finally { + uninstall(win) + } + }) +})