feat(shell): open documents dropped onto the window (#161)
Dropping a local file from Explorer/Finder anywhere over the app previously did nothing visible: the navigation guard blocks Chromium's default navigate-to-file, so drops were silently swallowed. Add a preload-side bridge (@genoffice/electron-utils/drop-open, installed by every surface's preload) that resolves dropped files via webUtils and forwards recognized documents to the shell over one IPC channel. The shell routes each path through the normal File > Open pipeline, reveals its window when the drop landed in a detached editor, and shows the existing "not supported" dialog for known legacy formats. Page-level drop zones that cancel their events (AI attachment panels, slides image insert) keep priority. While files hover, Home shows a pointer-events-none drop overlay (tokens only, i18n key in all 19 locales). The bridge module gets its own package subpath export so sandboxed preloads bundle only it — importing the barrel would pull node builtins into sandboxed preloads (bundled) or leave a bare require (externalized), both fatal there. Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -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",
|
||||
|
||||
@@ -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<DragEvent, 'dataTransfer'>,
|
||||
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<string>()
|
||||
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<symbol, boolean | undefined>
|
||||
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))
|
||||
})
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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<string, unknown>): void
|
||||
} {
|
||||
const recorded: RecordedEvent[] = []
|
||||
const target = {
|
||||
recorded,
|
||||
addEventListener(type: string, handler: (ev: unknown) => void) {
|
||||
recorded.push({ type, handler })
|
||||
},
|
||||
removeEventListener() {},
|
||||
fire(type: string, ev: Record<string, unknown>) {
|
||||
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 | string, unknown>)[
|
||||
Symbol.for('genoffice.drop-open-installed')
|
||||
]
|
||||
}
|
||||
|
||||
/** DragEvent-shaped literal; only the fields the bridge touches are provided */
|
||||
function fileDrag(paths: Array<string | ''>, prevented = false): Record<string, unknown> {
|
||||
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<string, string>) =>
|
||||
(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<typeof fakeWindow> {
|
||||
const win = fakeWindow()
|
||||
;(globalThis as GlobalWithWindow).window = win
|
||||
installDropOpenBridge()
|
||||
return win
|
||||
}
|
||||
|
||||
function uninstall(win: ReturnType<typeof fakeWindow>): 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)
|
||||
}
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user